### Install Dependencies and Start Optimization Loop Source: https://github.com/robmorgan/timestretch-rs/blob/main/optimize/README.md Installs Python dependencies, generates reference files, and starts the optimization loop using make commands. ```bash cd optimize make install-deps # Install Python libraries make refs # Generate reference files (needs rubberband-cli) make loop # Start the optimization loop ``` -------------------------------- ### Run DJ Mix Example Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Execute the DJ mix example using Cargo. This demonstrates a streaming DJ transition. ```sh cargo run --example dj_mix # Streaming DJ transition demo ``` -------------------------------- ### Run Benchmark Quality Example Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Execute the benchmark quality example using Cargo. This is an offline helper for benchmarking audio quality. ```sh cargo run --example benchmark_quality # Offline quality benchmark helper ``` -------------------------------- ### Run Realtime Stream Example Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Execute the realtime stream example using Cargo. This showcases the streaming API. ```sh cargo run --example realtime_stream # Streaming API demo ``` -------------------------------- ### Run Sample Halftime Example Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Execute the sample halftime example using Cargo. This applies a 2x halftime effect to audio. ```sh cargo run --example sample_halftime # 2x halftime effect ``` -------------------------------- ### Run Pitch Shift Example Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Execute the pitch shift example using Cargo. This demonstrates pitch shifting capabilities. ```sh cargo run --example pitch_shift # Pitch shifting demo ``` -------------------------------- ### Run DJ Beatmatch Example Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Execute the DJ beatmatch example using Cargo. This example synchronizes tempo between 126 and 128 BPM. ```sh cargo run --example dj_beatmatch # 126 → 128 BPM tempo sync ``` -------------------------------- ### Run Basic Time Stretch Example Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Execute the basic time stretch example using Cargo. This demonstrates a simple time stretching operation. ```sh cargo run --example basic_stretch # Simple time stretch ``` -------------------------------- ### Install wasm-pack Source: https://github.com/robmorgan/timestretch-rs/blob/main/web/README.md Install the wasm-pack tool for building Rust WebAssembly projects. ```bash cargo install wasm-pack ``` -------------------------------- ### Create Audio Directories Source: https://github.com/robmorgan/timestretch-rs/blob/main/benchmarks/README.md Use this command to create the necessary audio directories for the benchmark system. Ensure you have the `benchmarks/audio/originals` and `benchmarks/audio/references` directories set up. ```bash mkdir -p benchmarks/audio/originals benchmarks/audio/references ``` -------------------------------- ### Run HTTP server Source: https://github.com/robmorgan/timestretch-rs/blob/main/web/README.md Serve the web directory using Python's built-in HTTP server to host the demo locally. ```bash cd web python3 -m http.server 8080 ``` -------------------------------- ### Run Benchmark QA Harness Source: https://github.com/robmorgan/timestretch-rs/blob/main/qa/README.md Execute the benchmark QA harness with the 'qa-harnesses' feature and '--nocapture' option. Use the '--release' flag for optimized builds. ```bash cargo test --features qa-harnesses --release --test benchmarks -- --nocapture ``` -------------------------------- ### Run Reference Quality QA Harness Source: https://github.com/robmorgan/timestretch-rs/blob/main/qa/README.md Execute the reference quality QA harness with the 'qa-harnesses' feature and '--nocapture' option. ```bash cargo test --features qa-harnesses --test reference_quality -- --nocapture ``` -------------------------------- ### Generate Ableton References Source: https://github.com/robmorgan/timestretch-rs/blob/main/optimize/ableton/README.md Execute the make command to automate the process of opening Ableton projects, exporting audio, and validating the output. This process runs sequentially for each track. ```bash make ableton-refs ``` -------------------------------- ### Run Streaming Quality Tests with QA Harnesses Source: https://github.com/robmorgan/timestretch-rs/blob/main/RELEASE_CHECKLIST.md Execute streaming quality tests with QA harnesses enabled for release verification. ```bash cargo test --features qa-harnesses --release --test streaming_quality -- --nocapture ``` -------------------------------- ### Full Pipeline Execution Source: https://github.com/robmorgan/timestretch-rs/blob/main/optimize/ableton/README.md Run the full pipeline by executing 'make full', which includes generating Ableton references, library outputs, and scoring. Alternatively, use 'make compare' to skip Ableton rendering and proceed directly to scoring library outputs. ```bash make full # ableton-refs + library-refs + score ``` ```bash make compare # library-refs + score (skip Ableton rendering) ``` -------------------------------- ### Run Quality Gates QA Harness Source: https://github.com/robmorgan/timestretch-rs/blob/main/qa/README.md Execute the quality gates QA harness with the 'qa-harnesses' feature and '--nocapture' option. ```bash cargo test --features qa-harnesses --test quality_gates -- --nocapture ``` -------------------------------- ### Run Ad-hoc Reference-Quality Comparison Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Execute an ad-hoc reference-quality run that is non-strict and uses a short window (5 seconds). ```sh TIMESTRETCH_REFERENCE_MAX_SECONDS=5 cargo test --features qa-harnesses --test reference_quality -- --nocapture ``` -------------------------------- ### Build Documentation Without Warnings Source: https://github.com/robmorgan/timestretch-rs/blob/main/CLAUDE.md Generates documentation for the project, excluding dependencies, and treats documentation warnings as errors. This ensures that generated documentation is clean and informative. ```bash RUSTDOCFLAGS="-D warnings" cargo doc --no-deps ``` -------------------------------- ### Score Against Ableton Source: https://github.com/robmorgan/timestretch-rs/blob/main/optimize/ableton/README.md Use this make command to score the library's output against Ableton's rendered references. ```bash make score-ableton ``` -------------------------------- ### Run Realtime Allocations Tests Source: https://github.com/robmorgan/timestretch-rs/blob/main/RELEASE_CHECKLIST.md Execute realtime allocation tests to verify streaming route quality gates. ```bash cargo test --test realtime_allocations -- --nocapture ``` -------------------------------- ### Run Quality-Gate Benchmark Subset Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Execute the quality-gate benchmark subset, which is enforced in CI. Use a release build for accurate results. ```sh cargo test --features qa-harnesses --release --test quality_gates -- --nocapture ``` -------------------------------- ### Tempo-Aware Streaming with StreamProcessor Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Initialize a StreamProcessor for tempo-aware streaming and dynamically change the target tempo during playback. Reports current target BPM and latency. ```rust use timestretch::StreamProcessor; let mut processor = StreamProcessor::from_tempo(126.0, 128.0, 44100, 2); // Move the target deck tempo during playback processor.set_tempo(130.0); println!( "Current target BPM: {:.2}, latency: {:.1} ms", processor.target_bpm().unwrap_or(0.0), processor.latency_secs() * 1000.0 ); ``` -------------------------------- ### Inspect Generated Project XML Source: https://github.com/robmorgan/timestretch-rs/blob/main/optimize/ableton/README.md If you encounter issues with the warp mode, inspect the generated Ableton project file using this command. ```bash python scripts/create_als_project.py inspect generated_project.als ``` -------------------------------- ### Scoring Integration with Ableton References Source: https://github.com/robmorgan/timestretch-rs/blob/main/optimize/ableton/README.md Integrate scoring by using the 'optimize/scripts/score.py' script with the '--ref-source ableton' option. This allows comparison against Ableton Complex Pro output using the same metrics as rubberband scoring. ```bash cd optimize python scripts/score.py --ref-source ableton \ --ableton-manifest ableton/ableton_manifest.json \ --batch ableton/logs/scores.json ``` -------------------------------- ### Run Baseline Script Source: https://github.com/robmorgan/timestretch-rs/blob/main/benchmarks/baselines/README.md Execute the script to generate baseline JSON reports. ```bash ./benchmarks/run_m0_baseline.sh ``` -------------------------------- ### Run M0 Baseline Benchmark Source: https://github.com/robmorgan/timestretch-rs/blob/main/benchmarks/README.md Executes the M0 baseline benchmark with strict validation and archiving. This command enables strict validation, sets a fixed analysis window, and processes audio files with all EDM presets, outputting metrics and archiving results. ```bash # M0 baseline command (strict validation + archive) ./benchmarks/run_m0_baseline.sh ``` -------------------------------- ### Run Reference-Quality Comparison Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Perform a reference-quality comparison against an external Rubber Band render. Requires strict corpus and sets TIMESTRETCH_REFERENCE_MAX_SECONDS to 30. ```sh TIMESTRETCH_STRICT_REFERENCE_BENCHMARK=1 TIMESTRETCH_REFERENCE_MAX_SECONDS=30 cargo test --features qa-harnesses --test reference_quality -- --nocapture ``` -------------------------------- ### Run Ignored Quality Benchmark QA Harness Source: https://github.com/robmorgan/timestretch-rs/blob/main/qa/README.md Execute the ignored quality benchmark QA harness with the 'qa-harnesses' feature, '--ignored' flag, and '--nocapture' option. ```bash cargo test --features qa-harnesses --test quality_benchmark -- --ignored --nocapture ``` -------------------------------- ### Compare with External Rubber Band Render Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Compare a single scenario against an external Rubber Band render. Specify input/output WAV files and the desired ratio using environment variables. ```sh TIMESTRETCH_RUBBERBAND_ORIGINAL_WAV=benchmarks/audio/originals/loop.wav \ TIMESTRETCH_RUBBERBAND_REFERENCE_WAV=benchmarks/audio/references/loop_rubberband.wav \ TIMESTRETCH_RUBBERBAND_RATIO=1.113043478 \ cargo test --features qa-harnesses --test rubberband_comparison -- --nocapture ``` -------------------------------- ### Build WebAssembly module Source: https://github.com/robmorgan/timestretch-rs/blob/main/web/README.md Build the Rust code into a WebAssembly module for the web target. ```bash cd web wasm-pack build --target web --out-dir pkg ``` -------------------------------- ### Generate Library Outputs Source: https://github.com/robmorgan/timestretch-rs/blob/main/optimize/ableton/README.md Run the make command to generate outputs from the timestretch-cli tool in both batch and streaming modes. ```bash make library-refs ``` -------------------------------- ### Dry Run Manifest Generation Source: https://github.com/robmorgan/timestretch-rs/blob/main/optimize/ableton/README.md Use 'make manifest' to perform a dry run and print a list of what would be rendered without actually performing the rendering. ```bash make manifest # Print what would be rendered ``` -------------------------------- ### Fixed-Buffer Realtime Callbacks with StreamProcessor Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Utilize deterministic APIs for fixed-buffer audio processing where the host manages buffers. Provides bounded output budgets for predictable memory usage. ```rust use timestretch::{EdmPreset, StreamProcessor, StretchParams}; let params = StretchParams::new(1.02) .with_preset(EdmPreset::DjBeatmatch) .with_sample_rate(44_100) .with_channels(2); let mut processor = StreamProcessor::new(params); let input_chunk = vec![0.0f32; 256 * 2]; let callback_capacity = processor .max_next_process_interleaved_output_samples(input_chunk.len()) .unwrap(); let mut callback_output = vec![0.0f32; callback_capacity]; let written = processor .process_interleaved_into(&input_chunk, &mut callback_output) .unwrap(); host_submit(&callback_output[..written]); loop { let written = processor .flush_interleaved_into(&mut callback_output) .unwrap(); if written == 0 { break; } host_submit(&callback_output[..written]); } ``` -------------------------------- ### Enforce Strict Callback-Time Budget Source: https://github.com/robmorgan/timestretch-rs/blob/main/benchmarks/README.md Run the quality gate tests in release mode with a strict worst-case callback-time budget. This is useful for performance-critical scenarios. ```bash TIMESTRETCH_STRICT_CALLBACK_BUDGET=1 cargo test --features qa-harnesses --release --test quality_gates -- --nocapture ``` -------------------------------- ### Run External Rubber Band Comparison Benchmark Source: https://github.com/robmorgan/timestretch-rs/blob/main/benchmarks/README.md Compares timestretch-rs against an external Rubber Band render. This benchmark requires specifying original and reference WAV file paths and the stretch ratio via environment variables. It outputs comparison reports and WAV files. ```bash TIMESTRETCH_RUBBERBAND_ORIGINAL_WAV=benchmarks/audio/originals/my-loop.wav \ TIMESTRETCH_RUBBERBAND_REFERENCE_WAV=benchmarks/audio/references/my-loop_rubberband.wav \ TIMESTRETCH_RUBBERBAND_RATIO=1.024 \ cargo test --features qa-harnesses --test rubberband_comparison -- --nocapture ``` -------------------------------- ### WAV File I/O and Stretching Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Read audio data from WAV files, perform stretching operations, and write the results to new WAV files in various bit depths (16-bit, 24-bit, or float). Provides convenience functions for common workflows. ```rust use timestretch::io::wav; // Read a WAV file let buffer = wav::read_wav_file("input.wav").unwrap(); // Stretch it let params = timestretch::StretchParams::new(2.0) .with_preset(timestretch::EdmPreset::Halftime); let output = timestretch::stretch_buffer(&buffer, ¶ms).unwrap(); // Write the result (16-bit, 24-bit, or float) wav::write_wav_file_16bit("output_16.wav", &output).unwrap(); wav::write_wav_file_24bit("output_24.wav", &output).unwrap(); wav::write_wav_file_float("output_32.wav", &output).unwrap(); // Or use the one-liner convenience API timestretch::stretch_wav_file("input.wav", "output.wav", ¶ms).unwrap(); ``` -------------------------------- ### Check Code Formatting Source: https://github.com/robmorgan/timestretch-rs/blob/main/CLAUDE.md Verifies that the code is formatted according to rustfmt standards. This check ensures consistent code style across the project. ```bash cargo fmt --all --check ``` -------------------------------- ### Low-Latency Tempo Constructor for StreamProcessor Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Create a StreamProcessor with low-latency settings, ensuring the processing latency is below a specified threshold (e.g., 40ms). ```rust use timestretch::StreamProcessor; let mut processor = StreamProcessor::try_from_tempo_low_latency(126.0, 128.0, 44100, 2) .expect("valid BPM inputs"); assert!(processor.latency_secs() * 1000.0 < 40.0); ``` -------------------------------- ### Run All Tests Source: https://github.com/robmorgan/timestretch-rs/blob/main/CLAUDE.md Executes all tests across all targets. This check runs on Ubuntu, macOS, and Windows with stable Rust, and on Ubuntu with the Minimum Supported Rust Version (MSRV). ```bash cargo test --all-targets ``` -------------------------------- ### WAV File Convenience Functions Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Convenience functions for reading, processing (stretching or pitch shifting), and writing WAV audio files. ```APIDOC ## WAV File Convenience ### `stretch_wav_file(input, output, &StretchParams)` **Description**: Reads a WAV file, stretches its audio content using the provided parameters, and writes the result to an output WAV file. ### `stretch_to_bpm_wav_file(input, output, &StretchParams, source_bpm, target_bpm)` **Description**: Reads a WAV file, performs BPM-based stretching to a target BPM, and writes the result to an output WAV file. ### `stretch_to_bpm_auto_wav_file(input, output, &StretchParams, target_bpm)` **Description**: Reads a WAV file, automatically detects the source BPM, performs stretching to the target BPM, and writes the result to an output WAV file. ### `pitch_shift_wav_file(input, output, &StretchParams, factor)` **Description**: Reads a WAV file, shifts its pitch by a given factor without changing duration, and writes the result to an output WAV file. ``` -------------------------------- ### Decompress Ableton ALS Project Source: https://github.com/robmorgan/timestretch-rs/blob/main/optimize/ableton/README.md Use this script to decompress an Ableton Live project file (.als) into its XML representation for inspection. ```bash python scripts/create_als_project.py decompress "template/base_template Project/base_template.als" template/base_template.xml ``` -------------------------------- ### Configure StretchParams with Builder Pattern Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Use the builder pattern to configure StretchParams with custom settings. Presets can be applied first, followed by individual parameter overrides. ```rust let params = StretchParams::new(1.5) .with_sample_rate(48000) .with_channels(2) .with_preset(EdmPreset::HouseLoop) // apply preset first .with_fft_size(4096) // then override individual params .with_hop_size(1024) .with_transient_sensitivity(0.6) .with_elastic_timing(true) .with_crossfade_mode(timestretch::CrossfadeMode::Adaptive) .with_hpss(true) .with_multi_resolution(true) .with_sub_bass_cutoff(100.0) .with_stereo_mode(timestretch::StereoMode::MidSide) .with_phase_locking_mode(timestretch::PhaseLockingMode::RegionOfInfluence) .with_wsola_segment_size(960) .with_wsola_search_range(480) .with_beat_aware(true) .with_beat_snap_confidence_threshold(0.35) .with_beat_snap_tolerance_ms(5.0); ``` -------------------------------- ### Offline Pre-Analysis for DJ Stretching Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Perform audio analysis offline to create a pre-analysis artifact, which can then be loaded at runtime to optimize DJ stretching. This reduces runtime computation and improves accuracy, especially with beat snapping. ```rust use timestretch::{ analyze_for_dj, read_preanalysis_json, stretch, write_preanalysis_json, StretchParams, EdmPreset, }; use std::path::Path; // Build a reusable analysis artifact once (offline) let artifact = analyze_for_dj(&input, 44100); write_preanalysis_json(Path::new("track.preanalysis.json"), &artifact).unwrap(); // Load artifact at runtime and attach it to params let loaded = read_preanalysis_json(Path::new("track.preanalysis.json")).unwrap(); let params = StretchParams::new(126.0 / 128.0) .with_preset(EdmPreset::DjBeatmatch) .with_sample_rate(44100) .with_pre_analysis(loaded) .with_beat_snap_confidence_threshold(0.35) .with_beat_snap_tolerance_ms(5.0); let output = stretch(&input, ¶ms).unwrap(); ``` -------------------------------- ### Real-time Pitch Control with StreamProcessor Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Adjust the pitch scale of audio being processed in real-time using StreamProcessor. Allows for dynamic pitch shifting during playback. ```rust use timestretch::StreamProcessor; let mut processor = StreamProcessor::from_tempo(126.0, 128.0, 44100, 2); processor.set_pitch_scale(1.05).expect("valid pitch scale"); println!("Current pitch scale control: {:.3}", processor.pitch_scale()); ``` -------------------------------- ### Time Stretching Functions Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Provides functions for stretching raw audio samples or AudioBuffers to a new duration or tempo. ```APIDOC ## Time Stretching ### `stretch(&[f32], &StretchParams)` **Description**: Stretches raw audio sample data using the provided stretch parameters. ### `stretch_into(&[f32], &StretchParams, &mut Vec)` **Description**: Appends the stretched output of raw audio sample data into a caller-provided buffer. ### `stretch_buffer(&AudioBuffer, &StretchParams)` **Description**: Stretches an `AudioBuffer` object using the provided stretch parameters. ### `stretch_to_bpm(&[f32], &StretchParams, source_bpm, target_bpm)` **Description**: Stretches raw audio sample data to a target BPM, given the source BPM. ### `stretch_to_bpm_auto(&[f32], &StretchParams, target_bpm)` **Description**: Automatically detects the source BPM and stretches raw audio sample data to the target BPM. ### `stretch_bpm_buffer(&AudioBuffer, &StretchParams, source_bpm, target_bpm)` **Description**: Performs BPM-based stretching on an `AudioBuffer`, given the source and target BPMs. ### `stretch_bpm_buffer_auto(&AudioBuffer, &StretchParams, target_bpm)` **Description**: Automatically detects the source BPM and performs BPM-based stretching on an `AudioBuffer` to the target BPM. ``` -------------------------------- ### AudioBuffer API for Stretching Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Stretch audio using the AudioBuffer API, which simplifies handling of audio data. Converts mono samples to an AudioBuffer and applies stretch parameters. ```rust use timestretch::{AudioBuffer, StretchParams}; let buffer = AudioBuffer::from_mono(samples, 44100); let params = StretchParams::new(2.0); let output = timestretch::stretch_buffer(&buffer, ¶ms).unwrap(); println!("Duration: {:.2}s -> {:.2}s", buffer.duration_secs(), output.duration_secs()); ``` -------------------------------- ### BPM Detection Functions Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Provides functions for detecting the tempo and beat grid of audio data. ```APIDOC ## BPM Detection ### `detect_bpm(&[f32], sample_rate)` **Description**: Detects the tempo (BPM) from raw audio samples. ### `detect_bpm_buffer(&AudioBuffer)` **Description**: Detects the tempo (BPM) from an `AudioBuffer`. ### `detect_beat_grid(&[f32], sample_rate)` **Description**: Detects the beat grid positions from raw audio samples. ### `detect_beat_grid_buffer(&AudioBuffer)` **Description**: Detects the beat grid positions from an `AudioBuffer`. ### `bpm_ratio(source_bpm, target_bpm)` **Description**: Computes the stretch ratio required to change from a source BPM to a target BPM. ``` -------------------------------- ### Emit Machine-Readable Dashboard Artifacts Source: https://github.com/robmorgan/timestretch-rs/blob/main/benchmarks/README.md Generate machine-readable dashboard artifacts locally. This command writes per-gate CSV files to a specified directory for analysis. ```bash TIMESTRETCH_QUALITY_DASHBOARD_DIR=target/quality_dashboard cargo test --features qa-harnesses --test quality_gates -- --nocapture ``` -------------------------------- ### Run Clippy with Warnings as Errors Source: https://github.com/robmorgan/timestretch-rs/blob/main/CLAUDE.md Lints the code using Clippy, treating all warnings as errors. This ensures adherence to Rust best practices and coding style. ```bash cargo clippy --all-targets -- -D warnings ``` -------------------------------- ### One-Shot Audio Stretching Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Stretch audio by a specified factor using predefined EDM presets. Requires audio samples as f32 and StretchParams. ```rust use timestretch::{StretchParams, EdmPreset}; // Generate or load audio (f32 samples, -1.0 to 1.0) let input: Vec = load_audio(); let params = StretchParams::new(1.5) // 1.5x longer (slower) .with_sample_rate(44100) .with_channels(1) .with_preset(EdmPreset::HouseLoop); let output = timestretch::stretch(&input, ¶ms).unwrap(); ``` -------------------------------- ### Add Timestretch Dependency to Cargo.toml Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Add the timestretch crate to your project's dependencies in Cargo.toml. ```toml [dependencies] timestretch = "0.4.0" ``` -------------------------------- ### Add wasm32-unknown-unknown target Source: https://github.com/robmorgan/timestretch-rs/blob/main/web/README.md Add the necessary Rust target for WebAssembly compilation. ```bash rustup target add wasm32-unknown-unknown ``` -------------------------------- ### Pre-analysis Artifact Pipeline Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Functions for generating, reading, and writing pre-analysis artifacts, which can store offline beat and onset information. ```APIDOC ## Pre-analysis Artifact Pipeline ### `analyze_for_dj(&[f32], sample_rate)` **Description**: Generates an offline beat and onset analysis artifact from raw audio samples. ### `write_preanalysis_json(path, &PreAnalysisArtifact)` **Description**: Writes a `PreAnalysisArtifact` to a specified file path in JSON format. ### `read_preanalysis_json(path)` **Description**: Reads a `PreAnalysisArtifact` from a specified file path in JSON format. ``` -------------------------------- ### Adaptive Resample Blend Calculation Source: https://github.com/robmorgan/timestretch-rs/blob/main/PLAN-per-bin-spectral-flux.md This Rust code snippet demonstrates how to dynamically adjust the resample blend factor based on the spectral flux of the current frame. Higher flux (transients) leads to a larger blend, while lower flux (steady-state) results in a smaller blend. ```rust let base_blend = 0.04f32; let flux_factor = if let Some(flux) = vocoder_flux { let transient_score = flux.transient_bin_count as f32 / total_bins as f32; (transient_score * 3.0).clamp(0.5, 2.0) // 0.5× to 2× of base blend } else { 1.0 }; let blend = base_blend * flux_factor; ``` -------------------------------- ### Real-Time Streaming Audio Processing Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Process audio in real-time using StreamProcessor, allowing on-the-fly changes to stretch ratio and pitch. Manages buffer capacities for input and output. ```rust use timestretch::{EdmPreset, QualityMode, StreamProcessor, StretchParams}; let params = StretchParams::new(1.02) .with_preset(EdmPreset::DjBeatmatch) .with_sample_rate(44100) .with_channels(2) .with_quality_mode(QualityMode::Balanced); let mut processor = StreamProcessor::new(params); let (_, _, _, pending_capacity) = processor.capacities(); let ratio_hint = processor .current_stretch_ratio() .max(processor.target_stretch_ratio()) .max(1.0); let input_samples_per_chunk = 1024 * 2; // 1024 stereo frames let estimated_output = (input_samples_per_chunk as f64 * ratio_hint).ceil() as usize + pending_capacity; let mut output_chunk = Vec::with_capacity(estimated_output); // Feed chunks as they arrive from your audio driver loop { let input_chunk = read_audio_chunk(1024); output_chunk.clear(); processor.process_into(&input_chunk, &mut output_chunk).unwrap(); play_audio(&output_chunk); } // Change ratio on the fly (e.g. DJ pitch fader) processor.set_stretch_ratio(1.05).expect("valid ratio"); // Flush remaining samples when done let mut remaining = Vec::with_capacity(pending_capacity * 2); processor.flush_into(&mut remaining).unwrap(); ``` -------------------------------- ### Emit Quality Dashboard CSV Artifacts Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Generate quality dashboard CSV artifacts for each quality gate. Specify the output directory using the TIMESTRETCH_QUALITY_DASHBOARD_DIR environment variable. ```sh TIMESTRETCH_QUALITY_DASHBOARD_DIR=target/quality_dashboard cargo test --features qa-harnesses --release --test quality_gates -- --nocapture ``` -------------------------------- ### BPM-Based Audio Stretching Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Stretch audio to a target BPM, automatically computing the stretch ratio. This is useful for synchronizing tracks in DJ applications. Uses EdmPreset::DjBeatmatch for optimal results. ```rust use timestretch::{StretchParams, EdmPreset}; let params = StretchParams::new(1.0) // ratio computed automatically .with_sample_rate(44100) .with_channels(2) .with_preset(EdmPreset::DjBeatmatch); // Stretch a 126 BPM track to 128 BPM let output = timestretch::stretch_to_bpm(&input, ¶ms, 126.0, 128.0).unwrap(); ``` -------------------------------- ### DJ Beatmatching with Timestretch Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Adjust audio tempo between two BPM values for DJ beatmatching using EDM presets. Calculates the ratio based on original and target BPM. ```rust use timestretch::{StretchParams, EdmPreset, bpm_ratio}; let original_bpm = 126.0_f64; let target_bpm = 128.0_f64; let ratio = bpm_ratio(original_bpm, target_bpm); // source / target = ~0.984 let params = StretchParams::new(ratio) .with_preset(EdmPreset::DjBeatmatch) .with_sample_rate(44100) .with_channels(2); // stereo let output = timestretch::stretch(&input, ¶ms).unwrap(); ``` -------------------------------- ### Validate Output WAV Duration Source: https://github.com/robmorgan/timestretch-rs/blob/main/optimize/ableton/README.md Use this script to validate the duration of an output WAV file, which can help diagnose duration mismatch issues. ```bash python scripts/verify_render.py --info output.wav ``` -------------------------------- ### Pitch Shifting Functions Source: https://github.com/robmorgan/timestretch-rs/blob/main/README.md Provides functions for shifting the pitch of audio samples or AudioBuffers without altering their duration. ```APIDOC ## Pitch Shifting ### `pitch_shift(&[f32], &StretchParams, factor)` **Description**: Shifts the pitch of raw audio sample data by a given factor without changing its duration. ### `pitch_shift_buffer(&AudioBuffer, &StretchParams, factor)` **Description**: Shifts the pitch of an `AudioBuffer` by a given factor without changing its duration. ``` -------------------------------- ### Calculate Half-Wave Rectified Flux Source: https://github.com/robmorgan/timestretch-rs/blob/main/PLAN-per-bin-spectral-flux.md This snippet shows how to calculate the half-wave rectified spectral flux for a single bin. It is used to detect onsets by only considering positive changes in magnitude. ```rust let flux = (mag - prev_mag).max(0.0); // Only positive flux (onset) ``` -------------------------------- ### Track Catalog JSON Structure Source: https://github.com/robmorgan/timestretch-rs/blob/main/optimize/ableton/README.md Define source audio tracks, their BPMs, and target BPMs for time-stretching operations. The 'ratio' field is calculated as target_bpm / source_bpm. Set 'stereo' to true for stereo-specific scoring metrics. ```json [ { "id": "my-track", "source": "../samples/my_track.wav", "source_bpm": 124.0, "targets": [ {"target_bpm": 115.0, "ratio": 0.9274}, {"target_bpm": 128.0, "ratio": 1.0323} ], "stereo": true } ] ``` -------------------------------- ### Per-Frame Flux Data Structure Source: https://github.com/robmorgan/timestretch-rs/blob/main/PLAN-per-bin-spectral-flux.md Defines a structure to hold aggregated per-band spectral flux information for a single frame. This includes scores for different frequency bands and counts of transient bins. ```rust pub struct PerFrameFlux { pub sub_bass: f32, // <180Hz (sub_bass_bin) pub low: f32, // 180-500Hz pub mid: f32, // 500-4000Hz pub high: f32, // >4000Hz pub transient_bin_count: u16, // bins with flux > N× mean pub total_bins_rising: u16 // bins with any positive flux } ```