Render audio waveforms on gpu
This commit is contained in:
@@ -17,6 +17,42 @@ use uuid::Uuid;
|
||||
use super::{DragClipType, DraggingAsset, NodePath, PaneRenderer, SharedPaneState};
|
||||
use crate::widgets::ImeTextField;
|
||||
|
||||
/// Derive min/max peak pairs from raw audio samples for thumbnail rendering.
|
||||
/// Downsamples to `num_peaks` (min, max) pairs by scanning chunks of samples.
|
||||
fn peaks_from_raw_audio(
|
||||
raw: &(Vec<f32>, u32, u32), // (samples, sample_rate, channels)
|
||||
num_peaks: usize,
|
||||
) -> Vec<(f32, f32)> {
|
||||
let (samples, _sr, channels) = raw;
|
||||
let ch = (*channels as usize).max(1);
|
||||
let total_frames = samples.len() / ch;
|
||||
if total_frames == 0 || num_peaks == 0 {
|
||||
return vec![];
|
||||
}
|
||||
let frames_per_peak = (total_frames as f64 / num_peaks as f64).max(1.0);
|
||||
let mut peaks = Vec::with_capacity(num_peaks);
|
||||
for i in 0..num_peaks {
|
||||
let start = (i as f64 * frames_per_peak) as usize;
|
||||
let end = (((i + 1) as f64 * frames_per_peak) as usize).min(total_frames);
|
||||
let mut min_val = f32::MAX;
|
||||
let mut max_val = f32::MIN;
|
||||
for frame in start..end {
|
||||
// Mix all channels together for the thumbnail
|
||||
let mut sample = 0.0f32;
|
||||
for c in 0..ch {
|
||||
sample += samples[frame * ch + c];
|
||||
}
|
||||
sample /= ch as f32;
|
||||
min_val = min_val.min(sample);
|
||||
max_val = max_val.max(sample);
|
||||
}
|
||||
if min_val <= max_val {
|
||||
peaks.push((min_val, max_val));
|
||||
}
|
||||
}
|
||||
peaks
|
||||
}
|
||||
|
||||
// Thumbnail constants
|
||||
const THUMBNAIL_SIZE: u32 = 64;
|
||||
const THUMBNAIL_PREVIEW_SECONDS: f64 = 10.0;
|
||||
@@ -1790,8 +1826,8 @@ impl AssetLibraryPane {
|
||||
if asset_category == AssetCategory::Audio && !self.thumbnail_cache.has(&asset_id) {
|
||||
if let Some(clip) = document.audio_clips.get(&asset_id) {
|
||||
if let AudioClipType::Sampled { audio_pool_index } = &clip.clip_type {
|
||||
shared.waveform_cache.get(audio_pool_index)
|
||||
.map(|peaks| peaks.iter().map(|p| (p.min, p.max)).collect())
|
||||
shared.raw_audio_cache.get(audio_pool_index)
|
||||
.map(|raw| peaks_from_raw_audio(raw, THUMBNAIL_SIZE as usize))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -2380,8 +2416,8 @@ impl AssetLibraryPane {
|
||||
match &clip.clip_type {
|
||||
AudioClipType::Sampled { audio_pool_index } => {
|
||||
let wave_color = egui::Color32::from_rgb(100, 200, 100);
|
||||
let waveform: Option<Vec<(f32, f32)>> = shared.waveform_cache.get(audio_pool_index)
|
||||
.map(|peaks| peaks.iter().map(|p| (p.min, p.max)).collect());
|
||||
let waveform: Option<Vec<(f32, f32)>> = shared.raw_audio_cache.get(audio_pool_index)
|
||||
.map(|raw| peaks_from_raw_audio(raw, THUMBNAIL_SIZE as usize));
|
||||
if let Some(ref peaks) = waveform {
|
||||
Some(generate_waveform_thumbnail(peaks, bg_color, wave_color))
|
||||
} else {
|
||||
@@ -2525,8 +2561,8 @@ impl AssetLibraryPane {
|
||||
match &clip.clip_type {
|
||||
AudioClipType::Sampled { audio_pool_index } => {
|
||||
let wave_color = egui::Color32::from_rgb(100, 200, 100);
|
||||
let waveform: Option<Vec<(f32, f32)>> = shared.waveform_cache.get(audio_pool_index)
|
||||
.map(|peaks| peaks.iter().map(|p| (p.min, p.max)).collect());
|
||||
let waveform: Option<Vec<(f32, f32)>> = shared.raw_audio_cache.get(audio_pool_index)
|
||||
.map(|raw| peaks_from_raw_audio(raw, THUMBNAIL_SIZE as usize));
|
||||
if let Some(ref peaks) = waveform {
|
||||
Some(generate_waveform_thumbnail(peaks, bg_color, wave_color))
|
||||
} else {
|
||||
@@ -2850,9 +2886,8 @@ impl AssetLibraryPane {
|
||||
if asset_category == AssetCategory::Audio && !self.thumbnail_cache.has(&asset_id) {
|
||||
if let Some(clip) = document.audio_clips.get(&asset_id) {
|
||||
if let AudioClipType::Sampled { audio_pool_index } = &clip.clip_type {
|
||||
// Use cached waveform data (populated by fetch_waveform in main.rs)
|
||||
let waveform = shared.waveform_cache.get(audio_pool_index)
|
||||
.map(|peaks| peaks.iter().map(|p| (p.min, p.max)).collect());
|
||||
let waveform: Option<Vec<(f32, f32)>> = shared.raw_audio_cache.get(audio_pool_index)
|
||||
.map(|raw| peaks_from_raw_audio(raw, THUMBNAIL_SIZE as usize));
|
||||
if waveform.is_some() {
|
||||
println!("🎵 Found waveform for pool {} (asset {})", audio_pool_index, asset_id);
|
||||
} else {
|
||||
|
||||
@@ -189,15 +189,12 @@ pub struct SharedPaneState<'a> {
|
||||
pub polygon_sides: &'a mut u32,
|
||||
/// Cache of MIDI events for rendering (keyed by backend midi_clip_id)
|
||||
pub midi_event_cache: &'a std::collections::HashMap<u32, Vec<(f64, u8, bool)>>,
|
||||
/// Cache of waveform data for rendering (keyed by audio_pool_index)
|
||||
pub waveform_cache: &'a std::collections::HashMap<usize, Vec<daw_backend::WaveformPeak>>,
|
||||
/// Chunk-based waveform cache for multi-resolution waveforms
|
||||
/// Format: (pool_index, detail_level, chunk_index) -> Vec<WaveformPeak>
|
||||
pub waveform_chunk_cache: &'a std::collections::HashMap<(usize, u8, u32), Vec<daw_backend::WaveformPeak>>,
|
||||
/// Cache of rendered waveform images (GPU textures) for fast blitting
|
||||
pub waveform_image_cache: &'a mut crate::waveform_image_cache::WaveformImageCache,
|
||||
/// Audio pool indices that got new waveform data this frame (for thumbnail invalidation)
|
||||
/// Audio pool indices that got new raw audio data this frame (for thumbnail invalidation)
|
||||
pub audio_pools_with_new_waveforms: &'a std::collections::HashSet<usize>,
|
||||
/// Raw audio samples for GPU waveform rendering (pool_index -> (samples, sample_rate, channels))
|
||||
pub raw_audio_cache: &'a std::collections::HashMap<usize, (Vec<f32>, u32, u32)>,
|
||||
/// Pool indices needing GPU waveform texture upload
|
||||
pub waveform_gpu_dirty: &'a mut std::collections::HashSet<usize>,
|
||||
/// Effect ID to load into shader editor (set by asset library, consumed by shader editor)
|
||||
pub effect_to_load: &'a mut Option<Uuid>,
|
||||
/// Queue for effect thumbnail requests (effect IDs to generate thumbnails for)
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
// Waveform rendering shader for audio data stored in 2D Rgba16Float textures.
|
||||
// Audio samples are packed row-major into 2D: frame_index = y * tex_width + x
|
||||
// Mip levels use min/max reduction (4 consecutive samples per level).
|
||||
//
|
||||
// At full zoom, min≈max → renders as a continuous wave.
|
||||
// At zoom-out, min/max spread → renders as filled peak region.
|
||||
//
|
||||
// display_mode: 0 = combined (mono mix), 1 = split (left top, right bottom)
|
||||
|
||||
struct Params {
|
||||
// Clip rectangle in screen pixels (min.x, min.y, max.x, max.y)
|
||||
clip_rect: vec4<f32>,
|
||||
// Timeline viewport parameters
|
||||
viewport_start_time: f32,
|
||||
pixels_per_second: f32,
|
||||
// Audio file properties
|
||||
audio_duration: f32,
|
||||
sample_rate: f32,
|
||||
// Clip placement
|
||||
clip_start_time: f32,
|
||||
trim_start: f32,
|
||||
// Texture layout
|
||||
tex_width: f32,
|
||||
total_frames: f32, // total frame count in this texture segment
|
||||
segment_start_frame: f32, // first frame this texture covers (for multi-texture)
|
||||
display_mode: f32, // 0 = combined, 1 = split stereo
|
||||
// Appearance
|
||||
tint_color: vec4<f32>,
|
||||
// Screen dimensions for coordinate conversion
|
||||
screen_size: vec2<f32>,
|
||||
_pad: vec2<f32>,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var peak_tex: texture_2d<f32>;
|
||||
@group(0) @binding(1) var peak_sampler: sampler;
|
||||
@group(0) @binding(2) var<uniform> params: Params;
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) uv: vec2<f32>,
|
||||
}
|
||||
|
||||
// Fullscreen triangle (3 vertices, no vertex buffer)
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) vi: u32) -> VertexOutput {
|
||||
var out: VertexOutput;
|
||||
let x = f32(i32(vi) / 2) * 4.0 - 1.0;
|
||||
let y = f32(i32(vi) % 2) * 4.0 - 1.0;
|
||||
out.position = vec4(x, y, 0.0, 1.0);
|
||||
out.uv = vec2((x + 1.0) * 0.5, (1.0 - y) * 0.5);
|
||||
return out;
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
let frag_x = in.position.x;
|
||||
let frag_y = in.position.y;
|
||||
|
||||
// Clip to the clip rectangle
|
||||
if frag_x < params.clip_rect.x || frag_x > params.clip_rect.z ||
|
||||
frag_y < params.clip_rect.y || frag_y > params.clip_rect.w {
|
||||
discard;
|
||||
}
|
||||
|
||||
// Fragment X position → audio time
|
||||
let timeline_time = params.viewport_start_time + (frag_x - params.clip_rect.x) / params.pixels_per_second;
|
||||
let audio_time = timeline_time - params.clip_start_time + params.trim_start;
|
||||
|
||||
// Audio time → frame index
|
||||
let frame_f = audio_time * params.sample_rate - params.segment_start_frame;
|
||||
if frame_f < 0.0 || frame_f >= params.total_frames {
|
||||
discard;
|
||||
}
|
||||
|
||||
// Determine mip level based on how many audio frames map to one pixel
|
||||
let frames_per_pixel = params.sample_rate / params.pixels_per_second;
|
||||
// Each mip level reduces by 4x in sample count (2x in each texture dimension)
|
||||
let mip_f = max(0.0, log2(frames_per_pixel) / 2.0);
|
||||
let max_mip = f32(textureNumLevels(peak_tex) - 1u);
|
||||
let mip = min(mip_f, max_mip);
|
||||
|
||||
// Frame index at the chosen mip level
|
||||
let mip_floor = u32(mip);
|
||||
let reduction = pow(4.0, f32(mip_floor));
|
||||
let mip_frame = frame_f / reduction;
|
||||
|
||||
// Convert 1D mip-space index to 2D UV coordinates
|
||||
let mip_tex_width = params.tex_width / pow(2.0, f32(mip_floor));
|
||||
let mip_tex_height = ceil(params.total_frames / reduction / mip_tex_width);
|
||||
let texel_x = mip_frame % mip_tex_width;
|
||||
let texel_y = floor(mip_frame / mip_tex_width);
|
||||
let uv = vec2((texel_x + 0.5) / mip_tex_width, (texel_y + 0.5) / mip_tex_height);
|
||||
|
||||
// Sample the peak texture at computed mip level
|
||||
// R = left_min, G = left_max, B = right_min, A = right_max
|
||||
let peak = textureSampleLevel(peak_tex, peak_sampler, uv, mip);
|
||||
|
||||
let clip_height = params.clip_rect.w - params.clip_rect.y;
|
||||
let clip_top = params.clip_rect.y;
|
||||
|
||||
if params.display_mode < 0.5 {
|
||||
// Combined mode: merge both channels
|
||||
let wave_min = min(peak.r, peak.b);
|
||||
let wave_max = max(peak.g, peak.a);
|
||||
|
||||
let center_y = clip_top + clip_height * 0.5;
|
||||
let scale = clip_height * 0.45;
|
||||
|
||||
let y_top = center_y - wave_max * scale;
|
||||
let y_bot = center_y - wave_min * scale;
|
||||
|
||||
// At least 1px tall for visibility
|
||||
let y_top_adj = min(y_top, center_y - 0.5);
|
||||
let y_bot_adj = max(y_bot, center_y + 0.5);
|
||||
|
||||
if frag_y >= y_top_adj && frag_y <= y_bot_adj {
|
||||
return params.tint_color;
|
||||
}
|
||||
} else {
|
||||
// Split stereo mode: left channel in top half, right channel in bottom half
|
||||
let half_height = clip_height * 0.5;
|
||||
let mid_y = clip_top + half_height;
|
||||
|
||||
// Determine which channel this fragment belongs to
|
||||
if frag_y < mid_y {
|
||||
// Top half: left channel
|
||||
let center_y = clip_top + half_height * 0.5;
|
||||
let scale = half_height * 0.45;
|
||||
|
||||
let y_top = center_y - peak.g * scale; // left_max
|
||||
let y_bot = center_y - peak.r * scale; // left_min
|
||||
|
||||
let y_top_adj = min(y_top, center_y - 0.5);
|
||||
let y_bot_adj = max(y_bot, center_y + 0.5);
|
||||
|
||||
if frag_y >= y_top_adj && frag_y <= y_bot_adj {
|
||||
return params.tint_color;
|
||||
}
|
||||
} else {
|
||||
// Bottom half: right channel
|
||||
let center_y = mid_y + half_height * 0.5;
|
||||
let scale = half_height * 0.45;
|
||||
|
||||
let y_top = center_y - peak.a * scale; // right_max
|
||||
let y_bot = center_y - peak.b * scale; // right_min
|
||||
|
||||
let y_top_adj = min(y_top, center_y - 0.5);
|
||||
let y_bot_adj = max(y_bot, center_y + 0.5);
|
||||
|
||||
if frag_y >= y_top_adj && frag_y <= y_bot_adj {
|
||||
return params.tint_color;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
discard;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// Min/max mipmap generation for 1D audio data packed into 2D textures.
|
||||
// Each dest texel reduces 4 CONSECUTIVE source texels in audio order,
|
||||
// using 1D→2D coordinate conversion since the 2D layout is linearized 1D.
|
||||
// Row wrapping is handled by the modulo/division mapping:
|
||||
// x = index % width, y = index / width
|
||||
// So sample index 2048 with width=2048 maps to (0, 1), not (0, 0).
|
||||
//
|
||||
// Texture format: Rgba16Float
|
||||
// R = left_min, G = left_max, B = right_min, A = right_max
|
||||
// At mip 0 (raw samples): R=G=left_sample, B=A=right_sample
|
||||
|
||||
struct MipParams {
|
||||
src_width: u32,
|
||||
dst_width: u32,
|
||||
src_sample_count: u32, // valid texels in source level
|
||||
_pad: u32,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var src_mip: texture_2d<f32>;
|
||||
@group(0) @binding(1) var dst_mip: texture_storage_2d<rgba16float, write>;
|
||||
@group(0) @binding(2) var<uniform> params: MipParams;
|
||||
|
||||
@compute @workgroup_size(64)
|
||||
fn main(@builtin(global_invocation_id) id: vec3<u32>) {
|
||||
// Each thread handles one dest texel
|
||||
let dst_1d = id.x;
|
||||
let dst_size = textureDimensions(dst_mip);
|
||||
if dst_1d >= dst_size.x * dst_size.y {
|
||||
return;
|
||||
}
|
||||
|
||||
let dst_x = dst_1d % params.dst_width;
|
||||
let dst_y = dst_1d / params.dst_width;
|
||||
|
||||
// Map to 4 consecutive source texels in 1D audio order
|
||||
let src_base = dst_1d * 4u;
|
||||
var result = vec4(0.0);
|
||||
var initialized = false;
|
||||
|
||||
for (var i = 0u; i < 4u; i++) {
|
||||
let src_1d = src_base + i;
|
||||
if src_1d >= params.src_sample_count {
|
||||
break;
|
||||
}
|
||||
// 1D → 2D: wraps across rows naturally
|
||||
let src_x = src_1d % params.src_width;
|
||||
let src_y = src_1d / params.src_width;
|
||||
let s = textureLoad(src_mip, vec2(src_x, src_y), 0);
|
||||
|
||||
if !initialized {
|
||||
result = s;
|
||||
initialized = true;
|
||||
} else {
|
||||
result = vec4(
|
||||
min(result.r, s.r), // left_min
|
||||
max(result.g, s.g), // left_max
|
||||
min(result.b, s.b), // right_min
|
||||
max(result.a, s.a), // right_max
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
textureStore(dst_mip, vec2(dst_x, dst_y), result);
|
||||
}
|
||||
@@ -607,311 +607,6 @@ impl TimelinePane {
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculate which waveform tiles are visible in the viewport
|
||||
fn calculate_visible_tiles(
|
||||
audio_pool_index: usize,
|
||||
clip_start_time: f64,
|
||||
clip_duration: f64,
|
||||
clip_rect: egui::Rect,
|
||||
timeline_left_edge: f32,
|
||||
viewport_start_time: f64,
|
||||
pixels_per_second: f64,
|
||||
zoom_bucket: u32,
|
||||
height: u32,
|
||||
trim_start: f64,
|
||||
audio_file_duration: f64,
|
||||
) -> Vec<crate::waveform_image_cache::WaveformCacheKey> {
|
||||
use crate::waveform_image_cache::{WaveformCacheKey, TILE_WIDTH_PIXELS};
|
||||
|
||||
// Calculate clip position in screen space (including timeline offset)
|
||||
let clip_start_x = timeline_left_edge + ((clip_start_time - viewport_start_time) * pixels_per_second) as f32;
|
||||
let clip_width = (clip_duration * pixels_per_second) as f32;
|
||||
|
||||
// Check if clip is visible
|
||||
if clip_start_x + clip_width < clip_rect.min.x || clip_start_x > clip_rect.max.x {
|
||||
return vec![]; // Clip not visible
|
||||
}
|
||||
|
||||
// Calculate tile duration in seconds (based on zoom bucket, not current pixels_per_second)
|
||||
let seconds_per_pixel_in_tile = 1.0 / zoom_bucket as f64;
|
||||
let tile_duration_seconds = TILE_WIDTH_PIXELS as f64 * seconds_per_pixel_in_tile;
|
||||
|
||||
// Calculate visible time range within the clip
|
||||
let visible_start_pixel = (clip_rect.min.x - clip_start_x).max(0.0);
|
||||
let visible_end_pixel = (clip_rect.max.x - clip_start_x).min(clip_width);
|
||||
|
||||
// Convert screen pixels to time within clip
|
||||
let visible_start_time_in_clip = (visible_start_pixel as f64) / pixels_per_second;
|
||||
let visible_end_time_in_clip = (visible_end_pixel as f64) / pixels_per_second;
|
||||
|
||||
// Convert to audio file coordinates (tiles are indexed by audio file position)
|
||||
let visible_audio_start = trim_start + visible_start_time_in_clip;
|
||||
let visible_audio_end = (trim_start + visible_end_time_in_clip).min(audio_file_duration);
|
||||
|
||||
// Calculate which tiles from the audio file cover this range
|
||||
let start_tile = (visible_audio_start / tile_duration_seconds).floor() as u32;
|
||||
let end_tile = ((visible_audio_end / tile_duration_seconds).ceil() as u32).max(start_tile + 1);
|
||||
|
||||
// Generate cache keys for visible tiles
|
||||
let mut keys = Vec::new();
|
||||
for tile_idx in start_tile..end_tile {
|
||||
keys.push(WaveformCacheKey {
|
||||
audio_pool_index,
|
||||
zoom_bucket,
|
||||
tile_index: tile_idx,
|
||||
height,
|
||||
});
|
||||
}
|
||||
|
||||
keys
|
||||
}
|
||||
|
||||
/// Calculate tiles for pre-caching (1-2 screens ahead/behind)
|
||||
fn calculate_precache_tiles(
|
||||
visible_tiles: &[crate::waveform_image_cache::WaveformCacheKey],
|
||||
viewport_width_pixels: f32,
|
||||
) -> Vec<crate::waveform_image_cache::WaveformCacheKey> {
|
||||
use crate::waveform_image_cache::{WaveformCacheKey, TILE_WIDTH_PIXELS};
|
||||
|
||||
if visible_tiles.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
|
||||
// Calculate how many tiles = 1-2 screens
|
||||
let tiles_per_screen = ((viewport_width_pixels as usize + TILE_WIDTH_PIXELS - 1)
|
||||
/ TILE_WIDTH_PIXELS) as u32;
|
||||
let precache_count = tiles_per_screen * 2; // 2 screens worth
|
||||
|
||||
let first_visible = visible_tiles.first().unwrap();
|
||||
let last_visible = visible_tiles.last().unwrap();
|
||||
|
||||
let mut precache = Vec::new();
|
||||
|
||||
// Tiles before viewport
|
||||
for i in 1..=precache_count {
|
||||
if let Some(tile_idx) = first_visible.tile_index.checked_sub(i) {
|
||||
precache.push(WaveformCacheKey {
|
||||
audio_pool_index: first_visible.audio_pool_index,
|
||||
zoom_bucket: first_visible.zoom_bucket,
|
||||
tile_index: tile_idx,
|
||||
height: first_visible.height,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Tiles after viewport (with bounds check based on clip duration)
|
||||
for i in 1..=precache_count {
|
||||
let tile_idx = last_visible.tile_index + i;
|
||||
precache.push(WaveformCacheKey {
|
||||
audio_pool_index: first_visible.audio_pool_index,
|
||||
zoom_bucket: first_visible.zoom_bucket,
|
||||
tile_index: tile_idx,
|
||||
height: first_visible.height,
|
||||
});
|
||||
}
|
||||
|
||||
precache
|
||||
}
|
||||
|
||||
/// Select appropriate detail level based on zoom (pixels per second)
|
||||
///
|
||||
/// Detail levels:
|
||||
/// - Level 0 (Overview): 1 peak/sec - for extreme zoom out (0-2 pps)
|
||||
/// - Level 1 (Low): 10 peaks/sec - for zoomed out view (2-20 pps)
|
||||
/// - Level 2 (Medium): 100 peaks/sec - for normal view (20-200 pps)
|
||||
/// - Level 3 (High): 1000 peaks/sec - for zoomed in (200-2000 pps)
|
||||
/// - Level 4 (Max): Full resolution - for maximum zoom (>2000 pps)
|
||||
fn select_detail_level(pixels_per_second: f64) -> u8 {
|
||||
if pixels_per_second < 2.0 {
|
||||
0 // Overview
|
||||
} else if pixels_per_second < 20.0 {
|
||||
1 // Low
|
||||
} else if pixels_per_second < 200.0 {
|
||||
2 // Medium
|
||||
} else if pixels_per_second < 2000.0 {
|
||||
3 // High
|
||||
} else {
|
||||
4 // Max (full resolution)
|
||||
}
|
||||
}
|
||||
|
||||
/// Assemble waveform peaks from chunks for the ENTIRE audio file
|
||||
///
|
||||
/// Returns peaks for the entire audio file, or None if chunks are not available
|
||||
/// This assembles a complete waveform from chunks at the appropriate detail level
|
||||
fn assemble_peaks_from_chunks(
|
||||
waveform_chunk_cache: &std::collections::HashMap<(usize, u8, u32), Vec<daw_backend::WaveformPeak>>,
|
||||
audio_pool_index: usize,
|
||||
detail_level: u8,
|
||||
audio_file_duration: f64,
|
||||
audio_controller: Option<&std::sync::Arc<std::sync::Mutex<daw_backend::EngineController>>>,
|
||||
) -> Option<Vec<daw_backend::WaveformPeak>> {
|
||||
// Calculate chunk time span based on detail level
|
||||
let chunk_time_span = match detail_level {
|
||||
0 => 60.0, // Level 0: 60 seconds per chunk
|
||||
1 => 30.0, // Level 1: 30 seconds per chunk
|
||||
2 => 10.0, // Level 2: 10 seconds per chunk
|
||||
3 => 5.0, // Level 3: 5 seconds per chunk
|
||||
4 => 1.0, // Level 4: 1 second per chunk
|
||||
_ => 10.0, // Default
|
||||
};
|
||||
|
||||
// Calculate total number of chunks needed for entire audio file
|
||||
let total_chunks = (audio_file_duration / chunk_time_span).ceil() as u32;
|
||||
|
||||
let mut assembled_peaks = Vec::new();
|
||||
let mut missing_chunks = Vec::new();
|
||||
|
||||
// Check if all required chunks are available
|
||||
for chunk_idx in 0..total_chunks {
|
||||
let key = (audio_pool_index, detail_level, chunk_idx);
|
||||
if let Some(chunk_peaks) = waveform_chunk_cache.get(&key) {
|
||||
assembled_peaks.extend_from_slice(chunk_peaks);
|
||||
} else {
|
||||
// Track missing chunk
|
||||
missing_chunks.push(chunk_idx);
|
||||
}
|
||||
}
|
||||
|
||||
// If any chunks are missing, request them and return None
|
||||
if !missing_chunks.is_empty() {
|
||||
if let Some(controller_arc) = audio_controller {
|
||||
let mut controller = controller_arc.lock().unwrap();
|
||||
let _ = controller.generate_waveform_chunks(
|
||||
audio_pool_index,
|
||||
detail_level,
|
||||
missing_chunks,
|
||||
1, // Medium priority
|
||||
);
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(assembled_peaks)
|
||||
}
|
||||
|
||||
/// Render waveform visualization using cached texture tiles
|
||||
/// This is much faster than line-based rendering for many clips
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn render_audio_waveform(
|
||||
painter: &egui::Painter,
|
||||
clip_rect: egui::Rect,
|
||||
timeline_left_edge: f32,
|
||||
audio_pool_index: usize,
|
||||
clip_start_time: f64,
|
||||
clip_duration: f64,
|
||||
trim_start: f64,
|
||||
audio_file_duration: f64,
|
||||
viewport_start_time: f64,
|
||||
pixels_per_second: f64,
|
||||
waveform_image_cache: &mut crate::waveform_image_cache::WaveformImageCache,
|
||||
waveform_peaks: &[daw_backend::WaveformPeak],
|
||||
ctx: &egui::Context,
|
||||
tint_color: egui::Color32,
|
||||
) {
|
||||
use crate::waveform_image_cache::{calculate_zoom_bucket, TILE_WIDTH_PIXELS};
|
||||
|
||||
if waveform_peaks.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Calculate zoom bucket
|
||||
let zoom_bucket = calculate_zoom_bucket(pixels_per_second);
|
||||
|
||||
// Calculate visible tiles
|
||||
let visible_tiles = Self::calculate_visible_tiles(
|
||||
audio_pool_index,
|
||||
clip_start_time,
|
||||
clip_duration,
|
||||
clip_rect,
|
||||
timeline_left_edge,
|
||||
viewport_start_time,
|
||||
pixels_per_second,
|
||||
zoom_bucket,
|
||||
clip_rect.height() as u32,
|
||||
trim_start,
|
||||
audio_file_duration,
|
||||
);
|
||||
|
||||
// Render each tile
|
||||
for key in &visible_tiles {
|
||||
let texture = waveform_image_cache.get_or_create(
|
||||
*key,
|
||||
ctx,
|
||||
waveform_peaks,
|
||||
audio_file_duration,
|
||||
);
|
||||
|
||||
// Calculate tile position in audio file (tiles now represent fixed portions of the audio file)
|
||||
// Each pixel in the tile texture represents (1.0 / zoom_bucket) seconds
|
||||
let seconds_per_pixel_in_tile = 1.0 / key.zoom_bucket as f64;
|
||||
let tile_audio_start = key.tile_index as f64 * TILE_WIDTH_PIXELS as f64 * seconds_per_pixel_in_tile;
|
||||
let tile_audio_end = tile_audio_start + TILE_WIDTH_PIXELS as f64 * seconds_per_pixel_in_tile;
|
||||
|
||||
// Calculate which portion of this tile is visible in the trimmed clip
|
||||
let visible_audio_start = tile_audio_start.max(trim_start);
|
||||
let visible_audio_end = tile_audio_end.min(trim_start + clip_duration).min(audio_file_duration);
|
||||
|
||||
if visible_audio_start >= visible_audio_end {
|
||||
continue; // No visible portion
|
||||
}
|
||||
|
||||
// Calculate UV coordinates (only show the portion within trim bounds)
|
||||
let uv_min_x = ((visible_audio_start - tile_audio_start) / (tile_audio_end - tile_audio_start)).max(0.0) as f32;
|
||||
let uv_max_x = ((visible_audio_end - tile_audio_start) / (tile_audio_end - tile_audio_start)).min(1.0) as f32;
|
||||
|
||||
// Map audio file position to timeline position
|
||||
// Audio time trim_start corresponds to timeline position clip_start_time
|
||||
let tile_timeline_start = clip_start_time + (visible_audio_start - trim_start);
|
||||
let tile_timeline_end = clip_start_time + (visible_audio_end - trim_start);
|
||||
|
||||
// Convert to screen space
|
||||
let tile_screen_x = timeline_left_edge + ((tile_timeline_start - viewport_start_time) * pixels_per_second) as f32;
|
||||
let tile_screen_width = ((tile_timeline_end - tile_timeline_start) * pixels_per_second) as f32;
|
||||
|
||||
// Create unclipped tile rect
|
||||
let unclipped_tile_rect = egui::Rect::from_min_size(
|
||||
egui::pos2(tile_screen_x, clip_rect.min.y),
|
||||
egui::vec2(tile_screen_width, clip_rect.height()),
|
||||
);
|
||||
|
||||
// Clip to the visible clip rectangle
|
||||
let tile_rect = unclipped_tile_rect.intersect(clip_rect);
|
||||
|
||||
if tile_rect.width() <= 0.0 || tile_rect.height() <= 0.0 {
|
||||
continue; // Nothing visible
|
||||
}
|
||||
|
||||
// Adjust UV coordinates based on how much the tile was clipped
|
||||
let uv_span = uv_max_x - uv_min_x;
|
||||
let adjusted_uv_min_x = if unclipped_tile_rect.width() > 0.0 {
|
||||
uv_min_x + ((tile_rect.min.x - unclipped_tile_rect.min.x) / unclipped_tile_rect.width()) * uv_span
|
||||
} else {
|
||||
uv_min_x
|
||||
};
|
||||
let adjusted_uv_max_x = if unclipped_tile_rect.width() > 0.0 {
|
||||
uv_min_x + ((tile_rect.max.x - unclipped_tile_rect.min.x) / unclipped_tile_rect.width()) * uv_span
|
||||
} else {
|
||||
uv_max_x
|
||||
};
|
||||
|
||||
// Blit texture with adjusted UV coordinates
|
||||
painter.image(
|
||||
texture.id(),
|
||||
tile_rect,
|
||||
egui::Rect::from_min_max(egui::pos2(adjusted_uv_min_x, 0.0), egui::pos2(adjusted_uv_max_x, 1.0)),
|
||||
tint_color,
|
||||
);
|
||||
}
|
||||
|
||||
// Pre-cache adjacent tiles (non-blocking)
|
||||
let precache_tiles = Self::calculate_precache_tiles(&visible_tiles, clip_rect.width());
|
||||
// Create temporary HashMap with just this clip's waveform for pre-caching
|
||||
let mut temp_waveform_cache = std::collections::HashMap::new();
|
||||
temp_waveform_cache.insert(audio_pool_index, waveform_peaks.to_vec());
|
||||
waveform_image_cache.precache_tiles(&precache_tiles, ctx, &temp_waveform_cache, audio_file_duration);
|
||||
}
|
||||
|
||||
/// Render layer header column (left side with track names and controls)
|
||||
fn render_layer_headers(
|
||||
&mut self,
|
||||
@@ -1198,10 +893,9 @@ impl TimelinePane {
|
||||
active_layer_id: &Option<uuid::Uuid>,
|
||||
selection: &lightningbeam_core::selection::Selection,
|
||||
midi_event_cache: &std::collections::HashMap<u32, Vec<(f64, u8, bool)>>,
|
||||
waveform_cache: &std::collections::HashMap<usize, Vec<daw_backend::WaveformPeak>>,
|
||||
waveform_chunk_cache: &std::collections::HashMap<(usize, u8, u32), Vec<daw_backend::WaveformPeak>>,
|
||||
waveform_image_cache: &mut crate::waveform_image_cache::WaveformImageCache,
|
||||
audio_controller: Option<&std::sync::Arc<std::sync::Mutex<daw_backend::EngineController>>>,
|
||||
raw_audio_cache: &std::collections::HashMap<usize, (Vec<f32>, u32, u32)>,
|
||||
waveform_gpu_dirty: &mut std::collections::HashSet<usize>,
|
||||
target_format: wgpu::TextureFormat,
|
||||
) -> Vec<(egui::Rect, uuid::Uuid, f64, f64)> {
|
||||
let painter = ui.painter();
|
||||
|
||||
@@ -1492,59 +1186,68 @@ impl TimelinePane {
|
||||
);
|
||||
}
|
||||
}
|
||||
// Sampled Audio: Draw waveform
|
||||
// Sampled Audio: Draw waveform via GPU
|
||||
lightningbeam_core::clip::AudioClipType::Sampled { audio_pool_index } => {
|
||||
// Get audio file duration from backend
|
||||
let audio_file_duration = if let Some(ref controller_arc) = audio_controller {
|
||||
let mut controller = controller_arc.lock().unwrap();
|
||||
controller.get_pool_file_info(*audio_pool_index)
|
||||
.ok()
|
||||
.map(|(duration, _, _)| duration)
|
||||
.unwrap_or(clip.duration) // Fallback to clip duration
|
||||
} else {
|
||||
clip.duration // Fallback if no controller
|
||||
};
|
||||
if let Some((samples, sr, ch)) = raw_audio_cache.get(audio_pool_index) {
|
||||
let total_frames = samples.len() / (*ch).max(1) as usize;
|
||||
let audio_file_duration = total_frames as f64 / *sr as f64;
|
||||
let screen_size = ui.ctx().screen_rect().size();
|
||||
|
||||
// Select detail level based on zoom
|
||||
let requested_level = Self::select_detail_level(self.pixels_per_second as f64);
|
||||
let pending_upload = if waveform_gpu_dirty.contains(audio_pool_index) {
|
||||
waveform_gpu_dirty.remove(audio_pool_index);
|
||||
Some(crate::waveform_gpu::PendingUpload {
|
||||
samples: samples.clone(),
|
||||
sample_rate: *sr,
|
||||
channels: *ch,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Try to assemble peaks from chunks with progressive fallback to lower detail levels
|
||||
let mut peaks_to_render = None;
|
||||
for level in (0..=requested_level).rev() {
|
||||
if let Some(peaks) = Self::assemble_peaks_from_chunks(
|
||||
waveform_chunk_cache,
|
||||
*audio_pool_index,
|
||||
level,
|
||||
audio_file_duration,
|
||||
audio_controller,
|
||||
) {
|
||||
peaks_to_render = Some(peaks);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let tint = [
|
||||
bright_color.r() as f32 / 255.0,
|
||||
bright_color.g() as f32 / 255.0,
|
||||
bright_color.b() as f32 / 255.0,
|
||||
bright_color.a() as f32 / 255.0,
|
||||
];
|
||||
|
||||
// Final fallback to old waveform_cache if no chunks available at any level
|
||||
let peaks_to_render = peaks_to_render
|
||||
.or_else(|| waveform_cache.get(audio_pool_index).cloned())
|
||||
.unwrap_or_default();
|
||||
|
||||
if !peaks_to_render.is_empty() {
|
||||
Self::render_audio_waveform(
|
||||
painter,
|
||||
clip_rect,
|
||||
rect.min.x,
|
||||
*audio_pool_index,
|
||||
instance_start,
|
||||
preview_clip_duration,
|
||||
preview_trim_start,
|
||||
audio_file_duration,
|
||||
self.viewport_start_time,
|
||||
self.pixels_per_second as f64,
|
||||
waveform_image_cache,
|
||||
&peaks_to_render,
|
||||
ui.ctx(),
|
||||
bright_color, // Use bright color for waveform (lighter than background)
|
||||
let clip_screen_start = rect.min.x + ((instance_start - self.viewport_start_time) * self.pixels_per_second as f64) as f32;
|
||||
let clip_screen_end = clip_screen_start + (preview_clip_duration * self.pixels_per_second as f64) as f32;
|
||||
let waveform_rect = egui::Rect::from_min_max(
|
||||
egui::pos2(clip_screen_start.max(clip_rect.min.x), clip_rect.min.y),
|
||||
egui::pos2(clip_screen_end.min(clip_rect.max.x), clip_rect.max.y),
|
||||
);
|
||||
|
||||
if waveform_rect.width() > 0.0 && waveform_rect.height() > 0.0 {
|
||||
let callback = crate::waveform_gpu::WaveformCallback {
|
||||
pool_index: *audio_pool_index,
|
||||
segment_index: 0,
|
||||
params: crate::waveform_gpu::WaveformParams {
|
||||
clip_rect: [waveform_rect.min.x, waveform_rect.min.y, waveform_rect.max.x, waveform_rect.max.y],
|
||||
viewport_start_time: self.viewport_start_time as f32,
|
||||
pixels_per_second: self.pixels_per_second as f32,
|
||||
audio_duration: audio_file_duration as f32,
|
||||
sample_rate: *sr as f32,
|
||||
clip_start_time: instance_start as f32,
|
||||
trim_start: preview_trim_start as f32,
|
||||
tex_width: crate::waveform_gpu::tex_width() as f32,
|
||||
total_frames: total_frames as f32,
|
||||
segment_start_frame: 0.0,
|
||||
display_mode: 0.0,
|
||||
_pad1: [0.0, 0.0],
|
||||
tint_color: tint,
|
||||
screen_size: [screen_size.x, screen_size.y],
|
||||
_pad: [0.0, 0.0],
|
||||
},
|
||||
target_format,
|
||||
pending_upload,
|
||||
};
|
||||
|
||||
ui.painter().add(egui_wgpu::Callback::new_paint_callback(
|
||||
waveform_rect,
|
||||
callback,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Recording in progress: no visualization yet
|
||||
@@ -2375,7 +2078,7 @@ impl PaneRenderer for TimelinePane {
|
||||
|
||||
// Render layer rows with clipping
|
||||
ui.set_clip_rect(content_rect.intersect(original_clip_rect));
|
||||
let video_clip_hovers = self.render_layers(ui, content_rect, shared.theme, document, shared.active_layer_id, shared.selection, shared.midi_event_cache, shared.waveform_cache, shared.waveform_chunk_cache, shared.waveform_image_cache, shared.audio_controller);
|
||||
let video_clip_hovers = self.render_layers(ui, content_rect, shared.theme, document, shared.active_layer_id, shared.selection, shared.midi_event_cache, shared.raw_audio_cache, shared.waveform_gpu_dirty, shared.target_format);
|
||||
|
||||
// Render playhead on top (clip to timeline area)
|
||||
ui.set_clip_rect(timeline_rect.intersect(original_clip_rect));
|
||||
|
||||
Reference in New Issue
Block a user