Stream audio & video from .beam container; waveform LOD pyramid + persistence
Migrate the .beam container to SQLite and stream media from it instead of decoding whole files into RAM on import/load. Container & large files: - SQLite .beam container (beam_archive) with in-place transactional saves and an incremental BlobReader; supports both packed (chunked blobs) and referenced (external path) media, with a user preference + first-import prompt for files over the large-media threshold. Audio streaming: - Stream packed compressed audio on load via an inversion-of-control blob factory (AudioBlobSourceFactory): daw-backend defines the trait, core implements it over BlobReader, so the audio engine stays container-agnostic. - Bulk-activate disk streaming for all loaded clips after SetProject. - Sample-accurate compressed seek (SeekMode::Accurate; Coarse mislands on VBR). Video: - Video frames decoded/streamed on demand; thumbnails generated asynchronously on a dedicated decoder so import/load never blocks the UI. - The video's audio track is streamed on demand via an ffmpeg VideoAudioReader as a separate editable AudioClip (no /tmp WAV extraction). Waveform overview: - Streaming min/max LOD pyramid (waveform_pyramid), bounded memory, configurable floor B; serialized into the container and restored on load (or generated in the background from the packed blob when absent), so no re-decode on reload. - GPU min/max upload path; integer-LOD textureLoad fixes zoom-dependent wobble.
This commit is contained in:
@@ -307,23 +307,96 @@ impl ReadAheadBuffer {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Wraps a Symphonia decoder for streaming a single compressed audio file.
|
||||
struct CompressedReader {
|
||||
///
|
||||
/// Public (like [`VideoAudioReader`]) only so integration tests can exercise it
|
||||
/// directly; treat it as crate-internal.
|
||||
pub struct CompressedReader {
|
||||
format_reader: Box<dyn symphonia::core::formats::FormatReader>,
|
||||
decoder: Box<dyn symphonia::core::codecs::Decoder>,
|
||||
track_id: u32,
|
||||
/// Current decoder position in frames.
|
||||
current_frame: u64,
|
||||
/// Frames still to drop from the front of decoded output, so that after a
|
||||
/// (coarse) seek the next emitted sample lands exactly on the target frame.
|
||||
pending_discard: u64,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
#[allow(dead_code)]
|
||||
total_frames: u64,
|
||||
/// Temporary decode buffer.
|
||||
sample_buf: Option<SampleBuffer<f32>>,
|
||||
}
|
||||
|
||||
/// A seekable byte stream for packed media held in the host's project container.
|
||||
///
|
||||
/// `daw-backend` stays container-agnostic: it never references the `.beam` SQLite
|
||||
/// store directly. Instead the host (lightningbeam-core) implements this trait over
|
||||
/// its incremental blob reader and installs a factory ([`AudioBlobSourceFactory`])
|
||||
/// into the engine, so packed compressed audio can be stream-decoded without ever
|
||||
/// being fully loaded into RAM.
|
||||
pub trait MediaByteSource: std::io::Read + std::io::Seek + Send + Sync {
|
||||
/// Total length of the stream in bytes (Symphonia needs this for seeking).
|
||||
fn byte_len(&self) -> u64;
|
||||
}
|
||||
|
||||
/// Opens fresh byte streams for packed media by id. Installed into the engine by
|
||||
/// the host; invoked when activating a clip backed by container-packed audio.
|
||||
/// (`Debug` so it can ride in the `Query` enum, which derives `Debug`.)
|
||||
pub trait AudioBlobSourceFactory: Send + Sync + std::fmt::Debug {
|
||||
/// Open a new independent reader for the packed media item `media_id`
|
||||
/// (the UUID string stored on the audio pool entry).
|
||||
fn open(&self, media_id: &str) -> Result<Box<dyn MediaByteSource>, String>;
|
||||
}
|
||||
|
||||
/// Adapts a [`MediaByteSource`] to Symphonia's `MediaSource` (adds the seekable +
|
||||
/// byte-length metadata Symphonia's probe/seek require).
|
||||
struct SymphoniaByteSource(Box<dyn MediaByteSource>);
|
||||
|
||||
impl std::io::Read for SymphoniaByteSource {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
self.0.read(buf)
|
||||
}
|
||||
}
|
||||
impl std::io::Seek for SymphoniaByteSource {
|
||||
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
|
||||
self.0.seek(pos)
|
||||
}
|
||||
}
|
||||
impl symphonia::core::io::MediaSource for SymphoniaByteSource {
|
||||
fn is_seekable(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn byte_len(&self) -> Option<u64> {
|
||||
Some(self.0.byte_len())
|
||||
}
|
||||
}
|
||||
|
||||
/// How to open a streaming audio source: a filesystem path (referenced media or a
|
||||
/// video file) or a host-provided byte stream (container-packed media).
|
||||
pub enum StreamOpen {
|
||||
Path(PathBuf),
|
||||
Source {
|
||||
src: Box<dyn MediaByteSource>,
|
||||
/// Codec/extension hint for the Symphonia probe (e.g. `"mp3"`, `"flac"`).
|
||||
ext: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl CompressedReader {
|
||||
pub fn sample_rate(&self) -> u32 {
|
||||
self.sample_rate
|
||||
}
|
||||
|
||||
pub fn channels(&self) -> u32 {
|
||||
self.channels
|
||||
}
|
||||
|
||||
/// Total frames from the codec header (0 if the format doesn't report it).
|
||||
pub fn total_frames(&self) -> u64 {
|
||||
self.total_frames
|
||||
}
|
||||
|
||||
/// Open a compressed audio file and prepare for streaming decode.
|
||||
fn open(path: &Path) -> Result<Self, String> {
|
||||
pub fn open(path: &Path) -> Result<Self, String> {
|
||||
let file =
|
||||
std::fs::File::open(path).map_err(|e| format!("Failed to open file: {}", e))?;
|
||||
let mss = MediaSourceStream::new(Box::new(file), Default::default());
|
||||
@@ -332,7 +405,21 @@ impl CompressedReader {
|
||||
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
|
||||
hint.with_extension(ext);
|
||||
}
|
||||
Self::from_mss(mss, hint)
|
||||
}
|
||||
|
||||
/// Open a compressed stream from a host-provided byte source (packed media).
|
||||
pub fn open_source(src: Box<dyn MediaByteSource>, ext: Option<&str>) -> Result<Self, String> {
|
||||
let mss = MediaSourceStream::new(Box::new(SymphoniaByteSource(src)), Default::default());
|
||||
let mut hint = Hint::new();
|
||||
if let Some(ext) = ext {
|
||||
hint.with_extension(ext);
|
||||
}
|
||||
Self::from_mss(mss, hint)
|
||||
}
|
||||
|
||||
/// Shared probe + decoder setup over an already-built media stream.
|
||||
fn from_mss(mss: MediaSourceStream, hint: Hint) -> Result<Self, String> {
|
||||
let probed = symphonia::default::get_probe()
|
||||
.format(
|
||||
&hint,
|
||||
@@ -368,6 +455,7 @@ impl CompressedReader {
|
||||
decoder,
|
||||
track_id,
|
||||
current_frame: 0,
|
||||
pending_discard: 0,
|
||||
sample_rate,
|
||||
channels,
|
||||
total_frames,
|
||||
@@ -375,9 +463,17 @@ impl CompressedReader {
|
||||
})
|
||||
}
|
||||
|
||||
/// Seek to a specific frame. Returns the actual frame reached (may differ
|
||||
/// for compressed formats that can only seek to keyframes).
|
||||
fn seek(&mut self, target_frame: u64) -> Result<u64, String> {
|
||||
/// Seek to `target_frame`, **sample-accurately**. Uses `SeekMode::Accurate`:
|
||||
/// for an elementary stream like MP3 a *coarse* seek byte-estimates the
|
||||
/// position and seeds the timestamp from that estimate — which for VBR (or a
|
||||
/// file whose header padding the estimate ignores) lands off by up to ~1s.
|
||||
/// Accurate mode instead counts frame *headers* (no decode) from a true anchor
|
||||
/// (the current position, or a rewind to the start for backward seeks), so the
|
||||
/// returned `actual_ts` is exact; the small residual to `target_frame` is then
|
||||
/// dropped in `decode_next`. Container formats with seek tables (FLAC/OGG) seek
|
||||
/// cheaply; a long MP3 walks headers from the anchor (I/O, not decode) — a
|
||||
/// per-file seek index would make that O(1) (future work).
|
||||
pub fn seek(&mut self, target_frame: u64) -> Result<u64, String> {
|
||||
let seek_to = SeekTo::TimeStamp {
|
||||
ts: target_frame,
|
||||
track_id: self.track_id,
|
||||
@@ -385,21 +481,23 @@ impl CompressedReader {
|
||||
|
||||
let seeked = self
|
||||
.format_reader
|
||||
.seek(SeekMode::Coarse, seek_to)
|
||||
.seek(SeekMode::Accurate, seek_to)
|
||||
.map_err(|e| format!("Seek failed: {}", e))?;
|
||||
|
||||
let actual_frame = seeked.actual_ts;
|
||||
self.current_frame = actual_frame;
|
||||
// Drop the frames between where the coarse seek landed and the target.
|
||||
self.pending_discard = target_frame.saturating_sub(actual_frame);
|
||||
|
||||
// Reset the decoder after seeking.
|
||||
self.decoder.reset();
|
||||
|
||||
Ok(actual_frame)
|
||||
Ok(target_frame)
|
||||
}
|
||||
|
||||
/// Decode the next chunk of audio into `out`. Returns the number of frames
|
||||
/// decoded. Returns `Ok(0)` at end-of-file.
|
||||
fn decode_next(&mut self, out: &mut Vec<f32>) -> Result<usize, String> {
|
||||
pub fn decode_next(&mut self, out: &mut Vec<f32>) -> Result<usize, String> {
|
||||
out.clear();
|
||||
|
||||
loop {
|
||||
@@ -428,10 +526,22 @@ impl CompressedReader {
|
||||
if let Some(ref mut buf) = self.sample_buf {
|
||||
buf.copy_interleaved_ref(decoded);
|
||||
let samples = buf.samples();
|
||||
out.extend_from_slice(samples);
|
||||
let frames = samples.len() / self.channels as usize;
|
||||
self.current_frame += frames as u64;
|
||||
return Ok(frames);
|
||||
let ch = self.channels as usize;
|
||||
let frames = samples.len() / ch;
|
||||
|
||||
// Drop leading frames for sample-accurate seek alignment.
|
||||
let discard = self.pending_discard.min(frames as u64) as usize;
|
||||
self.pending_discard -= discard as u64;
|
||||
out.extend_from_slice(&samples[discard * ch..]);
|
||||
let emitted = frames - discard;
|
||||
self.current_frame += emitted as u64;
|
||||
|
||||
if emitted > 0 {
|
||||
return Ok(emitted);
|
||||
}
|
||||
// Whole packet discarded for alignment — keep decoding so
|
||||
// we never falsely report EOF (Ok(0)).
|
||||
continue;
|
||||
}
|
||||
|
||||
return Ok(0);
|
||||
@@ -445,16 +555,383 @@ impl CompressedReader {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// VideoAudioReader
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Streams the audio track out of a media file (a video container, or any audio
|
||||
/// file) using FFmpeg, decoding on demand. Mirrors [`CompressedReader`]'s
|
||||
/// interface so the disk reader can drive either through [`StreamSource`].
|
||||
///
|
||||
/// Seeking is **sample-accurate**: after `seek(target)`, the next `decode_next`
|
||||
/// yields samples beginning at exactly `target`. FFmpeg's container seek only
|
||||
/// lands at-or-before the target, so we decode forward and discard the leading
|
||||
/// samples to hit the frame precisely — this keeps video audio frame-synced with
|
||||
/// other (mmap/in-memory) clips.
|
||||
///
|
||||
/// Public (vs. the private `CompressedReader`) only so integration tests can
|
||||
/// exercise it directly; treat it as crate-internal.
|
||||
pub struct VideoAudioReader {
|
||||
input: ffmpeg_next::format::context::Input,
|
||||
decoder: ffmpeg_next::decoder::Audio,
|
||||
/// Built lazily from the first decoded frame's format/layout → interleaved f32.
|
||||
resampler: Option<ffmpeg_next::software::resampling::Context>,
|
||||
stream_index: usize,
|
||||
/// Seconds per stream-timestamp unit.
|
||||
time_base: f64,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
total_frames: u64,
|
||||
/// Absolute frame index of the next sample `decode_next` will output.
|
||||
current_frame: u64,
|
||||
/// Frames still to drop from the front of decoded output (seek alignment).
|
||||
pending_discard: u64,
|
||||
/// When set, the next decoded frame establishes the discard needed to land on
|
||||
/// this absolute target frame (sample-accurate seek).
|
||||
align_to: Option<u64>,
|
||||
}
|
||||
|
||||
impl VideoAudioReader {
|
||||
pub fn sample_rate(&self) -> u32 {
|
||||
self.sample_rate
|
||||
}
|
||||
|
||||
pub fn channels(&self) -> u32 {
|
||||
self.channels
|
||||
}
|
||||
|
||||
/// Estimated total audio frames (from the stream/container duration).
|
||||
pub fn total_frames(&self) -> u64 {
|
||||
self.total_frames
|
||||
}
|
||||
|
||||
pub fn open(path: &Path) -> Result<Self, String> {
|
||||
ffmpeg_next::init().map_err(|e| e.to_string())?;
|
||||
let input = ffmpeg_next::format::input(&path)
|
||||
.map_err(|e| format!("Failed to open media: {}", e))?;
|
||||
|
||||
// Pull stream scalars + build the decoder inside a scope so the stream
|
||||
// borrow of `input` ends before we use `input` again.
|
||||
let (stream_index, time_base, stream_duration, decoder) = {
|
||||
let stream = input
|
||||
.streams()
|
||||
.best(ffmpeg_next::media::Type::Audio)
|
||||
.ok_or_else(|| "No audio stream found".to_string())?;
|
||||
let stream_index = stream.index();
|
||||
let time_base = f64::from(stream.time_base());
|
||||
let stream_duration = stream.duration();
|
||||
let ctx = ffmpeg_next::codec::context::Context::from_parameters(stream.parameters())
|
||||
.map_err(|e| e.to_string())?;
|
||||
let decoder = ctx.decoder().audio().map_err(|e| e.to_string())?;
|
||||
(stream_index, time_base, stream_duration, decoder)
|
||||
};
|
||||
|
||||
let sample_rate = decoder.rate();
|
||||
let channels = decoder.channels() as u32;
|
||||
|
||||
let duration_secs = if stream_duration > 0 {
|
||||
stream_duration as f64 * time_base
|
||||
} else if input.duration() > 0 {
|
||||
input.duration() as f64 / f64::from(ffmpeg_next::ffi::AV_TIME_BASE)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let total_frames = (duration_secs * sample_rate as f64).max(0.0) as u64;
|
||||
|
||||
Ok(Self {
|
||||
input,
|
||||
decoder,
|
||||
resampler: None,
|
||||
stream_index,
|
||||
time_base,
|
||||
sample_rate,
|
||||
channels,
|
||||
total_frames,
|
||||
current_frame: 0,
|
||||
pending_discard: 0,
|
||||
align_to: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn seek(&mut self, target_frame: u64) -> Result<u64, String> {
|
||||
let seconds = target_frame as f64 / self.sample_rate.max(1) as f64;
|
||||
let ts_av = (seconds * f64::from(ffmpeg_next::ffi::AV_TIME_BASE)) as i64;
|
||||
// Seek to at-or-before the target (max_ts = ts_av) so we can decode
|
||||
// forward to it exactly. ffmpeg-next's `seek` wants a bounded range.
|
||||
self.input
|
||||
.seek(ts_av, 0..(ts_av + 1))
|
||||
.map_err(|e| format!("Seek failed: {}", e))?;
|
||||
self.decoder.flush();
|
||||
self.pending_discard = 0;
|
||||
self.align_to = Some(target_frame);
|
||||
self.current_frame = target_frame;
|
||||
// We align to the exact frame below, so the effective position IS target.
|
||||
Ok(target_frame)
|
||||
}
|
||||
|
||||
pub fn decode_next(&mut self, out: &mut Vec<f32>) -> Result<usize, String> {
|
||||
out.clear();
|
||||
loop {
|
||||
// Drain a decoded frame if one is ready.
|
||||
let mut decoded = ffmpeg_next::frame::Audio::empty();
|
||||
if self.decoder.receive_frame(&mut decoded).is_ok() {
|
||||
self.ensure_layout(&mut decoded);
|
||||
let n = self.emit(&decoded, out);
|
||||
if n > 0 {
|
||||
return Ok(n);
|
||||
}
|
||||
continue; // frame fully discarded by seek-alignment; keep going
|
||||
}
|
||||
|
||||
// Read one packet (owned), releasing the `input` borrow before decoding.
|
||||
let packet = self.input.packets().next().map(|(_, p)| p);
|
||||
match packet {
|
||||
Some(packet) => {
|
||||
if packet.stream() == self.stream_index {
|
||||
self.decoder
|
||||
.send_packet(&packet)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// EOF: flush and drain whatever remains.
|
||||
let _ = self.decoder.send_eof();
|
||||
let mut decoded = ffmpeg_next::frame::Audio::empty();
|
||||
if self.decoder.receive_frame(&mut decoded).is_ok() {
|
||||
self.ensure_layout(&mut decoded);
|
||||
return Ok(self.emit(&decoded, out));
|
||||
}
|
||||
return Ok(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Decoders for some formats (e.g. raw mono WAV) leave the frame's channel
|
||||
/// layout unset. The resampler needs a concrete layout that matches the
|
||||
/// frame, so fill one in from the channel count when it's missing.
|
||||
fn ensure_layout(&self, frame: &mut ffmpeg_next::frame::Audio) {
|
||||
if frame.channel_layout().is_empty() {
|
||||
frame.set_channel_layout(
|
||||
ffmpeg_next::channel_layout::ChannelLayout::default(self.channels as i32),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Resample one decoded frame to interleaved f32, apply any pending
|
||||
/// seek-alignment discard, append to `out`, return frames emitted.
|
||||
fn emit(&mut self, frame: &ffmpeg_next::frame::Audio, out: &mut Vec<f32>) -> usize {
|
||||
// `frame` already has a non-empty channel layout (set by `ensure_layout`
|
||||
// before this call), so the resampler config and the actual frame agree
|
||||
// — otherwise swr fails with AVERROR_INPUT_CHANGED.
|
||||
if self.resampler.is_none() {
|
||||
match ffmpeg_next::software::resampling::Context::get(
|
||||
frame.format(),
|
||||
frame.channel_layout(),
|
||||
self.sample_rate,
|
||||
ffmpeg_next::format::Sample::F32(ffmpeg_next::format::sample::Type::Packed),
|
||||
frame.channel_layout(),
|
||||
self.sample_rate,
|
||||
) {
|
||||
Ok(r) => self.resampler = Some(r),
|
||||
Err(_) => return 0,
|
||||
}
|
||||
}
|
||||
|
||||
let mut resampled = ffmpeg_next::frame::Audio::empty();
|
||||
if self
|
||||
.resampler
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.run(frame, &mut resampled)
|
||||
.is_err()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The output is packed (interleaved) f32. Read it from the raw byte plane
|
||||
// `data(0)` — its length is correct (`frames * channels * 4`), whereas
|
||||
// `plane::<f32>(0)` is a known ffmpeg-next footgun that reports only
|
||||
// `samples()` elements (ignoring channels) and would slice out of range
|
||||
// for multi-channel audio.
|
||||
let ch = self.channels.max(1) as usize;
|
||||
let bytes = resampled.data(0);
|
||||
let n_frames = (bytes.len() / 4) / ch;
|
||||
if n_frames == 0 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// On the first frame after a seek, compute how many leading frames to
|
||||
// drop so output begins exactly at the seek target.
|
||||
if let Some(target) = self.align_to.take() {
|
||||
let frame_start = self.pts_to_frame(frame.pts());
|
||||
self.pending_discard = target.saturating_sub(frame_start);
|
||||
}
|
||||
|
||||
let discard = (self.pending_discard.min(n_frames as u64)) as usize;
|
||||
self.pending_discard -= discard as u64;
|
||||
|
||||
let start_byte = discard * ch * 4;
|
||||
let end_byte = n_frames * ch * 4;
|
||||
out.extend(
|
||||
bytes[start_byte..end_byte]
|
||||
.chunks_exact(4)
|
||||
.map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])),
|
||||
);
|
||||
let emitted = n_frames - discard;
|
||||
self.current_frame += emitted as u64;
|
||||
emitted
|
||||
}
|
||||
|
||||
/// Convert a stream PTS to an absolute audio frame index.
|
||||
fn pts_to_frame(&self, pts: Option<i64>) -> u64 {
|
||||
match pts {
|
||||
Some(p) if p >= 0 => {
|
||||
((p as f64 * self.time_base) * self.sample_rate as f64).round() as u64
|
||||
}
|
||||
_ => self.current_frame,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// StreamSource — dispatches the disk reader over either decoder backend.
|
||||
// (Wired into the reader thread in a later step.)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Which decoder backend a streaming source uses.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SourceKind {
|
||||
/// Symphonia, for compressed audio files (MP3, FLAC, OGG, …).
|
||||
CompressedAudio,
|
||||
/// FFmpeg, for the audio track of a video container.
|
||||
VideoAudio,
|
||||
}
|
||||
|
||||
/// A streaming audio source backing one active clip: either Symphonia
|
||||
/// ([`CompressedReader`]) or FFmpeg ([`VideoAudioReader`]).
|
||||
enum StreamSource {
|
||||
Compressed(CompressedReader),
|
||||
Video(VideoAudioReader),
|
||||
}
|
||||
|
||||
impl StreamSource {
|
||||
fn open(open: StreamOpen, kind: SourceKind) -> Result<Self, String> {
|
||||
match (kind, open) {
|
||||
(SourceKind::CompressedAudio, StreamOpen::Path(p)) => {
|
||||
Ok(StreamSource::Compressed(CompressedReader::open(&p)?))
|
||||
}
|
||||
(SourceKind::CompressedAudio, StreamOpen::Source { src, ext }) => {
|
||||
Ok(StreamSource::Compressed(CompressedReader::open_source(src, ext.as_deref())?))
|
||||
}
|
||||
(SourceKind::VideoAudio, StreamOpen::Path(p)) => {
|
||||
Ok(StreamSource::Video(VideoAudioReader::open(&p)?))
|
||||
}
|
||||
(SourceKind::VideoAudio, StreamOpen::Source { .. }) => {
|
||||
Err("VideoAudio cannot be opened from a packed byte source".to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_rate(&self) -> u32 {
|
||||
match self {
|
||||
StreamSource::Compressed(r) => r.sample_rate,
|
||||
StreamSource::Video(r) => r.sample_rate,
|
||||
}
|
||||
}
|
||||
|
||||
fn channels(&self) -> u32 {
|
||||
match self {
|
||||
StreamSource::Compressed(r) => r.channels,
|
||||
StreamSource::Video(r) => r.channels,
|
||||
}
|
||||
}
|
||||
|
||||
fn seek(&mut self, target_frame: u64) -> Result<u64, String> {
|
||||
match self {
|
||||
StreamSource::Compressed(r) => r.seek(target_frame),
|
||||
StreamSource::Video(r) => r.seek(target_frame),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_next(&mut self, out: &mut Vec<f32>) -> Result<usize, String> {
|
||||
match self {
|
||||
StreamSource::Compressed(r) => r.decode_next(out),
|
||||
StreamSource::Video(r) => r.decode_next(out),
|
||||
}
|
||||
}
|
||||
|
||||
fn total_frames(&self) -> u64 {
|
||||
match self {
|
||||
StreamSource::Compressed(r) => r.total_frames(),
|
||||
StreamSource::Video(r) => r.total_frames(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode a media source end-to-end and build its [`WaveformPyramid`] overview,
|
||||
/// streaming — only one decode chunk plus the (bounded) pyramid are ever in
|
||||
/// memory, never the full sample buffer. `floor_samples_per_texel` is the
|
||||
/// finest-level resolution (see [`crate::audio::waveform_pyramid`]).
|
||||
pub fn build_waveform_pyramid(
|
||||
path: &Path,
|
||||
kind: SourceKind,
|
||||
floor_samples_per_texel: u32,
|
||||
) -> Result<crate::audio::waveform_pyramid::WaveformPyramid, String> {
|
||||
let src = StreamSource::open(StreamOpen::Path(path.to_path_buf()), kind)?;
|
||||
build_pyramid_from_streamsource(src, floor_samples_per_texel)
|
||||
}
|
||||
|
||||
/// Build a waveform pyramid from a host-provided byte source (container-packed
|
||||
/// compressed audio) — the load-time counterpart of [`build_waveform_pyramid`]
|
||||
/// for media that has no filesystem path.
|
||||
pub fn build_waveform_pyramid_from_source(
|
||||
src: Box<dyn MediaByteSource>,
|
||||
ext: Option<&str>,
|
||||
floor_samples_per_texel: u32,
|
||||
) -> Result<crate::audio::waveform_pyramid::WaveformPyramid, String> {
|
||||
let src = StreamSource::open(
|
||||
StreamOpen::Source { src, ext: ext.map(|s| s.to_string()) },
|
||||
SourceKind::CompressedAudio,
|
||||
)?;
|
||||
build_pyramid_from_streamsource(src, floor_samples_per_texel)
|
||||
}
|
||||
|
||||
fn build_pyramid_from_streamsource(
|
||||
mut src: StreamSource,
|
||||
floor_samples_per_texel: u32,
|
||||
) -> Result<crate::audio::waveform_pyramid::WaveformPyramid, String> {
|
||||
use crate::audio::waveform_pyramid::WaveformPyramidBuilder;
|
||||
|
||||
let channels = src.channels();
|
||||
let mut builder = WaveformPyramidBuilder::new(channels, floor_samples_per_texel);
|
||||
builder.reserve_for_frames(src.total_frames());
|
||||
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
let frames = src.decode_next(&mut buf)?;
|
||||
if frames == 0 {
|
||||
break;
|
||||
}
|
||||
builder.push_interleaved(&buf);
|
||||
}
|
||||
Ok(builder.finish())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DiskReaderCommand
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Commands sent from the engine to the disk reader thread.
|
||||
pub enum DiskReaderCommand {
|
||||
/// Start streaming a compressed file for a clip instance.
|
||||
/// Start streaming a file for a clip instance, using the decoder backend
|
||||
/// selected by `kind` (compressed audio vs. a video's audio track). `open`
|
||||
/// is either a filesystem path (referenced media / video) or a host-provided
|
||||
/// byte stream (container-packed media).
|
||||
ActivateFile {
|
||||
reader_id: u64,
|
||||
path: PathBuf,
|
||||
open: StreamOpen,
|
||||
kind: SourceKind,
|
||||
buffer: Arc<ReadAheadBuffer>,
|
||||
},
|
||||
/// Stop streaming for a clip instance.
|
||||
@@ -529,7 +1006,7 @@ impl DiskReader {
|
||||
mut command_rx: rtrb::Consumer<DiskReaderCommand>,
|
||||
running: Arc<AtomicBool>,
|
||||
) {
|
||||
let mut active_files: HashMap<u64, (CompressedReader, Arc<ReadAheadBuffer>)> =
|
||||
let mut active_files: HashMap<u64, (StreamSource, Arc<ReadAheadBuffer>)> =
|
||||
HashMap::new();
|
||||
let mut decode_buf = Vec::with_capacity(8192);
|
||||
|
||||
@@ -539,18 +1016,19 @@ impl DiskReader {
|
||||
match cmd {
|
||||
DiskReaderCommand::ActivateFile {
|
||||
reader_id,
|
||||
path,
|
||||
open,
|
||||
kind,
|
||||
buffer,
|
||||
} => match CompressedReader::open(&path) {
|
||||
} => match StreamSource::open(open, kind) {
|
||||
Ok(reader) => {
|
||||
eprintln!("[DiskReader] Activated reader={}, ch={}, sr={}, path={:?}",
|
||||
reader_id, reader.channels, reader.sample_rate, path);
|
||||
eprintln!("[DiskReader] Activated reader={}, kind={:?}, ch={}, sr={}",
|
||||
reader_id, kind, reader.channels(), reader.sample_rate());
|
||||
active_files.insert(reader_id, (reader, buffer));
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"[DiskReader] Failed to open compressed file {:?}: {}",
|
||||
path, e
|
||||
"[DiskReader] Failed to open reader={} ({:?}): {}",
|
||||
reader_id, kind, e
|
||||
);
|
||||
}
|
||||
},
|
||||
@@ -588,7 +1066,7 @@ impl DiskReader {
|
||||
|
||||
// If the target has jumped behind or far ahead of the buffer,
|
||||
// seek the decoder and reset.
|
||||
if target < buf_start || target > buf_end + reader.sample_rate as u64 {
|
||||
if target < buf_start || target > buf_end + reader.sample_rate() as u64 {
|
||||
buffer.reset(target);
|
||||
let _ = reader.seek(target);
|
||||
continue;
|
||||
@@ -607,7 +1085,7 @@ impl DiskReader {
|
||||
let buf_valid = buffer.valid_frames_count();
|
||||
let buf_end = buf_start + buf_valid;
|
||||
let prefetch_target =
|
||||
target + (PREFETCH_SECONDS * reader.sample_rate as f64) as u64;
|
||||
target + (PREFETCH_SECONDS * reader.sample_rate() as f64) as u64;
|
||||
|
||||
if buf_end >= prefetch_target {
|
||||
continue; // Already filled far enough ahead.
|
||||
@@ -649,3 +1127,7 @@ impl Drop for DiskReader {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tests for VideoAudioReader live in `daw-backend/tests/video_audio_stream.rs`
|
||||
// (integration tests) so they build the lib in normal mode, independent of
|
||||
// pre-existing breakage in the crate's `#[cfg(test)]` unit tests (automation.rs).
|
||||
|
||||
+172
-80
@@ -91,6 +91,10 @@ pub struct Engine {
|
||||
// Disk reader for streaming playback of compressed files
|
||||
disk_reader: Option<crate::audio::disk_reader::DiskReader>,
|
||||
|
||||
// Host-installed factory for opening container-packed audio as a byte stream
|
||||
// (set on load, before the project's clips are bulk-activated for streaming).
|
||||
blob_source_factory: Option<Arc<dyn crate::audio::disk_reader::AudioBlobSourceFactory>>,
|
||||
|
||||
// Input monitoring and metering
|
||||
input_monitoring: bool,
|
||||
input_gain: f32,
|
||||
@@ -176,6 +180,7 @@ impl Engine {
|
||||
metronome: Metronome::new(sample_rate),
|
||||
recording_sample_buffer: Vec::with_capacity(4096),
|
||||
disk_reader: Some(disk_reader),
|
||||
blob_source_factory: None,
|
||||
input_monitoring: false,
|
||||
input_gain: 1.0,
|
||||
input_level_peak: 0.0,
|
||||
@@ -273,6 +278,97 @@ impl Engine {
|
||||
|
||||
/// Rebuild the clip snapshot from the current project state.
|
||||
/// Call this after any command that adds, removes, or modifies clip instances.
|
||||
/// Set up disk streaming for a clip backed by a streaming pool entry
|
||||
/// (Compressed or VideoAudio). Sends `ActivateFile` to the disk reader and
|
||||
/// returns the read-ahead buffer to attach to the clip. Returns `None` if the
|
||||
/// entry isn't streamed, or a packed source can't be opened.
|
||||
fn activate_streaming_for(
|
||||
&mut self,
|
||||
reader_id: u64,
|
||||
pool_index: usize,
|
||||
) -> Option<Arc<crate::audio::disk_reader::ReadAheadBuffer>> {
|
||||
use crate::audio::pool::AudioStorage;
|
||||
use crate::audio::disk_reader::{DiskReader, DiskReaderCommand, SourceKind, StreamOpen};
|
||||
|
||||
// Decide how to open the source. `Packed` ⇒ via the host factory (bytes in
|
||||
// the container); otherwise stream from the file path. Extract owned values
|
||||
// first so the immutable pool borrow ends before we touch the disk reader.
|
||||
enum OpenDesc {
|
||||
Path(std::path::PathBuf),
|
||||
Packed { media_id: String, ext: Option<String> },
|
||||
}
|
||||
let (kind, sample_rate, channels, desc) = {
|
||||
let file = self.audio_pool.get_file(pool_index)?;
|
||||
let kind = match file.storage {
|
||||
AudioStorage::Compressed { .. } => SourceKind::CompressedAudio,
|
||||
AudioStorage::VideoAudio { .. } => SourceKind::VideoAudio,
|
||||
_ => return None,
|
||||
};
|
||||
let desc = match &file.packed_media_id {
|
||||
Some(id) => OpenDesc::Packed { media_id: id.clone(), ext: file.original_format.clone() },
|
||||
None => OpenDesc::Path(file.path.clone()),
|
||||
};
|
||||
(kind, file.sample_rate, file.channels, desc)
|
||||
};
|
||||
|
||||
let open = match desc {
|
||||
OpenDesc::Path(p) => StreamOpen::Path(p),
|
||||
OpenDesc::Packed { media_id, ext } => {
|
||||
let factory = match self.blob_source_factory.as_ref() {
|
||||
Some(f) => f,
|
||||
None => {
|
||||
eprintln!("[Engine] packed audio (pool {}) but no blob factory installed", pool_index);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
match factory.open(&media_id) {
|
||||
Ok(src) => StreamOpen::Source { src, ext },
|
||||
Err(e) => {
|
||||
eprintln!("[Engine] blob factory open({}) failed: {}", media_id, e);
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let buffer = DiskReader::create_buffer(sample_rate, channels);
|
||||
if let Some(ref mut dr) = self.disk_reader {
|
||||
dr.send(DiskReaderCommand::ActivateFile { reader_id, open, kind, buffer: buffer.clone() });
|
||||
}
|
||||
Some(buffer)
|
||||
}
|
||||
|
||||
/// Activate disk streaming for every loaded clip backed by a streaming pool
|
||||
/// entry. Called after `SetProject` since loaded clips bypass `AddAudioClip`.
|
||||
fn activate_all_streaming_clips(&mut self) {
|
||||
use crate::audio::track::TrackNode;
|
||||
// Collect (track, clip, pool) first via an immutable walk, then activate
|
||||
// (needs &mut self) and attach the buffer back to the clip.
|
||||
let targets: Vec<(TrackId, u64, usize)> = self
|
||||
.project
|
||||
.track_iter()
|
||||
.filter_map(|(track_id, node)| match node {
|
||||
TrackNode::Audio(t) => Some((track_id, t)),
|
||||
_ => None,
|
||||
})
|
||||
.flat_map(|(track_id, t)| {
|
||||
t.clips
|
||||
.iter()
|
||||
.map(move |c| (track_id, c.id as u64, c.audio_pool_index))
|
||||
})
|
||||
.collect();
|
||||
|
||||
for (track_id, clip_id, pool_index) in targets {
|
||||
if let Some(buffer) = self.activate_streaming_for(clip_id, pool_index) {
|
||||
if let Some(TrackNode::Audio(track)) = self.project.get_track_mut(track_id) {
|
||||
if let Some(clip) = track.clips.iter_mut().find(|c| c.id as u64 == clip_id) {
|
||||
clip.read_ahead = Some(buffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh_clip_snapshot(&self) {
|
||||
let mut snap = self.clip_snapshot.write().unwrap();
|
||||
snap.audio.clear();
|
||||
@@ -914,7 +1010,7 @@ impl Engine {
|
||||
let start_secs = self.tempo_map.beats_to_seconds(start_beats);
|
||||
let end_secs = self.tempo_map.beats_to_seconds(end_beats);
|
||||
let content_dur_secs = (end_secs - start_secs).seconds_to_f64();
|
||||
let clip = AudioClipInstance::new(
|
||||
let mut clip = AudioClipInstance::new(
|
||||
clip_id,
|
||||
pool_index,
|
||||
Seconds(offset),
|
||||
@@ -923,6 +1019,13 @@ impl Engine {
|
||||
Beats(duration),
|
||||
);
|
||||
|
||||
// If the source is streamed (a compressed audio file, or a video's
|
||||
// audio track), set up disk streaming instead of an in-memory decode.
|
||||
// Each clip instance gets its own read-ahead buffer keyed by clip_id.
|
||||
if let Some(buffer) = self.activate_streaming_for(clip_id as u64, pool_index) {
|
||||
clip.read_ahead = Some(buffer);
|
||||
}
|
||||
|
||||
// Add clip to track
|
||||
if let Some(crate::audio::track::TrackNode::Audio(track)) = self.project.get_track_mut(track_id) {
|
||||
track.clips.push(clip);
|
||||
@@ -2313,6 +2416,34 @@ impl Engine {
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a video file's audio track as a streaming pool entry (FFmpeg, decoded
|
||||
/// on demand — no extraction). Probes the audio track for channels/rate/frames
|
||||
/// without decoding, and returns the pool index. Playback activation
|
||||
/// (per-clip read-ahead) is wired separately when a clip references it.
|
||||
fn do_add_video_audio(&mut self, path: &std::path::Path) -> Result<usize, String> {
|
||||
use crate::audio::disk_reader::VideoAudioReader;
|
||||
|
||||
let reader = VideoAudioReader::open(path)?;
|
||||
let channels = reader.channels();
|
||||
let sample_rate = reader.sample_rate();
|
||||
let total_frames = reader.total_frames();
|
||||
drop(reader);
|
||||
|
||||
let audio_file = crate::audio::pool::AudioFile::from_video_audio(
|
||||
path.to_path_buf(),
|
||||
channels,
|
||||
sample_rate,
|
||||
total_frames,
|
||||
);
|
||||
let pool_index = self.audio_pool.add_file(audio_file);
|
||||
|
||||
eprintln!(
|
||||
"[ENGINE] AddVideoAudio: ch={}, sr={}, total_frames={}, pool_index={}, path={:?}",
|
||||
channels, sample_rate, total_frames, pool_index, path
|
||||
);
|
||||
Ok(pool_index)
|
||||
}
|
||||
|
||||
/// Import an audio file into the pool: mmap for PCM, streaming for compressed.
|
||||
/// Returns the pool index on success. Emits AudioFileReady event.
|
||||
fn do_import_audio(&mut self, path: &std::path::Path) -> Result<usize, String> {
|
||||
@@ -2738,10 +2869,14 @@ impl Engine {
|
||||
Query::GetPoolAudioSamples(pool_index) => {
|
||||
match self.audio_pool.get_file(pool_index) {
|
||||
Some(file) => {
|
||||
// For Compressed storage, return decoded_for_waveform if available
|
||||
// For streamed (Compressed/VideoAudio) storage, return the
|
||||
// progressively-decoded waveform overview if available.
|
||||
let samples = match &file.storage {
|
||||
crate::audio::pool::AudioStorage::Compressed {
|
||||
decoded_for_waveform, decoded_frames, ..
|
||||
}
|
||||
| crate::audio::pool::AudioStorage::VideoAudio {
|
||||
decoded_for_waveform, decoded_frames, ..
|
||||
} if *decoded_frames > 0 => {
|
||||
decoded_for_waveform.clone()
|
||||
}
|
||||
@@ -2794,77 +2929,12 @@ impl Engine {
|
||||
self.refresh_clip_snapshot();
|
||||
result
|
||||
}
|
||||
Query::AddAudioFileSync(path, data, channels, sample_rate) => {
|
||||
// Add audio file to pool and return the pool index
|
||||
// Detect original format from file extension
|
||||
let path_buf = std::path::PathBuf::from(&path);
|
||||
let original_format = path_buf.extension()
|
||||
.and_then(|ext| ext.to_str())
|
||||
.map(|s| s.to_lowercase());
|
||||
|
||||
// Create AudioFile and add to pool
|
||||
let audio_file = crate::audio::pool::AudioFile::with_format(
|
||||
path_buf.clone(),
|
||||
data.clone(), // Clone data for background thread
|
||||
channels,
|
||||
sample_rate,
|
||||
original_format,
|
||||
);
|
||||
let pool_index = self.audio_pool.add_file(audio_file);
|
||||
|
||||
// Generate Level 0 (overview) waveform chunks asynchronously in background thread
|
||||
let chunk_tx = self.chunk_generation_tx.clone();
|
||||
let duration = data.len() as f64 / (sample_rate as f64 * channels as f64);
|
||||
println!("🔄 [ENGINE] Spawning background thread to generate Level 0 chunks for pool {}", pool_index);
|
||||
std::thread::spawn(move || {
|
||||
// Create temporary AudioFile for chunk generation
|
||||
let temp_audio_file = crate::audio::pool::AudioFile::with_format(
|
||||
path_buf,
|
||||
data,
|
||||
channels,
|
||||
sample_rate,
|
||||
None,
|
||||
);
|
||||
|
||||
// Generate Level 0 chunks
|
||||
let chunk_count = crate::audio::waveform_cache::WaveformCache::calculate_chunk_count(duration, 0);
|
||||
println!("🔄 [BACKGROUND] Generating {} Level 0 chunks for pool {}", chunk_count, pool_index);
|
||||
let chunks = crate::audio::waveform_cache::WaveformCache::generate_chunks(
|
||||
&temp_audio_file,
|
||||
pool_index,
|
||||
0, // Level 0 (overview)
|
||||
&(0..chunk_count).collect::<Vec<_>>(),
|
||||
);
|
||||
|
||||
// Send chunks via MPSC channel (will be forwarded by audio thread)
|
||||
if !chunks.is_empty() {
|
||||
println!("📤 [BACKGROUND] Generated {} chunks, sending to audio thread (pool {})", chunks.len(), pool_index);
|
||||
let event_chunks: Vec<(u32, (f64, f64), Vec<crate::io::WaveformPeak>)> = chunks
|
||||
.into_iter()
|
||||
.map(|chunk| (chunk.chunk_index, chunk.time_range, chunk.peaks))
|
||||
.collect();
|
||||
|
||||
match chunk_tx.send(AudioEvent::WaveformChunksReady {
|
||||
pool_index,
|
||||
detail_level: 0,
|
||||
chunks: event_chunks,
|
||||
}) {
|
||||
Ok(_) => println!("✅ [BACKGROUND] Chunks sent successfully for pool {}", pool_index),
|
||||
Err(e) => eprintln!("❌ [BACKGROUND] Failed to send chunks: {}", e),
|
||||
}
|
||||
} else {
|
||||
eprintln!("⚠️ [BACKGROUND] No chunks generated for pool {}", pool_index);
|
||||
}
|
||||
});
|
||||
|
||||
// Notify UI about the new audio file (for event listeners)
|
||||
let _ = self.event_tx.push(AudioEvent::AudioFileAdded(pool_index, path));
|
||||
|
||||
QueryResponse::AudioFileAddedSync(Ok(pool_index))
|
||||
}
|
||||
Query::ImportAudioSync(path) => {
|
||||
QueryResponse::AudioImportedSync(self.do_import_audio(&path))
|
||||
}
|
||||
Query::AddVideoAudioSync(path) => {
|
||||
QueryResponse::AudioImportedSync(self.do_add_video_audio(&path))
|
||||
}
|
||||
Query::GetProject => {
|
||||
// Save graph presets before cloning — AudioTrack::clone() creates
|
||||
// a fresh default graph (not a copy), so the preset must be populated
|
||||
@@ -2879,11 +2949,19 @@ impl Engine {
|
||||
match project.rebuild_audio_graphs(self.buffer_pool.buffer_size()) {
|
||||
Ok(()) => {
|
||||
self.project = project;
|
||||
// Loaded clips bypass AddAudioClip, so their disk streaming was
|
||||
// never activated — do it now for every streaming-backed clip.
|
||||
self.activate_all_streaming_clips();
|
||||
self.refresh_clip_snapshot();
|
||||
QueryResponse::ProjectSet(Ok(()))
|
||||
}
|
||||
Err(e) => QueryResponse::ProjectSet(Err(format!("Failed to rebuild audio graphs: {}", e))),
|
||||
}
|
||||
}
|
||||
Query::SetBlobSourceFactory(factory) => {
|
||||
self.blob_source_factory = Some(factory);
|
||||
QueryResponse::BlobSourceFactorySet(Ok(()))
|
||||
}
|
||||
Query::DuplicateMidiClipSync(clip_id) => {
|
||||
match self.project.midi_clip_pool.duplicate_clip(clip_id) {
|
||||
Some(new_id) => QueryResponse::MidiClipDuplicated(Ok(new_id)),
|
||||
@@ -3395,16 +3473,6 @@ impl EngineController {
|
||||
}
|
||||
}
|
||||
|
||||
/// Add an audio file to the pool synchronously and get the pool index
|
||||
/// Returns the pool index where the audio file was added
|
||||
pub fn add_audio_file_sync(&mut self, path: String, data: Vec<f32>, channels: u32, sample_rate: u32) -> Result<usize, String> {
|
||||
let query = Query::AddAudioFileSync(path, data, channels, sample_rate);
|
||||
match self.send_query(query)? {
|
||||
QueryResponse::AudioFileAddedSync(result) => result,
|
||||
_ => Err("Unexpected query response".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Import an audio file asynchronously. The engine will memory-map WAV/AIFF
|
||||
/// files for instant availability, or set up stream decoding for compressed
|
||||
/// formats. Listen for `AudioEvent::AudioFileReady` to get the pool index.
|
||||
@@ -3427,6 +3495,30 @@ impl EngineController {
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a video file's audio track as a streaming pool entry (decoded on
|
||||
/// demand via FFmpeg — no extraction to disk or RAM). Probes the audio track
|
||||
/// and returns the pool index. Use this for a video clip's embedded audio.
|
||||
pub fn add_video_audio_sync(&mut self, path: std::path::PathBuf) -> Result<usize, String> {
|
||||
let query = Query::AddVideoAudioSync(path);
|
||||
match self.send_query(query)? {
|
||||
QueryResponse::AudioImportedSync(result) => result,
|
||||
_ => Err("Unexpected query response".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Install the host's packed-media byte-source factory. Must be called before
|
||||
/// loading a project so its container-packed audio can be streamed (the disk
|
||||
/// reader opens packed entries through this factory).
|
||||
pub fn set_blob_source_factory(
|
||||
&mut self,
|
||||
factory: std::sync::Arc<dyn crate::audio::disk_reader::AudioBlobSourceFactory>,
|
||||
) -> Result<(), String> {
|
||||
match self.send_query(Query::SetBlobSourceFactory(factory))? {
|
||||
QueryResponse::BlobSourceFactorySet(result) => result,
|
||||
_ => Err("Unexpected query response".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate the next unique audio clip instance ID (atomic, thread-safe)
|
||||
pub fn next_audio_clip_id(&self) -> AudioClipInstanceId {
|
||||
self.next_audio_clip_id.fetch_add(1, Ordering::Relaxed)
|
||||
|
||||
@@ -15,10 +15,12 @@ pub mod recording;
|
||||
pub mod sample_loader;
|
||||
pub mod track;
|
||||
pub mod waveform_cache;
|
||||
pub mod waveform_pyramid;
|
||||
|
||||
pub use automation::{AutomationLane, AutomationLaneId, AutomationPoint, CurveType, ParameterId};
|
||||
pub use buffer_pool::BufferPool;
|
||||
pub use clip::{AudioClipInstance, AudioClipInstanceId, Clip, ClipId};
|
||||
pub use disk_reader::{AudioBlobSourceFactory, MediaByteSource};
|
||||
pub use engine::{AudioClipSnapshot, Engine, EngineController};
|
||||
pub use export::{export_audio, ExportFormat, ExportSettings};
|
||||
pub use metronome::Metronome;
|
||||
|
||||
@@ -83,6 +83,16 @@ pub enum AudioStorage {
|
||||
decoded_frames: u64,
|
||||
total_frames: u64,
|
||||
},
|
||||
|
||||
/// Audio track of a video container, decoded on demand via FFmpeg
|
||||
/// (`VideoAudioReader`). The source video file is `AudioFile::path`. Like
|
||||
/// `Compressed`, playback is streamed through the disk reader and
|
||||
/// `decoded_for_waveform` is filled progressively for the overview.
|
||||
VideoAudio {
|
||||
decoded_for_waveform: Vec<f32>,
|
||||
decoded_frames: u64,
|
||||
total_frames: u64,
|
||||
},
|
||||
}
|
||||
|
||||
/// Audio file stored in the pool
|
||||
@@ -98,6 +108,10 @@ pub struct AudioFile {
|
||||
pub original_format: Option<String>,
|
||||
/// Original compressed file bytes (preserved across save/load to avoid re-encoding)
|
||||
pub original_bytes: Option<Vec<u8>>,
|
||||
/// When `Some`, this entry's bytes are packed in the project container (not on
|
||||
/// disk at `path`); the disk reader opens them via the host's
|
||||
/// `AudioBlobSourceFactory` using this media id. `None` ⇒ stream from `path`.
|
||||
pub packed_media_id: Option<String>,
|
||||
}
|
||||
|
||||
impl AudioFile {
|
||||
@@ -112,6 +126,7 @@ impl AudioFile {
|
||||
frames,
|
||||
original_format: None,
|
||||
original_bytes: None,
|
||||
packed_media_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,6 +141,7 @@ impl AudioFile {
|
||||
frames,
|
||||
original_format,
|
||||
original_bytes: None,
|
||||
packed_media_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,6 +174,7 @@ impl AudioFile {
|
||||
frames: total_frames,
|
||||
original_format: Some("wav".to_string()),
|
||||
original_bytes: None,
|
||||
packed_media_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,6 +198,32 @@ impl AudioFile {
|
||||
frames: total_frames,
|
||||
original_format,
|
||||
original_bytes: None,
|
||||
packed_media_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a placeholder AudioFile for a video's audio track. `path` is the
|
||||
/// source video file; the audio is streamed on demand by the disk reader's
|
||||
/// FFmpeg-backed `VideoAudioReader`.
|
||||
pub fn from_video_audio(
|
||||
path: PathBuf,
|
||||
channels: u32,
|
||||
sample_rate: u32,
|
||||
total_frames: u64,
|
||||
) -> Self {
|
||||
Self {
|
||||
path,
|
||||
storage: AudioStorage::VideoAudio {
|
||||
decoded_for_waveform: Vec::new(),
|
||||
decoded_frames: 0,
|
||||
total_frames,
|
||||
},
|
||||
channels,
|
||||
sample_rate,
|
||||
frames: total_frames,
|
||||
original_format: None,
|
||||
original_bytes: None,
|
||||
packed_media_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,8 +317,8 @@ impl AudioFile {
|
||||
}
|
||||
written
|
||||
}
|
||||
AudioStorage::Compressed { .. } => {
|
||||
// Compressed files are read through the disk reader
|
||||
AudioStorage::Compressed { .. } | AudioStorage::VideoAudio { .. } => {
|
||||
// Streamed through the disk reader, not via read_samples().
|
||||
0
|
||||
}
|
||||
}
|
||||
@@ -786,6 +829,18 @@ pub struct AudioPoolEntry {
|
||||
pub channels: u32,
|
||||
/// Embedded audio data (for files < 10MB)
|
||||
pub embedded_data: Option<EmbeddedAudioData>,
|
||||
/// Stable media id (UUID string) for the SQLite `.beam` container. When set,
|
||||
/// the audio bytes live in the container's `media` table keyed by this id
|
||||
/// (packed storage). `None` for referenced entries (use `relative_path`) or
|
||||
/// legacy ZIP-loaded entries. Populated by the file_io save/load layer.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub media_id: Option<String>,
|
||||
/// Transient carrier for this entry's serialized waveform-pyramid blob (LBWF
|
||||
/// bytes). Never serialized into project.json — the bytes live in the
|
||||
/// container's `media` table (kind `Waveform`). Set by the file_io save layer
|
||||
/// (in) and load layer (out); `None` everywhere else.
|
||||
#[serde(skip)]
|
||||
pub waveform_blob: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl AudioClipPool {
|
||||
@@ -800,6 +855,28 @@ impl AudioClipPool {
|
||||
let mut entries = Vec::new();
|
||||
|
||||
for (index, file) in self.files.iter().enumerate() {
|
||||
// Packed-in-container streaming entry: its bytes already live in the
|
||||
// `.beam` media table (kept in place across re-saves). Emit just the
|
||||
// media id — no path, no embedded bytes, nothing to decode.
|
||||
if let Some(media_id) = &file.packed_media_id {
|
||||
entries.push(AudioPoolEntry {
|
||||
pool_index: index,
|
||||
waveform_blob: None,
|
||||
name: file
|
||||
.path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| format!("file_{}", index)),
|
||||
relative_path: None,
|
||||
duration: file.duration_seconds(),
|
||||
sample_rate: file.sample_rate,
|
||||
channels: file.channels,
|
||||
embedded_data: None,
|
||||
media_id: Some(media_id.clone()),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
let file_path = &file.path;
|
||||
let file_path_str = file_path.to_string_lossy();
|
||||
|
||||
@@ -830,6 +907,7 @@ impl AudioClipPool {
|
||||
|
||||
let entry = AudioPoolEntry {
|
||||
pool_index: index,
|
||||
waveform_blob: None,
|
||||
name: file_path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
@@ -839,6 +917,7 @@ impl AudioClipPool {
|
||||
sample_rate: file.sample_rate,
|
||||
channels: file.channels,
|
||||
embedded_data,
|
||||
media_id: None,
|
||||
};
|
||||
|
||||
entries.push(entry);
|
||||
@@ -977,7 +1056,31 @@ impl AudioClipPool {
|
||||
let entry_start = std::time::Instant::now();
|
||||
eprintln!("📊 [LOAD_SERIALIZED] Processing entry {}/{}: '{}'", i + 1, entries.len(), entry.name);
|
||||
|
||||
let success = if let Some(ref embedded) = entry.embedded_data {
|
||||
let success = if entry.media_id.is_some() && entry.embedded_data.is_none() {
|
||||
// Packed-in-container streaming entry: build a Compressed placeholder
|
||||
// backed by the host blob factory (opened at clip-activation time).
|
||||
// No decode here — playback streams through the disk reader.
|
||||
let media_id = entry.media_id.clone().unwrap();
|
||||
let ext = std::path::Path::new(&entry.name)
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.map(|s| s.to_lowercase());
|
||||
let total_frames = (entry.duration * entry.sample_rate as f64).ceil() as u64;
|
||||
let mut file = AudioFile::from_compressed(
|
||||
PathBuf::from(&entry.name),
|
||||
entry.channels,
|
||||
entry.sample_rate,
|
||||
total_frames,
|
||||
ext,
|
||||
);
|
||||
file.packed_media_id = Some(media_id);
|
||||
if entry.pool_index < self.files.len() {
|
||||
self.files[entry.pool_index] = file;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else if let Some(ref embedded) = entry.embedded_data {
|
||||
// Load from embedded data
|
||||
eprintln!("📊 [LOAD_SERIALIZED] Entry has embedded data (format: {})", embedded.format);
|
||||
match Self::load_from_embedded_into_pool(self, entry.pool_index, embedded.clone(), &entry.name) {
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
//! Streaming min/max waveform LOD pyramid.
|
||||
//!
|
||||
//! A waveform pyramid is a tree of zoom levels. **Index = tree depth:**
|
||||
//! `levels[0]` is the **root** (a single texel — the min/max envelope of the
|
||||
//! whole file, lowest resolution); each deeper level is `BRANCH`× finer, and
|
||||
//! `levels.last()` is the **floor** (one texel per `floor_samples_per_texel`
|
||||
//! source frames — the finest *persisted* level). A node's children live at
|
||||
//! `index + 1`, so the residency invariant ("a node is cleared only after its
|
||||
//! children") reads straight off the index.
|
||||
//!
|
||||
//! Below the floor (finer than the floor bucket) is *not* stored; the caller
|
||||
//! re-decodes the source window on demand for true per-sample detail.
|
||||
//!
|
||||
//! The builder is **streaming**: samples are pushed once, in order, and only the
|
||||
//! finest level is accumulated (~`total_frames / floor` texels); the coarser
|
||||
//! levels are derived by repeated `BRANCH:1` min/max reduction in [`finish`].
|
||||
//! This yields the identical pyramid to an in-stream cascade (each parent = the
|
||||
//! min/max of its children) without ever holding the full sample buffer.
|
||||
//!
|
||||
//! **Ragged edges are handled by reducing over available children:** a bucket
|
||||
//! whose group is partial (1..BRANCH children, or `< floor` samples at the floor)
|
||||
//! simply takes the min/max of what's there — no value padding. Padding to a
|
||||
//! regular shape, if ever needed, is a GPU-texture/tile concern, not the data's.
|
||||
//!
|
||||
//! Each texel carries per-channel min/max for up to two channels
|
||||
//! (`Lmin,Lmax,Rmin,Rmax`), matching the GPU waveform texture; mono mirrors the
|
||||
//! left channel into the right.
|
||||
//!
|
||||
//! [`finish`]: WaveformPyramidBuilder::finish
|
||||
|
||||
/// Reduction factor between adjacent pyramid levels.
|
||||
pub const BRANCH: u32 = 4;
|
||||
|
||||
/// Default finest-level resolution (source frames per floor texel). Trades
|
||||
/// on-disk pyramid size against how soon zoom-in must re-decode the source.
|
||||
pub const DEFAULT_FLOOR_SAMPLES_PER_TEXEL: u32 = 256;
|
||||
|
||||
/// One waveform texel: per-channel min/max (stereo; mono duplicates left→right).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Texel {
|
||||
pub l_min: f32,
|
||||
pub l_max: f32,
|
||||
pub r_min: f32,
|
||||
pub r_max: f32,
|
||||
}
|
||||
|
||||
impl Texel {
|
||||
const EMPTY: Texel = Texel {
|
||||
l_min: f32::INFINITY,
|
||||
l_max: f32::NEG_INFINITY,
|
||||
r_min: f32::INFINITY,
|
||||
r_max: f32::NEG_INFINITY,
|
||||
};
|
||||
|
||||
#[inline]
|
||||
fn include_sample(&mut self, l: f32, r: f32) {
|
||||
self.l_min = self.l_min.min(l);
|
||||
self.l_max = self.l_max.max(l);
|
||||
self.r_min = self.r_min.min(r);
|
||||
self.r_max = self.r_max.max(r);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn include_texel(&mut self, c: &Texel) {
|
||||
self.l_min = self.l_min.min(c.l_min);
|
||||
self.l_max = self.l_max.max(c.l_max);
|
||||
self.r_min = self.r_min.min(c.r_min);
|
||||
self.r_max = self.r_max.max(c.r_max);
|
||||
}
|
||||
}
|
||||
|
||||
/// A built min/max LOD pyramid, **root-first**: `levels[0]` is the coarsest
|
||||
/// (whole-file envelope), `levels.last()` is the finest persisted (floor).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WaveformPyramid {
|
||||
pub floor_samples_per_texel: u32,
|
||||
pub branch: u32,
|
||||
pub channels: u32,
|
||||
pub total_frames: u64,
|
||||
pub levels: Vec<Vec<Texel>>,
|
||||
}
|
||||
|
||||
impl WaveformPyramid {
|
||||
/// Coarsest level — a single texel (whole-file envelope), or empty if no
|
||||
/// samples were pushed.
|
||||
pub fn root(&self) -> &[Texel] {
|
||||
self.levels.first().map_or(&[][..], |v| v)
|
||||
}
|
||||
|
||||
/// Finest persisted level (`floor_samples_per_texel` frames per texel).
|
||||
pub fn floor(&self) -> &[Texel] {
|
||||
self.levels.last().map_or(&[][..], |v| v)
|
||||
}
|
||||
|
||||
/// Number of levels (tree depth + 1).
|
||||
pub fn depth(&self) -> usize {
|
||||
self.levels.len()
|
||||
}
|
||||
|
||||
/// Serialize to a compact binary blob (for persisting in the `.beam`
|
||||
/// container). Header carries `B`/branch/channels/total_frames + per-level
|
||||
/// lengths, then root-first texel data (`f32` min/max).
|
||||
pub fn to_bytes(&self) -> Vec<u8> {
|
||||
let total_texels: usize = self.levels.iter().map(|l| l.len()).sum();
|
||||
let mut out = Vec::with_capacity(32 + self.levels.len() * 4 + total_texels * 16);
|
||||
out.extend_from_slice(b"LBWF");
|
||||
out.extend_from_slice(&1u32.to_le_bytes()); // format version
|
||||
out.extend_from_slice(&self.floor_samples_per_texel.to_le_bytes());
|
||||
out.extend_from_slice(&self.branch.to_le_bytes());
|
||||
out.extend_from_slice(&self.channels.to_le_bytes());
|
||||
out.extend_from_slice(&self.total_frames.to_le_bytes());
|
||||
out.extend_from_slice(&(self.levels.len() as u32).to_le_bytes());
|
||||
for level in &self.levels {
|
||||
out.extend_from_slice(&(level.len() as u32).to_le_bytes());
|
||||
}
|
||||
for level in &self.levels {
|
||||
for t in level {
|
||||
out.extend_from_slice(&t.l_min.to_le_bytes());
|
||||
out.extend_from_slice(&t.l_max.to_le_bytes());
|
||||
out.extend_from_slice(&t.r_min.to_le_bytes());
|
||||
out.extend_from_slice(&t.r_max.to_le_bytes());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Reconstruct from [`WaveformPyramid::to_bytes`].
|
||||
pub fn from_bytes(data: &[u8]) -> Result<WaveformPyramid, String> {
|
||||
let mut r = ByteReader::new(data);
|
||||
if r.take(4)? != b"LBWF" {
|
||||
return Err("Not a waveform pyramid blob".to_string());
|
||||
}
|
||||
let version = r.u32()?;
|
||||
if version != 1 {
|
||||
return Err(format!("Unsupported waveform pyramid version {}", version));
|
||||
}
|
||||
let floor_samples_per_texel = r.u32()?;
|
||||
let branch = r.u32()?;
|
||||
let channels = r.u32()?;
|
||||
let total_frames = r.u64()?;
|
||||
let num_levels = r.u32()? as usize;
|
||||
let mut level_lens = Vec::with_capacity(num_levels);
|
||||
for _ in 0..num_levels {
|
||||
level_lens.push(r.u32()? as usize);
|
||||
}
|
||||
let mut levels = Vec::with_capacity(num_levels);
|
||||
for &len in &level_lens {
|
||||
let mut level = Vec::with_capacity(len);
|
||||
for _ in 0..len {
|
||||
level.push(Texel {
|
||||
l_min: r.f32()?,
|
||||
l_max: r.f32()?,
|
||||
r_min: r.f32()?,
|
||||
r_max: r.f32()?,
|
||||
});
|
||||
}
|
||||
levels.push(level);
|
||||
}
|
||||
Ok(WaveformPyramid {
|
||||
floor_samples_per_texel,
|
||||
branch,
|
||||
channels,
|
||||
total_frames,
|
||||
levels,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal little-endian byte cursor for [`WaveformPyramid::from_bytes`].
|
||||
struct ByteReader<'a> {
|
||||
data: &'a [u8],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl<'a> ByteReader<'a> {
|
||||
fn new(data: &'a [u8]) -> Self {
|
||||
Self { data, pos: 0 }
|
||||
}
|
||||
fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
|
||||
let end = self.pos.checked_add(n).ok_or("overflow")?;
|
||||
if end > self.data.len() {
|
||||
return Err("Truncated waveform pyramid blob".to_string());
|
||||
}
|
||||
let s = &self.data[self.pos..end];
|
||||
self.pos = end;
|
||||
Ok(s)
|
||||
}
|
||||
fn u32(&mut self) -> Result<u32, String> {
|
||||
Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap()))
|
||||
}
|
||||
fn u64(&mut self) -> Result<u64, String> {
|
||||
Ok(u64::from_le_bytes(self.take(8)?.try_into().unwrap()))
|
||||
}
|
||||
fn f32(&mut self) -> Result<f32, String> {
|
||||
Ok(f32::from_le_bytes(self.take(4)?.try_into().unwrap()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Streaming builder for a [`WaveformPyramid`]. See the module docs.
|
||||
pub struct WaveformPyramidBuilder {
|
||||
floor: u32,
|
||||
branch: u32,
|
||||
channels: u32,
|
||||
total_frames: u64,
|
||||
floor_level: Vec<Texel>,
|
||||
acc: Texel,
|
||||
acc_count: u32,
|
||||
}
|
||||
|
||||
impl WaveformPyramidBuilder {
|
||||
pub fn new(channels: u32, floor_samples_per_texel: u32) -> Self {
|
||||
Self {
|
||||
floor: floor_samples_per_texel.max(1),
|
||||
branch: BRANCH,
|
||||
channels: channels.max(1),
|
||||
total_frames: 0,
|
||||
floor_level: Vec::new(),
|
||||
acc: Texel::EMPTY,
|
||||
acc_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Pre-reserve the floor `Vec` from an estimated total frame count (e.g. the
|
||||
/// probe's `total_frames`), to avoid reallocations during streaming. Purely a
|
||||
/// hint — the final size is set by the actual number of frames pushed.
|
||||
pub fn reserve_for_frames(&mut self, estimated_frames: u64) {
|
||||
let est_texels = (estimated_frames / self.floor as u64).saturating_add(1);
|
||||
self.floor_level.reserve(est_texels.min(usize::MAX as u64) as usize);
|
||||
}
|
||||
|
||||
/// Push a block of interleaved samples (`channels` per frame). Partial
|
||||
/// trailing frames (fewer than `channels`) are ignored.
|
||||
pub fn push_interleaved(&mut self, samples: &[f32]) {
|
||||
let ch = self.channels as usize;
|
||||
for frame in samples.chunks_exact(ch) {
|
||||
let l = frame[0];
|
||||
let r = if ch >= 2 { frame[1] } else { l };
|
||||
self.push_frame(l, r);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn push_frame(&mut self, l: f32, r: f32) {
|
||||
self.total_frames += 1;
|
||||
self.acc.include_sample(l, r);
|
||||
self.acc_count += 1;
|
||||
if self.acc_count >= self.floor {
|
||||
self.floor_level.push(std::mem::replace(&mut self.acc, Texel::EMPTY));
|
||||
self.acc_count = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Flush the trailing partial bucket and reduce up to the root.
|
||||
pub fn finish(mut self) -> WaveformPyramid {
|
||||
if self.acc_count > 0 {
|
||||
self.floor_level.push(self.acc);
|
||||
}
|
||||
|
||||
// Build finest-first by repeated BRANCH:1 reduction until one texel.
|
||||
// The shape is fully determined by the floor texel count; the last group
|
||||
// at each level may be ragged (1..BRANCH children) and reduces over what
|
||||
// it has.
|
||||
let mut levels = vec![std::mem::take(&mut self.floor_level)];
|
||||
let branch = self.branch as usize;
|
||||
while levels.last().map_or(0, |l| l.len()) > 1 {
|
||||
let prev = levels.last().unwrap();
|
||||
let mut next = Vec::with_capacity(prev.len().div_ceil(branch));
|
||||
for chunk in prev.chunks(branch) {
|
||||
let mut t = Texel::EMPTY;
|
||||
for c in chunk {
|
||||
t.include_texel(c);
|
||||
}
|
||||
next.push(t);
|
||||
}
|
||||
levels.push(next);
|
||||
}
|
||||
// Output is root-first (convention B): levels[0] = root, last = floor.
|
||||
levels.reverse();
|
||||
|
||||
WaveformPyramid {
|
||||
floor_samples_per_texel: self.floor,
|
||||
branch: self.branch,
|
||||
channels: self.channels,
|
||||
total_frames: self.total_frames,
|
||||
levels,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tests live in `daw-backend/tests/waveform_pyramid.rs` (integration tests) so
|
||||
// they build the lib in normal mode, independent of the crate's pre-existing
|
||||
// broken `#[cfg(test)]` unit tests (automation.rs).
|
||||
@@ -430,8 +430,6 @@ pub enum Query {
|
||||
/// Add a MIDI clip instance to a track synchronously (track_id, instance) - returns instance ID
|
||||
/// The clip must already exist in the MidiClipPool
|
||||
AddMidiClipInstanceSync(TrackId, crate::audio::midi::MidiClipInstance),
|
||||
/// Add an audio file to the pool synchronously (path, data, channels, sample_rate) - returns pool index
|
||||
AddAudioFileSync(String, Vec<f32>, u32, u32),
|
||||
/// Import an audio file synchronously (path) - returns pool index.
|
||||
/// Does the same work as Command::ImportAudio (mmap for PCM, streaming
|
||||
/// setup for compressed) but returns the real pool index in the response.
|
||||
@@ -440,12 +438,20 @@ pub enum Query {
|
||||
/// problem for very large files, switch to async import with event-based
|
||||
/// pool index reconciliation.
|
||||
ImportAudioSync(std::path::PathBuf),
|
||||
/// Add the audio track of a video file as a streaming pool entry (FFmpeg,
|
||||
/// decoded on demand — no extraction). Probes the audio track and returns
|
||||
/// the pool index. Response: `AudioImportedSync`.
|
||||
AddVideoAudioSync(std::path::PathBuf),
|
||||
/// Get raw audio samples from pool (pool_index) - returns (samples, sample_rate, channels)
|
||||
GetPoolAudioSamples(usize),
|
||||
/// Get a clone of the current project for serialization
|
||||
GetProject,
|
||||
/// Set the project (replaces current project state)
|
||||
SetProject(Box<crate::audio::project::Project>),
|
||||
/// Install the host's packed-media byte-source factory (for streaming
|
||||
/// container-packed audio on load). Sent before `SetProject` so bulk
|
||||
/// activation can open packed sources.
|
||||
SetBlobSourceFactory(std::sync::Arc<dyn crate::audio::disk_reader::AudioBlobSourceFactory>),
|
||||
/// Duplicate a MIDI clip in the pool, returning the new clip's ID
|
||||
DuplicateMidiClipSync(MidiClipId),
|
||||
/// Get whether a track's graph is still the auto-generated default
|
||||
@@ -516,10 +522,10 @@ pub enum QueryResponse {
|
||||
AudioExported(Result<(), String>),
|
||||
/// MIDI clip instance added (returns instance ID)
|
||||
MidiClipInstanceAdded(Result<MidiClipInstanceId, String>),
|
||||
/// Audio file added to pool (returns pool index)
|
||||
AudioFileAddedSync(Result<usize, String>),
|
||||
/// Audio file imported to pool (returns pool index)
|
||||
AudioImportedSync(Result<usize, String>),
|
||||
/// Packed-media byte-source factory installed
|
||||
BlobSourceFactorySet(Result<(), String>),
|
||||
/// Raw audio samples from pool (samples, sample_rate, channels)
|
||||
PoolAudioSamples(Result<(Vec<f32>, u32, u32), String>),
|
||||
/// Project retrieved
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
//! Integration test for `CompressedReader::open_source` — decoding a streaming
|
||||
//! audio source from an in-memory byte stream (the packed-in-container path)
|
||||
//! rather than a filesystem path. Proves the `MediaByteSource` adapter feeds
|
||||
//! Symphonia correctly (probe + decode + seekable byte length).
|
||||
|
||||
use std::io::{Cursor, Read, Seek, SeekFrom};
|
||||
|
||||
use daw_backend::audio::disk_reader::{CompressedReader, MediaByteSource};
|
||||
|
||||
/// A `MediaByteSource` over an in-memory buffer (stands in for core's BlobReader).
|
||||
struct VecSource(Cursor<Vec<u8>>);
|
||||
|
||||
impl Read for VecSource {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
self.0.read(buf)
|
||||
}
|
||||
}
|
||||
impl Seek for VecSource {
|
||||
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
|
||||
self.0.seek(pos)
|
||||
}
|
||||
}
|
||||
impl MediaByteSource for VecSource {
|
||||
fn byte_len(&self) -> u64 {
|
||||
self.0.get_ref().len() as u64
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a minimal PCM16 mono WAV byte buffer holding `frames` samples of a ramp.
|
||||
fn make_wav(sample_rate: u32, frames: u32) -> Vec<u8> {
|
||||
let channels: u16 = 1;
|
||||
let bits: u16 = 16;
|
||||
let block_align: u16 = channels * bits / 8;
|
||||
let byte_rate: u32 = sample_rate * block_align as u32;
|
||||
let data_len: u32 = frames * block_align as u32;
|
||||
|
||||
let mut v = Vec::new();
|
||||
v.extend_from_slice(b"RIFF");
|
||||
v.extend_from_slice(&(36 + data_len).to_le_bytes());
|
||||
v.extend_from_slice(b"WAVE");
|
||||
v.extend_from_slice(b"fmt ");
|
||||
v.extend_from_slice(&16u32.to_le_bytes());
|
||||
v.extend_from_slice(&1u16.to_le_bytes()); // PCM
|
||||
v.extend_from_slice(&channels.to_le_bytes());
|
||||
v.extend_from_slice(&sample_rate.to_le_bytes());
|
||||
v.extend_from_slice(&byte_rate.to_le_bytes());
|
||||
v.extend_from_slice(&block_align.to_le_bytes());
|
||||
v.extend_from_slice(&bits.to_le_bytes());
|
||||
v.extend_from_slice(b"data");
|
||||
v.extend_from_slice(&data_len.to_le_bytes());
|
||||
for i in 0..frames {
|
||||
// A ramp from -16000..16000 so values are recognizable.
|
||||
let s = (((i % 1000) as i32 - 500) * 32) as i16;
|
||||
v.extend_from_slice(&s.to_le_bytes());
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_source_decodes_in_memory_wav() {
|
||||
let sample_rate = 8000;
|
||||
let frames = 4096;
|
||||
let bytes = make_wav(sample_rate, frames);
|
||||
|
||||
let src = Box::new(VecSource(Cursor::new(bytes)));
|
||||
let mut reader = CompressedReader::open_source(src, Some("wav"))
|
||||
.expect("open_source should probe the in-memory WAV");
|
||||
|
||||
assert_eq!(reader.sample_rate(), sample_rate);
|
||||
assert_eq!(reader.channels(), 1);
|
||||
|
||||
// Decode the whole stream and count emitted frames.
|
||||
let mut buf = Vec::new();
|
||||
let mut decoded = 0usize;
|
||||
loop {
|
||||
let n = reader.decode_next(&mut buf).expect("decode_next");
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
decoded += n;
|
||||
}
|
||||
// Should recover (approximately) all frames — codec frame counts can round.
|
||||
assert!(
|
||||
(decoded as i64 - frames as i64).abs() < 64,
|
||||
"decoded {} vs expected {}",
|
||||
decoded,
|
||||
frames
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
//! Integration tests for `VideoAudioReader` (FFmpeg streaming audio source).
|
||||
//!
|
||||
//! These build the daw-backend lib in normal mode, so they're independent of
|
||||
//! the crate's pre-existing broken `#[cfg(test)]` unit tests (automation.rs).
|
||||
//! They synthesize a mono 32-bit-float WAV whose sample `i` has value `i/n`, so
|
||||
//! a decoded sample's value identifies its frame index — letting us assert both
|
||||
//! in-order decoding and **sample-accurate seeking** (the property video audio
|
||||
//! needs to stay synced with other clips).
|
||||
|
||||
use daw_backend::audio::disk_reader::{
|
||||
build_waveform_pyramid, CompressedReader, SourceKind, VideoAudioReader,
|
||||
};
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
fn write_ramp_wav(path: &Path, n: u32, sample_rate: u32) {
|
||||
let channels = 1u16;
|
||||
let bytes_per_sample = 4u32;
|
||||
let data_size = n * bytes_per_sample;
|
||||
let mut buf: Vec<u8> = Vec::with_capacity(44 + data_size as usize);
|
||||
buf.extend_from_slice(b"RIFF");
|
||||
buf.extend_from_slice(&(36 + data_size).to_le_bytes());
|
||||
buf.extend_from_slice(b"WAVE");
|
||||
buf.extend_from_slice(b"fmt ");
|
||||
buf.extend_from_slice(&16u32.to_le_bytes());
|
||||
buf.extend_from_slice(&3u16.to_le_bytes()); // IEEE float
|
||||
buf.extend_from_slice(&channels.to_le_bytes());
|
||||
buf.extend_from_slice(&sample_rate.to_le_bytes());
|
||||
buf.extend_from_slice(&(sample_rate * channels as u32 * bytes_per_sample).to_le_bytes());
|
||||
buf.extend_from_slice(&((channels as u32 * bytes_per_sample) as u16).to_le_bytes());
|
||||
buf.extend_from_slice(&32u16.to_le_bytes());
|
||||
buf.extend_from_slice(b"data");
|
||||
buf.extend_from_slice(&data_size.to_le_bytes());
|
||||
for i in 0..n {
|
||||
buf.extend_from_slice(&((i as f32) / (n as f32)).to_le_bytes());
|
||||
}
|
||||
let mut f = std::fs::File::create(path).unwrap();
|
||||
f.write_all(&buf).unwrap();
|
||||
}
|
||||
|
||||
/// Stereo ramp: frame `i` has left = `i/n`, right = `0.5 - i/n` (distinct per
|
||||
/// channel), interleaved `[L0,R0,L1,R1,…]`. Exercises the channels>1 path.
|
||||
fn write_stereo_ramp_wav(path: &Path, n: u32, sample_rate: u32) {
|
||||
let channels = 2u16;
|
||||
let bytes_per_sample = 4u32;
|
||||
let data_size = n * channels as u32 * bytes_per_sample;
|
||||
let mut buf: Vec<u8> = Vec::with_capacity(44 + data_size as usize);
|
||||
buf.extend_from_slice(b"RIFF");
|
||||
buf.extend_from_slice(&(36 + data_size).to_le_bytes());
|
||||
buf.extend_from_slice(b"WAVE");
|
||||
buf.extend_from_slice(b"fmt ");
|
||||
buf.extend_from_slice(&16u32.to_le_bytes());
|
||||
buf.extend_from_slice(&3u16.to_le_bytes()); // IEEE float
|
||||
buf.extend_from_slice(&channels.to_le_bytes());
|
||||
buf.extend_from_slice(&sample_rate.to_le_bytes());
|
||||
buf.extend_from_slice(&(sample_rate * channels as u32 * bytes_per_sample).to_le_bytes());
|
||||
buf.extend_from_slice(&((channels as u32 * bytes_per_sample) as u16).to_le_bytes());
|
||||
buf.extend_from_slice(&32u16.to_le_bytes());
|
||||
buf.extend_from_slice(b"data");
|
||||
buf.extend_from_slice(&data_size.to_le_bytes());
|
||||
for i in 0..n {
|
||||
let l = i as f32 / n as f32;
|
||||
let r = 0.5 - i as f32 / n as f32;
|
||||
buf.extend_from_slice(&l.to_le_bytes());
|
||||
buf.extend_from_slice(&r.to_le_bytes());
|
||||
}
|
||||
let mut f = std::fs::File::create(path).unwrap();
|
||||
f.write_all(&buf).unwrap();
|
||||
}
|
||||
|
||||
fn temp_path(tag: &str) -> std::path::PathBuf {
|
||||
let mut p = std::env::temp_dir();
|
||||
p.push(format!("lb_videoaudio_test_{}_{}.wav", std::process::id(), tag));
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_samples_in_order() {
|
||||
let n = 4000u32;
|
||||
let sr = 8000u32;
|
||||
let path = temp_path("seq");
|
||||
write_ramp_wav(&path, n, sr);
|
||||
|
||||
let mut reader = VideoAudioReader::open(&path).unwrap();
|
||||
assert_eq!(reader.channels(), 1);
|
||||
assert_eq!(reader.sample_rate(), sr);
|
||||
// Probe estimate (used by add_video_audio_sync) should be ~n frames.
|
||||
let tf = reader.total_frames() as f64;
|
||||
assert!(
|
||||
(tf - n as f64).abs() < n as f64 * 0.1,
|
||||
"total_frames {} not ~{}",
|
||||
tf, n
|
||||
);
|
||||
|
||||
let mut all = Vec::new();
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
let frames = reader.decode_next(&mut buf).unwrap();
|
||||
if frames == 0 {
|
||||
break;
|
||||
}
|
||||
all.extend_from_slice(&buf);
|
||||
}
|
||||
|
||||
// Allow a couple of priming/flush samples of slack at the very end.
|
||||
assert!(all.len() + 4 >= n as usize, "decoded too few samples: {}", all.len());
|
||||
for (i, &v) in all.iter().enumerate().take(n as usize) {
|
||||
let expected = i as f32 / n as f32;
|
||||
assert!((v - expected).abs() < 1e-3, "sample {} = {}, expected {}", i, v, expected);
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
/// CompressedReader (symphonia) must seek **sample-accurately** too, so compressed
|
||||
/// audio stays frame-synced with video audio. Symphonia decodes WAV via the same
|
||||
/// path; its coarse seek lands on packet boundaries, exercising the decode-discard.
|
||||
#[test]
|
||||
fn compressed_reader_seek_is_sample_accurate() {
|
||||
let n = 4000u32;
|
||||
let sr = 8000u32;
|
||||
let path = temp_path("comp_seek");
|
||||
write_ramp_wav(&path, n, sr);
|
||||
|
||||
let mut reader = CompressedReader::open(&path).unwrap();
|
||||
assert_eq!(reader.channels(), 1);
|
||||
assert_eq!(reader.sample_rate(), sr);
|
||||
|
||||
for &target in &[2000u64, 137, 3500, 0] {
|
||||
let actual = reader.seek(target).unwrap();
|
||||
assert_eq!(actual, target, "seek should report the exact target");
|
||||
|
||||
let mut buf = Vec::new();
|
||||
let mut frames = 0;
|
||||
for _ in 0..128 {
|
||||
frames = reader.decode_next(&mut buf).unwrap();
|
||||
if frames > 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(frames > 0, "no samples after seek to {}", target);
|
||||
let expected = target as f32 / n as f32;
|
||||
assert!(
|
||||
(buf[0] - expected).abs() < 1e-3,
|
||||
"compressed seek to {}: first sample = {}, expected {}",
|
||||
target, buf[0], expected
|
||||
);
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
/// The decode→pyramid bridge should produce an envelope matching the signal,
|
||||
/// through both reader backends (symphonia + ffmpeg), with bounded memory.
|
||||
#[test]
|
||||
fn waveform_pyramid_from_decode_matches_signal() {
|
||||
let n = 5000u32;
|
||||
let sr = 8000u32;
|
||||
let path = temp_path("pyr");
|
||||
write_ramp_wav(&path, n, sr); // ramp 0 .. (n-1)/n, all positive
|
||||
|
||||
for kind in [SourceKind::CompressedAudio, SourceKind::VideoAudio] {
|
||||
let p = build_waveform_pyramid(&path, kind, 256).unwrap();
|
||||
assert_eq!(p.channels, 1);
|
||||
assert_eq!(p.root().len(), 1, "{:?}: root should be one texel", kind);
|
||||
let root = p.root()[0];
|
||||
assert!(root.l_min.abs() < 1e-2, "{:?}: root min {} ~ 0", kind, root.l_min);
|
||||
let expected_max = (n - 1) as f32 / n as f32;
|
||||
assert!(
|
||||
(root.l_max - expected_max).abs() < 1e-2,
|
||||
"{:?}: root max {} ~ {}", kind, root.l_max, expected_max
|
||||
);
|
||||
// Frame count is approximate across decoders (priming/resampler overhead);
|
||||
// the envelope above is the real check. Just confirm it's about right.
|
||||
assert!((p.total_frames as i64 - n as i64).abs() < 128, "{:?}: frames {}", kind, p.total_frames);
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_stereo_interleaved() {
|
||||
let n = 2000u32;
|
||||
let sr = 8000u32;
|
||||
let path = temp_path("stereo");
|
||||
write_stereo_ramp_wav(&path, n, sr);
|
||||
|
||||
let mut reader = VideoAudioReader::open(&path).unwrap();
|
||||
assert_eq!(reader.channels(), 2);
|
||||
|
||||
let mut all = Vec::new();
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
let frames = reader.decode_next(&mut buf).unwrap();
|
||||
if frames == 0 {
|
||||
break;
|
||||
}
|
||||
// Each decode_next returns whole interleaved frames.
|
||||
assert_eq!(buf.len() % 2, 0, "stereo decode returned a partial frame");
|
||||
all.extend_from_slice(&buf);
|
||||
}
|
||||
|
||||
// Interleaved L/R, ~n frames.
|
||||
assert!(all.len() + 8 >= (n * 2) as usize, "decoded too few samples: {}", all.len());
|
||||
for i in 0..n as usize {
|
||||
let l = all[2 * i];
|
||||
let r = all[2 * i + 1];
|
||||
assert!((l - i as f32 / n as f32).abs() < 1e-3, "L[{}]={} expected {}", i, l, i as f32 / n as f32);
|
||||
assert!(
|
||||
(r - (0.5 - i as f32 / n as f32)).abs() < 1e-3,
|
||||
"R[{}]={} expected {}", i, r, 0.5 - i as f32 / n as f32
|
||||
);
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seek_is_sample_accurate() {
|
||||
let n = 4000u32;
|
||||
let sr = 8000u32;
|
||||
let path = temp_path("seek");
|
||||
write_ramp_wav(&path, n, sr);
|
||||
|
||||
let mut reader = VideoAudioReader::open(&path).unwrap();
|
||||
|
||||
for &target in &[2000u64, 137, 3500, 0] {
|
||||
let actual = reader.seek(target).unwrap();
|
||||
assert_eq!(actual, target);
|
||||
|
||||
// Pull the first non-empty decode after the seek.
|
||||
let mut buf = Vec::new();
|
||||
let mut frames = 0;
|
||||
for _ in 0..64 {
|
||||
frames = reader.decode_next(&mut buf).unwrap();
|
||||
if frames > 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(frames > 0, "no samples after seek to {}", target);
|
||||
|
||||
let expected = target as f32 / n as f32;
|
||||
assert!(
|
||||
(buf[0] - expected).abs() < 1e-3,
|
||||
"after seek to {}: first sample = {}, expected {}",
|
||||
target,
|
||||
buf[0],
|
||||
expected
|
||||
);
|
||||
// And the next few advance in order.
|
||||
for k in 0..frames.min(8) {
|
||||
let exp = (target as usize + k) as f32 / n as f32;
|
||||
assert!((buf[k] - exp).abs() < 1e-3, "seek {}+{}: {} vs {}", target, k, buf[k], exp);
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
//! Integration tests for the streaming waveform LOD pyramid builder.
|
||||
//!
|
||||
//! Convention B: `levels[0]` is the root (coarsest), `levels.last()` the floor
|
||||
//! (finest). Tests use the `.root()` / `.floor()` accessors so they don't depend
|
||||
//! on the raw index ordering.
|
||||
|
||||
use daw_backend::audio::waveform_pyramid::{Texel, WaveformPyramid, WaveformPyramidBuilder};
|
||||
|
||||
fn build_mono(samples: &[f32], floor: u32) -> WaveformPyramid {
|
||||
let mut b = WaveformPyramidBuilder::new(1, floor);
|
||||
b.push_interleaved(samples);
|
||||
b.finish()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floor_level_min_max_per_bucket() {
|
||||
// 8 samples, floor 4 → two floor texels covering [0..4) and [4..8).
|
||||
let s: Vec<f32> = (0..8).map(|i| i as f32).collect();
|
||||
let p = build_mono(&s, 4);
|
||||
assert_eq!(p.floor().len(), 2);
|
||||
assert_eq!(p.floor()[0], Texel { l_min: 0.0, l_max: 3.0, r_min: 0.0, r_max: 3.0 });
|
||||
assert_eq!(p.floor()[1], Texel { l_min: 4.0, l_max: 7.0, r_min: 4.0, r_max: 7.0 });
|
||||
// Root reduces the two floor texels into the envelope [0..8).
|
||||
assert_eq!(p.root().len(), 1);
|
||||
assert_eq!(p.root()[0], Texel { l_min: 0.0, l_max: 7.0, r_min: 0.0, r_max: 7.0 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_trailing_bucket_is_flushed() {
|
||||
// 6 samples, floor 4 → texels [0..4) and a ragged [4..6).
|
||||
let s: Vec<f32> = (0..6).map(|i| i as f32).collect();
|
||||
let p = build_mono(&s, 4);
|
||||
assert_eq!(p.floor().len(), 2);
|
||||
assert_eq!(p.floor()[1], Texel { l_min: 4.0, l_max: 5.0, r_min: 4.0, r_max: 5.0 });
|
||||
assert_eq!(p.total_frames, 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_level_envelope_matches_global_min_max() {
|
||||
let s: Vec<f32> = (0..1000).map(|i| ((i as f32) * 0.01).sin()).collect();
|
||||
let g_min = s.iter().cloned().fold(f32::INFINITY, f32::min);
|
||||
let g_max = s.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
|
||||
let p = build_mono(&s, 16);
|
||||
assert_eq!(p.root().len(), 1);
|
||||
assert!((p.root()[0].l_min - g_min).abs() < 1e-6);
|
||||
assert!((p.root()[0].l_max - g_max).abs() < 1e-6);
|
||||
// Every level's overall min/max equals the global (extremes are lossless).
|
||||
for level in &p.levels {
|
||||
let lmin = level.iter().map(|t| t.l_min).fold(f32::INFINITY, f32::min);
|
||||
let lmax = level.iter().map(|t| t.l_max).fold(f32::NEG_INFINITY, f32::max);
|
||||
assert!((lmin - g_min).abs() < 1e-6);
|
||||
assert!((lmax - g_max).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn levels_are_root_first_and_get_finer() {
|
||||
let s: Vec<f32> = (0..1000).map(|i| i as f32).collect();
|
||||
let p = build_mono(&s, 16);
|
||||
// Root first, floor last; strictly finer (more texels) as depth increases.
|
||||
assert_eq!(p.root().len(), 1);
|
||||
assert!(p.depth() >= 3);
|
||||
for w in p.levels.windows(2) {
|
||||
assert!(w[1].len() >= w[0].len(), "deeper level should be finer");
|
||||
}
|
||||
// Floor has ceil(1000/16) = 63 texels.
|
||||
assert_eq!(p.floor().len(), 63);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stereo_channels_tracked_separately() {
|
||||
// L ramps up, R ramps down; interleaved.
|
||||
let n = 64;
|
||||
let mut s = Vec::new();
|
||||
for i in 0..n {
|
||||
s.push(i as f32); // L
|
||||
s.push(-(i as f32)); // R
|
||||
}
|
||||
let mut b = WaveformPyramidBuilder::new(2, 16);
|
||||
b.push_interleaved(&s);
|
||||
let p = b.finish();
|
||||
assert_eq!(p.root().len(), 1);
|
||||
assert_eq!(p.root()[0].l_min, 0.0);
|
||||
assert_eq!(p.root()[0].l_max, (n - 1) as f32);
|
||||
assert_eq!(p.root()[0].r_min, -((n - 1) as f32));
|
||||
assert_eq!(p.root()[0].r_max, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pyramid_size_is_bounded() {
|
||||
let n = 100_000usize;
|
||||
let s: Vec<f32> = (0..n).map(|i| (i % 7) as f32).collect();
|
||||
let floor = 256u32;
|
||||
let p = build_mono(&s, floor);
|
||||
let total: usize = p.levels.iter().map(|l| l.len()).sum();
|
||||
let floor_texels = (n as u32).div_ceil(floor) as usize;
|
||||
// Geometric bound: < floor_texels * branch/(branch-1) + small per-level slack.
|
||||
let bound = floor_texels * 4 / 3 + p.depth() + 2;
|
||||
assert!(total <= bound, "pyramid too big: {} > {}", total, bound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bytes_round_trip() {
|
||||
let s: Vec<f32> = (0..3333).map(|i| ((i as f32) * 0.013).sin()).collect();
|
||||
let p = build_mono(&s, 64);
|
||||
let bytes = p.to_bytes();
|
||||
let q = WaveformPyramid::from_bytes(&bytes).unwrap();
|
||||
assert_eq!(p.floor_samples_per_texel, q.floor_samples_per_texel);
|
||||
assert_eq!(p.branch, q.branch);
|
||||
assert_eq!(p.channels, q.channels);
|
||||
assert_eq!(p.total_frames, q.total_frames);
|
||||
assert_eq!(p.levels, q.levels);
|
||||
// Truncated/garbage input is rejected, not panicking.
|
||||
assert!(WaveformPyramid::from_bytes(&bytes[..bytes.len() - 4]).is_err());
|
||||
assert!(WaveformPyramid::from_bytes(b"nope").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pushing_in_arbitrary_chunks_matches() {
|
||||
// The streaming builder must be agnostic to how samples are chunked.
|
||||
let s: Vec<f32> = (0..5000).map(|i| ((i * 13) % 97) as f32 - 48.0).collect();
|
||||
let whole = build_mono(&s, 32);
|
||||
|
||||
let mut b = WaveformPyramidBuilder::new(1, 32);
|
||||
b.reserve_for_frames(5000);
|
||||
for chunk in s.chunks(37) {
|
||||
b.push_interleaved(chunk);
|
||||
}
|
||||
let chunked = b.finish();
|
||||
|
||||
assert_eq!(whole.depth(), chunked.depth());
|
||||
for (a, c) in whole.levels.iter().zip(chunked.levels.iter()) {
|
||||
assert_eq!(a, c);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user