Use CQT transform for spectrograph instead of FFT

This commit is contained in:
Skyler Lehmkuhl
2026-02-14 21:18:30 -05:00
parent 777d3ef6be
commit 068715c0fa
13 changed files with 1076 additions and 782 deletions
@@ -92,10 +92,6 @@ pub struct PianoRollPane {
// Resolved note cache — tracks when to invalidate
cached_clip_id: Option<u32>,
// Spectrogram cache — keyed by audio pool index
// Stores pre-computed SpectrogramUpload data ready for GPU
spectrogram_computed: HashMap<usize, crate::spectrogram_gpu::SpectrogramUpload>,
// Spectrogram gamma (power curve for colormap)
spectrogram_gamma: f32,
}
@@ -126,8 +122,7 @@ impl PianoRollPane {
auto_scroll_enabled: true,
user_scrolled_since_play: false,
cached_clip_id: None,
spectrogram_computed: HashMap::new(),
spectrogram_gamma: 5.0,
spectrogram_gamma: 0.8,
}
}
@@ -1256,80 +1251,51 @@ impl PianoRollPane {
}
}
let screen_size = ui.ctx().input(|i| i.content_rect().size());
// Render spectrogram for each sampled clip on this layer
// Render CQT spectrogram for each sampled clip on this layer
for &(pool_index, timeline_start, trim_start, _duration, sample_rate) in &clip_infos {
// Compute spectrogram if not cached
let needs_compute = !self.spectrogram_computed.contains_key(&pool_index);
let pending_upload = if needs_compute {
if let Some((samples, sr, ch)) = shared.raw_audio_cache.get(&pool_index) {
let spec_data = crate::spectrogram_compute::compute_spectrogram(
samples, *sr, *ch, 2048, 512,
);
if spec_data.time_bins > 0 {
let upload = crate::spectrogram_gpu::SpectrogramUpload {
magnitudes: spec_data.magnitudes,
time_bins: spec_data.time_bins as u32,
freq_bins: spec_data.freq_bins as u32,
sample_rate: spec_data.sample_rate,
hop_size: spec_data.hop_size as u32,
fft_size: spec_data.fft_size as u32,
duration: spec_data.duration as f32,
};
// Store a marker so we don't recompute
self.spectrogram_computed.insert(pool_index, crate::spectrogram_gpu::SpectrogramUpload {
magnitudes: Vec::new(), // We don't need to keep the data around
time_bins: upload.time_bins,
freq_bins: upload.freq_bins,
sample_rate: upload.sample_rate,
hop_size: upload.hop_size,
fft_size: upload.fft_size,
duration: upload.duration,
});
Some(upload)
} else {
None
}
} else {
None
}
// Get audio duration from the raw audio cache
let audio_duration = if let Some((samples, sr, ch)) = shared.raw_audio_cache.get(&pool_index) {
samples.len() as f64 / (*sr as f64 * *ch as f64)
} else {
None
};
// Get cached spectrogram metadata for params
let spec_meta = self.spectrogram_computed.get(&pool_index);
let (time_bins, freq_bins, hop_size, fft_size, audio_duration) = match spec_meta {
Some(m) => (m.time_bins as f32, m.freq_bins as f32, m.hop_size as f32, m.fft_size as f32, m.duration),
None => continue,
continue;
};
if view_rect.width() > 0.0 && view_rect.height() > 0.0 {
let callback = crate::spectrogram_gpu::SpectrogramCallback {
// Calculate visible CQT column range for streaming
let viewport_end_time = self.viewport_start_time + (view_rect.width() / self.pixels_per_second) as f64;
let vis_audio_start = (self.viewport_start_time - timeline_start + trim_start).max(0.0);
let vis_audio_end = (viewport_end_time - timeline_start + trim_start).min(audio_duration);
let vis_col_start = (vis_audio_start * sample_rate as f64 / 512.0).floor() as i64;
let vis_col_end = (vis_audio_end * sample_rate as f64 / 512.0).ceil() as i64 + 1;
let callback = crate::cqt_gpu::CqtCallback {
pool_index,
params: crate::spectrogram_gpu::SpectrogramParams {
params: crate::cqt_gpu::CqtRenderParams {
clip_rect: [view_rect.min.x, view_rect.min.y, view_rect.max.x, view_rect.max.y],
viewport_start_time: self.viewport_start_time as f32,
pixels_per_second: self.pixels_per_second,
audio_duration,
audio_duration: audio_duration as f32,
sample_rate: sample_rate as f32,
clip_start_time: timeline_start as f32,
trim_start: trim_start as f32,
time_bins,
freq_bins,
hop_size,
fft_size,
freq_bins: 174.0,
bins_per_octave: 24.0,
hop_size: 512.0,
scroll_y: self.scroll_y,
note_height: self.note_height,
screen_size: [screen_size.x, screen_size.y],
min_note: MIN_NOTE as f32,
max_note: MAX_NOTE as f32,
gamma: self.spectrogram_gamma,
_pad: [0.0; 3],
cache_capacity: 0.0, // filled by prepare()
cache_start_column: 0.0,
cache_valid_start: 0.0,
cache_valid_end: 0.0,
_pad: [0.0; 2],
},
target_format: shared.target_format,
pending_upload,
sample_rate,
visible_col_start: vis_col_start,
visible_col_end: vis_col_end,
};
ui.painter().add(egui_wgpu::Callback::new_paint_callback(
@@ -0,0 +1,101 @@
// GPU Constant-Q Transform (CQT) compute shader.
//
// Reads raw audio samples from a waveform mip-0 texture (Rgba16Float, packed
// row-major at TEX_WIDTH=2048) and computes CQT magnitude for each
// (freq_bin, time_column) pair, writing normalized dB values into a ring-buffer
// cache texture (R32Float, width=cache_capacity, height=freq_bins).
//
// Dispatch: (ceil(freq_bins / 64), num_columns, 1)
// Each thread handles one frequency bin for one time column.
struct CqtParams {
hop_size: u32,
freq_bins: u32,
cache_capacity: u32,
cache_write_offset: u32, // ring buffer position to start writing
num_columns: u32, // how many columns in this dispatch
column_start: u32, // global CQT column index of first column
tex_width: u32, // waveform texture width (2048)
total_frames: u32, // total audio frames in waveform texture
sample_rate: f32,
_pad0: u32,
_pad1: u32,
_pad2: u32,
}
struct BinInfo {
window_length: u32,
phase_step: f32, // 2*pi*Q / N_k
_pad0: u32,
_pad1: u32,
}
@group(0) @binding(0) var audio_tex: texture_2d<f32>;
@group(0) @binding(1) var cqt_out: texture_storage_2d<rgba16float, write>;
@group(0) @binding(2) var<uniform> params: CqtParams;
@group(0) @binding(3) var<storage, read> bins: array<BinInfo>;
const PI2: f32 = 6.283185307;
@compute @workgroup_size(64)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let bin_k = gid.x;
let col_rel = gid.y; // relative to this dispatch batch
if bin_k >= params.freq_bins || col_rel >= params.num_columns {
return;
}
let global_col = params.column_start + col_rel;
let sample_start = global_col * params.hop_size;
let info = bins[bin_k];
let n_k = info.window_length;
// Center the analysis window: offset by half the window length so the
// column timestamp refers to the center of the window, not the start.
// This gives better time alignment, especially for low-frequency bins
// that have very long windows.
let half_win = n_k / 2u;
// Accumulate complex inner product: sum of x[n] * w[n] * exp(-i * phase_step * n)
var sum_re: f32 = 0.0;
var sum_im: f32 = 0.0;
for (var n = 0u; n < n_k; n++) {
// Center the window around the hop position
let raw_idx = i32(sample_start) + i32(n) - i32(half_win);
if raw_idx < 0 || u32(raw_idx) >= params.total_frames {
continue;
}
let sample_idx = u32(raw_idx);
// Read audio sample from 2D waveform texture (mip 0)
// At mip 0: R=G=left, B=A=right; average to mono
let tx = sample_idx % params.tex_width;
let ty = sample_idx / params.tex_width;
let texel = textureLoad(audio_tex, vec2<i32>(i32(tx), i32(ty)), 0);
let sample_val = (texel.r + texel.b) * 0.5;
// Hann window computed analytically
let window = 0.5 * (1.0 - cos(PI2 * f32(n) / f32(n_k)));
// Complex exponential: exp(-i * phase_step * n)
let angle = info.phase_step * f32(n);
let windowed = sample_val * window;
sum_re += windowed * cos(angle);
sum_im -= windowed * sin(angle);
}
// Magnitude, normalized by window length
let mag = sqrt(sum_re * sum_re + sum_im * sum_im) / f32(n_k);
// Convert to dB, map -80dB..0dB -> 0.0..1.0
// WGSL log() is natural log, so log10(x) = log(x) / log(10)
let db = 20.0 * log(mag + 1e-10) / 2.302585093;
let normalized = clamp((db + 80.0) / 80.0, 0.0, 1.0);
// Write to ring buffer cache texture
let cache_x = (params.cache_write_offset + col_rel) % params.cache_capacity;
textureStore(cqt_out, vec2<i32>(i32(cache_x), i32(bin_k)), vec4(normalized, 0.0, 0.0, 1.0));
}
@@ -1,30 +1,37 @@
// Spectrogram rendering shader for FFT magnitude data.
// Texture layout: X = frequency bin, Y = time bin
// Values: normalized magnitude (0.0 = silence, 1.0 = peak)
// Vertical axis maps MIDI notes to frequency bins (matching piano roll)
// CQT spectrogram render shader.
//
// Reads from a ring-buffer cache texture (Rgba16Float) where:
// X = time column (ring buffer index), Y = CQT frequency bin
// CQT bins map directly to MIDI notes via: bin = (note - min_note) * bins_per_octave / 12
//
// Applies the same colormap as the old FFT spectrogram.
// Must match CqtRenderParams in cqt_gpu.rs exactly (96 bytes).
struct Params {
clip_rect: vec4<f32>,
viewport_start_time: f32,
pixels_per_second: f32,
audio_duration: f32,
sample_rate: f32,
clip_start_time: f32,
trim_start: f32,
time_bins: f32,
freq_bins: f32,
hop_size: f32,
fft_size: f32,
scroll_y: f32,
note_height: f32,
screen_size: vec2<f32>,
min_note: f32,
max_note: f32,
gamma: f32,
clip_rect: vec4<f32>, // 16 @ 0
viewport_start_time: f32, // 4 @ 16
pixels_per_second: f32, // 4 @ 20
audio_duration: f32, // 4 @ 24
sample_rate: f32, // 4 @ 28
clip_start_time: f32, // 4 @ 32
trim_start: f32, // 4 @ 36
freq_bins: f32, // 4 @ 40
bins_per_octave: f32, // 4 @ 44
hop_size: f32, // 4 @ 48
scroll_y: f32, // 4 @ 52
note_height: f32, // 4 @ 56
min_note: f32, // 4 @ 60
max_note: f32, // 4 @ 64
gamma: f32, // 4 @ 68
cache_capacity: f32, // 4 @ 72
cache_start_column: f32, // 4 @ 76
cache_valid_start: f32, // 4 @ 80
cache_valid_end: f32, // 4 @ 84
_pad: vec2<f32>, // 8 @ 88, total 96
}
@group(0) @binding(0) var spec_tex: texture_2d<f32>;
@group(0) @binding(1) var spec_sampler: sampler;
@group(0) @binding(0) var cache_tex: texture_2d<f32>;
@group(0) @binding(1) var cache_sampler: sampler;
@group(0) @binding(2) var<uniform> params: Params;
struct VertexOutput {
@@ -42,7 +49,6 @@ fn vs_main(@builtin(vertex_index) vi: u32) -> VertexOutput {
return out;
}
// Signed distance from point to rounded rectangle boundary
fn rounded_rect_sdf(pos: vec2<f32>, rect_min: vec2<f32>, rect_max: vec2<f32>, r: f32) -> f32 {
let center = (rect_min + rect_max) * 0.5;
let half_size = (rect_max - rect_min) * 0.5;
@@ -55,27 +61,21 @@ fn colormap(v: f32, gamma: f32) -> vec4<f32> {
let t = pow(clamp(v, 0.0, 1.0), gamma);
if t < 1.0 / 6.0 {
// Black -> blue
let s = t * 6.0;
return vec4(0.0, 0.0, s, 1.0);
} else if t < 2.0 / 6.0 {
// Blue -> purple
let s = (t - 1.0 / 6.0) * 6.0;
return vec4(s * 0.6, 0.0, 1.0 - s * 0.2, 1.0);
} else if t < 3.0 / 6.0 {
// Purple -> red
let s = (t - 2.0 / 6.0) * 6.0;
return vec4(0.6 + s * 0.4, 0.0, 0.8 - s * 0.8, 1.0);
} else if t < 4.0 / 6.0 {
// Red -> orange
let s = (t - 3.0 / 6.0) * 6.0;
return vec4(1.0, s * 0.5, 0.0, 1.0);
} else if t < 5.0 / 6.0 {
// Orange -> yellow
let s = (t - 4.0 / 6.0) * 6.0;
return vec4(1.0, 0.5 + s * 0.5, 0.0, 1.0);
} else {
// Yellow -> white
let s = (t - 5.0 / 6.0) * 6.0;
return vec4(1.0, 1.0, s, 1.0);
}
@@ -98,11 +98,9 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
let content_top = params.clip_rect.y - params.scroll_y;
let content_bottom = params.clip_rect.y + (params.max_note - params.min_note + 1.0) * params.note_height - params.scroll_y;
// Rounded corners: content edges on X, visible viewport edges on Y.
// This rounds left/right where the clip starts/ends, and top/bottom at the view boundary.
// Rounded corners
let vis_top = max(content_top, params.clip_rect.y);
let vis_bottom = min(content_bottom, params.clip_rect.w);
let corner_radius = 6.0;
let dist = rounded_rect_sdf(
vec2(frag_x, frag_y),
@@ -114,7 +112,7 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
discard;
}
// Fragment X -> audio time -> time bin
// Fragment X -> audio time -> global CQT column
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;
@@ -122,32 +120,35 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
discard;
}
let time_bin = audio_time * params.sample_rate / params.hop_size;
if time_bin < 0.0 || time_bin >= params.time_bins {
let global_col = audio_time * params.sample_rate / params.hop_size;
// Check if this column is in the cached range
if global_col < params.cache_valid_start || global_col >= params.cache_valid_end {
discard;
}
// Fragment Y -> MIDI note -> frequency -> frequency bin
// Fragment Y -> MIDI note -> CQT bin (direct mapping!)
let note = params.max_note - ((frag_y - params.clip_rect.y + params.scroll_y) / params.note_height);
if note < params.min_note || note > params.max_note {
discard;
}
// MIDI note -> frequency: freq = 440 * 2^((note - 69) / 12)
let freq = 440.0 * pow(2.0, (note - 69.0) / 12.0);
// CQT bin: each octave has bins_per_octave bins, starting from min_note
let bin = (note - params.min_note) * params.bins_per_octave / 12.0;
// Frequency -> FFT bin index
let freq_bin = freq * params.fft_size / params.sample_rate;
if freq_bin < 0.0 || freq_bin >= params.freq_bins {
if bin < 0.0 || bin >= params.freq_bins {
discard;
}
// Sample texture with bilinear filtering
let u = freq_bin / params.freq_bins;
let v = time_bin / params.time_bins;
let magnitude = textureSampleLevel(spec_tex, spec_sampler, vec2(u, v), 0.0).r;
// Map global column to ring buffer position
let ring_pos = global_col - params.cache_start_column;
let cache_x = ring_pos % params.cache_capacity;
// Sample cache texture with bilinear filtering
let u = (cache_x + 0.5) / params.cache_capacity;
let v = (bin + 0.5) / params.freq_bins;
let magnitude = textureSampleLevel(cache_tex, cache_sampler, vec2(u, v), 0.0).r;
return colormap(magnitude, params.gamma);
}