From 711eb148df71b6c5c2191a49082e6ca9cf4e2ce2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=20Luis=20Monta=C3=B1es=20Ojados?= Date: Sat, 17 Jan 2026 20:25:58 +0100 Subject: [PATCH] feat(tui): add interactive 5-band per-user equalizer --- cmd/tui/model.go | 98 +++++++++++++++++++++++++++++- pkg/audio/biquad.go | 135 +++++++++++++++++++++++++++++++++++++++++ pkg/audio/common.go | 6 +- pkg/audio/fft.go | 138 ++++++++++++++++++++++++++++++++++++++++++ pkg/audio/playback.go | 111 +++++++++++++++++++++++++++++++++ 5 files changed, 485 insertions(+), 3 deletions(-) create mode 100644 pkg/audio/biquad.go create mode 100644 pkg/audio/fft.go diff --git a/cmd/tui/model.go b/cmd/tui/model.go index 4baa32a..41f59d0 100644 --- a/cmd/tui/model.go +++ b/cmd/tui/model.go @@ -120,6 +120,9 @@ type Model struct { showUserView bool viewUser *UserNode pokeID uint16 // Target ID for pending poke + + // Interactive EQ + eqBandIdx int // 0-4 } // addLog adds a message to the log panel @@ -820,6 +823,28 @@ func (m *Model) handleUserViewKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) { newVol = 0.0 } m.audioPlayer.SetUserVolume(u.ID, newVol) + + case "right", "l": + // Increase Gain for selected band + current := m.audioPlayer.GetUserGain(u.ID, m.eqBandIdx) + m.audioPlayer.SetUserGain(u.ID, m.eqBandIdx, current+1.0) + + case "left", "h": + // Decrease Gain + current := m.audioPlayer.GetUserGain(u.ID, m.eqBandIdx) + m.audioPlayer.SetUserGain(u.ID, m.eqBandIdx, current-1.0) + + case "up", "k": + m.eqBandIdx-- + if m.eqBandIdx < 0 { + m.eqBandIdx = 4 + } + + case "down", "j": + m.eqBandIdx++ + if m.eqBandIdx > 4 { + m.eqBandIdx = 0 + } } return m, nil } @@ -1412,14 +1437,85 @@ func (m *Model) renderUserView() string { "--- Audio Settings ---", fmt.Sprintf("%s %d%%", labelStyle.Render("Volume:"), int(vol*100)), fmt.Sprintf("%s %s", labelStyle.Render("Local Mute:"), muteStr), + } + + // EQ Visualization + var eqGraph []string + if m.audioPlayer != nil { + bands := m.audioPlayer.GetEQBands(u.ID) + if len(bands) > 0 { + eqGraph = append(eqGraph, "", "--- Interactive Equalizer ---", "") + + // Render bars for 5 bands + // 0: Bass, 1: Low-Mid, 2: Mid, 3: High-Mid, 4: High + labels := []string{"100Hz", "350Hz", "1kHz", "3kHz", "8kHz"} + + for i, val := range bands { + if i >= len(labels) { + break + } + + // Get current gain setting + gain := m.audioPlayer.GetUserGain(u.ID, i) + + // Scale 0.0-1.0 to bars (width 20) + const maxBars = 20 + bars := int(val * maxBars) + if bars > maxBars { + bars = maxBars + } + + // Bar characters: █ ▇ ▆ ▅ ▄ ▃ ▂ + barStr := "" + if bars > 0 { + barStr = strings.Repeat("█", bars) + } + + // Colorize based on intensity + barStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("39")) // Blue default + if val > 0.8 { + barStyle = barStyle.Foreground(lipgloss.Color("196")) // Red clipping + } else if val > 0.5 { + barStyle = barStyle.Foreground(lipgloss.Color("208")) // Orange high + } else if val > 0.2 { + barStyle = barStyle.Foreground(lipgloss.Color("46")) // Green normal + } + + // Selection Indicator + selector := " " + labelStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Width(6) + gainStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("245")).Width(6) + + if i == m.eqBandIdx { + selector = "->" + labelStyle = labelStyle.Foreground(lipgloss.Color("226")).Bold(true) // Yellow for selected + gainStyle = gainStyle.Foreground(lipgloss.Color("226")) + } + + gainStr := fmt.Sprintf("%+3.0fdB", gain) + + line := fmt.Sprintf("%s %s %s | %s", + selector, + labelStyle.Render(labels[i]), + gainStyle.Render(gainStr), + barStyle.Render(fmt.Sprintf("%-20s", barStr))) + + eqGraph = append(eqGraph, line) + } + } + } + + info = append(info, eqGraph...) + info = append(info, "", "--- Menu ---", "1. Poke", "2. Toggle Local Mute", "+/-: Adjust Volume", + "Arrows: Adjust EQ", "", "(Press ESC to close)", - } + ) return lipgloss.JoinVertical(lipgloss.Left, info...) } diff --git a/pkg/audio/biquad.go b/pkg/audio/biquad.go new file mode 100644 index 0000000..4144ade --- /dev/null +++ b/pkg/audio/biquad.go @@ -0,0 +1,135 @@ +package audio + +import ( + "math" +) + +// BiquadFilter represents a second-order IIR filter. +// Formulas from RBJ Audio-EQ-Cookbook. +type BiquadFilter struct { + // Coefficients + b0, b1, b2, a1, a2 float64 + + // State (history) + x1, x2, y1, y2 float64 +} + +// NewPeakingEQ creates a peaking EQ filter (boost/cut at specific frequency) +// rate: sample rate (e.g. 48000) +// freq: center frequency in Hz +// q: quality factor (width of the bell) +// dbGain: gain in decibels (e.g. +3.0, -6.0) +func NewPeakingEQ(rate, freq, q, dbGain float64) *BiquadFilter { + f := &BiquadFilter{} + f.Configure(rate, freq, q, dbGain) + return f +} + +// Configure recalculates coefficients +func (f *BiquadFilter) Configure(rate, freq, q, dbGain float64) { + // Intermediate variables + A := math.Pow(10, dbGain/40) + omega := 2 * math.Pi * freq / rate + sn := math.Sin(omega) + cs := math.Cos(omega) + alpha := sn / (2 * q) + + // Coefficients + b0 := 1 + alpha*A + b1 := -2 * cs + b2 := 1 - alpha*A + a0 := 1 + alpha/A + a1 := -2 * cs + a2 := 1 - alpha/A + + // Normalize by a0 + invA0 := 1 / a0 + f.b0 = b0 * invA0 + f.b1 = b1 * invA0 + f.b2 = b2 * invA0 + f.a1 = a1 * invA0 + f.a2 = a2 * invA0 +} + +// Process processes a single sample +func (f *BiquadFilter) Process(in float64) float64 { + // Difference equation: + // y[n] = b0*x[n] + b1*x[n-1] + b2*x[n-2] - a1*y[n-1] - a2*y[n-2] + out := f.b0*in + f.b1*f.x1 + f.b2*f.x2 - f.a1*f.y1 - f.a2*f.y2 + + // Update history + f.x2 = f.x1 + f.x1 = in + f.y2 = f.y1 + f.y1 = out + + return out +} + +// Reset clears the filter memory +func (f *BiquadFilter) Reset() { + f.x1, f.x2, f.y1, f.y2 = 0, 0, 0, 0 +} + +// EQChain manages a cascade of filters (our 5 bands) +type EQChain struct { + Filters []*BiquadFilter +} + +// NewEQChain creates the standard 5-band EQ chain +func NewEQChain(sampleRate float64) *EQChain { + return &EQChain{ + Filters: []*BiquadFilter{ + NewPeakingEQ(sampleRate, 100, 1.0, 0), // SUB (Reduced from 1000 to proper bass freq) + NewPeakingEQ(sampleRate, 350, 1.0, 0), // LOW + NewPeakingEQ(sampleRate, 1000, 1.0, 0), // MID + NewPeakingEQ(sampleRate, 3000, 1.0, 0), // HI + NewPeakingEQ(sampleRate, 8000, 1.0, 0), // AIR + }, + } +} + +// SetGain sets the gain for a specific band index (0-4) +func (e *EQChain) SetGain(bandIdx int, dbGain float64) { + if bandIdx < 0 || bandIdx >= len(e.Filters) { + return + } + + rate := 48000.0 // Assuming fixed rate for now + // Frequencies map to our standard bands + freqs := []float64{100, 350, 1000, 3000, 8000} + + e.Filters[bandIdx].Configure(rate, freqs[bandIdx], 1.0, dbGain) +} + +// Reset clears history of all filters +func (e *EQChain) Reset() { + for _, f := range e.Filters { + f.Reset() + } +} + +// ProcessBlock processes a slice of samples in-place (or returns new slice) +// We'll return a new float buffer for FFT analysis anyway +func (e *EQChain) Process(samples []int16) []int16 { + out := make([]int16, len(samples)) + + for i, s := range samples { + val := float64(s) + + // Run through cascade + for _, f := range e.Filters { + val = f.Process(val) + } + + // Clip + if val > 32767 { + val = 32767 + } else if val < -32768 { + val = -32768 + } + + out[i] = int16(val) + } + return out +} diff --git a/pkg/audio/common.go b/pkg/audio/common.go index a1cf3f8..401e673 100644 --- a/pkg/audio/common.go +++ b/pkg/audio/common.go @@ -8,6 +8,8 @@ const ( // UserSettings represents per-user audio configuration type UserSettings struct { - Volume float32 // 0.0 - 1.0 (or higher for boost) - Muted bool + Volume float32 // 0.0 - 1.0 (or higher for boost) + Muted bool + Gains []float64 // 5-band Equalizer Gains in dB + EQBands []float64 } diff --git a/pkg/audio/fft.go b/pkg/audio/fft.go new file mode 100644 index 0000000..0dd2950 --- /dev/null +++ b/pkg/audio/fft.go @@ -0,0 +1,138 @@ +package audio + +import ( + "math" +) + +// CalculateEQBands computes frequency magnitudes for 5 EQ bands from PCM samples. +// It uses a simplified approach tailored for visualization: +// 1. Converts int16 PCM to float64 +// 2. Applies a Window function (Hanning) +// 3. Performs a simple DFT (Discrete Fourier Transform) - sufficient for small N/visualization +// 4. Aggregates bins into 5 bands: Bass, Low-Mid, Mid, Hybrid-High, High +func CalculateEQBands(samples []int16, sampleRate int) []float64 { + // We'll use a relatively small window size for responsiveness and performance + // 512 samples at 48kHz is ~10ms, which is very fast. + // 1024 samples is ~21ms. + + const windowSize = 1024 + if len(samples) < windowSize { + // Not enough data, return empty or zeroed bands + // Pad with zeros if we really wanted to processing, but for vis just return what we have? + // Actually, let's just make a copy and pad with zeros to windowSize + padded := make([]int16, windowSize) + copy(padded, samples) + samples = padded + } else { + // Take the last windowSize samples (most recent audio) + samples = samples[len(samples)-windowSize:] + } + + // Prepare complex input + real := make([]float64, windowSize) + imag := make([]float64, windowSize) + + // Apply Hanning Window + for i := 0; i < windowSize; i++ { + val := float64(samples[i]) / 32768.0 // Normalize to -1.0..1.0 + // Hanning window formula + window := 0.5 * (1 - math.Cos(2*math.Pi*float64(i)/float64(windowSize-1))) + real[i] = val * window + } + + // Perform basic FFT (Cooley-Tukey) + // Since windowSize is power of 2 (1024), we can use a recursive or iterative FFT. + // For simplicity in a single file without deps, we'll write a small recursive one or iterative. + // Given typical Go performance, a simple recursive one is fine for N=1024 per user talk event. + fft(real, imag) + + // Calculate magnitudes and bucket into bands + // Freq resolution = SampleRate / WindowSize = 48000 / 1024 ~= 46.875 Hz per bin + // Nyquist = 24000 Hz (Bin 512) + + // Band definitions (approximate range): + // 1. Sub/Bass: 0 - 250 Hz (Bins 0-5) + // 2. Low Mids: 250 - 500 Hz (Bins 6-10) + // 3. Mids: 500 - 2000 Hz (Bins 11-42) + // 4. Upper Mids: 2000 - 4000 Hz (Bins 43-85) + // 5. Highs: 4000Hz+ (Bins 86-512) + + bands := make([]float64, 5) + + // Helper to collect energy + collectEnergy := func(startBin, endBin int) float64 { + sum := 0.0 + for i := startBin; i <= endBin && i < windowSize/2; i++ { + // Magnitude = sqrt(re^2 + im^2) + mag := math.Sqrt(real[i]*real[i] + imag[i]*imag[i]) + sum += mag + } + // Average + count := float64(endBin - startBin + 1) + if count > 0 { + return sum / count + } + return 0 + } + + bands[0] = collectEnergy(1, 6) // Skip DC (bin 0) + bands[1] = collectEnergy(7, 12) + bands[2] = collectEnergy(13, 45) + bands[3] = collectEnergy(46, 90) + bands[4] = collectEnergy(91, 511) + + // Normalize output for visualization (0.0 to 1.0) + // We need some scaling factor. Based on expected signals. + const scale = 50.0 // heuristic + for i := range bands { + bands[i] = bands[i] * scale + if bands[i] > 1.0 { + bands[i] = 1.0 + } + } + + return bands +} + +// Simple in-place Cooley-Tukey FFT. +// n must be power of 2. +func fft(real, imag []float64) { + n := len(real) + if n <= 1 { + return + } + + // Split even and odd + half := n / 2 + realEven := make([]float64, half) + imagEven := make([]float64, half) + realOdd := make([]float64, half) + imagOdd := make([]float64, half) + + for i := 0; i < half; i++ { + realEven[i] = real[2*i] + imagEven[i] = imag[2*i] + realOdd[i] = real[2*i+1] + imagOdd[i] = imag[2*i+1] + } + + // Recursion + fft(realEven, imagEven) + fft(realOdd, imagOdd) + + // Combine + for k := 0; k < half; k++ { + tReal := math.Cos(-2 * math.Pi * float64(k) / float64(n)) + tImag := math.Sin(-2 * math.Pi * float64(k) / float64(n)) + + // Multiply odd by twist factor (tReal+itImag) * (oddReal+iOddImag) + // (ac - bd) + i(ad + bc) + twistReal := tReal*realOdd[k] - tImag*imagOdd[k] + twistImag := tReal*imagOdd[k] + tImag*realOdd[k] + + real[k] = realEven[k] + twistReal + imag[k] = imagEven[k] + twistImag + real[k+half] = realEven[k] - twistReal + imag[k+half] = imagEven[k] - twistImag + } +} diff --git a/pkg/audio/playback.go b/pkg/audio/playback.go index 20afca7..4f95d7f 100644 --- a/pkg/audio/playback.go +++ b/pkg/audio/playback.go @@ -30,6 +30,9 @@ type Player struct { // map[SenderID] -> AudioQueue userBuffers map[uint16][]int16 + // User EQs (DSP Filters) + userEQs map[uint16]*EQChain + // User settings userSettings map[uint16]*UserSettings bufferMu sync.Mutex @@ -108,6 +111,7 @@ func NewPlayer() (*Player, error) { muted: false, stopChan: make(chan struct{}), userBuffers: make(map[uint16][]int16), + userEQs: make(map[uint16]*EQChain), userSettings: make(map[uint16]*UserSettings), }, nil } @@ -171,6 +175,53 @@ func (p *Player) PlayPCM(senderID uint16, samples []int16) { return } + // Apply EQ Filters if gains are non-zero + p.ensureEQ(senderID) + + // Check if any band has gain != 0 + hasActiveEQ := false + if settings, ok := p.userSettings[senderID]; ok && len(settings.Gains) == 5 { + for _, g := range settings.Gains { + if g != 0 { + hasActiveEQ = true + break + } + } + } + + // Apply filters if needed + // Note: We should probably process always if we want smooth transitions, + // but for optimization we skip if all 0. + // However, skipping might cause clicks if we jump from filtered to non-filtered state abruptly. + // For "Pro" audio, always process. For TUI app, let's process if active. + if hasActiveEQ { + if eq, ok := p.userEQs[senderID]; ok { + // Update gains from settings + // (Ideally we only do this on change, but doing it here ensures sync) + gains := p.userSettings[senderID].Gains + for i, g := range gains { + eq.SetGain(i, g) + } + + // Process in-place (conceptually) - actually implementation creates new slice + samples = eq.Process(samples) + } + } else { + // Even if not active, we might want to reset filters if they were active before? + // Or just leave them alone. + } + + // Calculate EQ bands for visualization + // We do this BEFORE appending to buffer to ensure we have visual feedback even if buffer is full/lagging + // This is a "fire and forget" calculation for UI + bands := CalculateEQBands(samples, 48000) + + // Update user settings with new bands + if _, ok := p.userSettings[senderID]; !ok { + p.userSettings[senderID] = &UserSettings{Volume: 1.0, Muted: false} + } + p.userSettings[senderID].EQBands = bands + // Append to user's specific buffer // This ensures sequential playback for the same user p.userBuffers[senderID] = append(p.userBuffers[senderID], samples...) @@ -249,6 +300,66 @@ func (p *Player) GetUserSettings(clientID uint16) (float32, bool) { return 1.0, false } +// GetEQBands returns the current 5-band EQ values for a user (0.0-1.0) +func (p *Player) GetEQBands(clientID uint16) []float64 { + p.bufferMu.Lock() + defer p.bufferMu.Unlock() + + if settings, ok := p.userSettings[clientID]; ok { + return settings.EQBands + } + return nil +} + +// SetUserGain sets the EQ gain for a specific band (0-4) and user. +// Gain is in dB (e.g. -12.0 to +12.0) +func (p *Player) SetUserGain(clientID uint16, bandIdx int, gainDb float64) { + p.bufferMu.Lock() + defer p.bufferMu.Unlock() + + p.ensureUserSettings(clientID) + + // Ensure Gains slice exists + if len(p.userSettings[clientID].Gains) != 5 { + p.userSettings[clientID].Gains = make([]float64, 5) + } + + if bandIdx >= 0 && bandIdx < 5 { + p.userSettings[clientID].Gains[bandIdx] = gainDb + } +} + +// GetUserGain returns the gain for a band +func (p *Player) GetUserGain(clientID uint16, bandIdx int) float64 { + p.bufferMu.Lock() + defer p.bufferMu.Unlock() + + if settings, ok := p.userSettings[clientID]; ok { + if len(settings.Gains) > bandIdx { + return settings.Gains[bandIdx] + } + } + return 0.0 +} + +func (p *Player) ensureUserSettings(clientID uint16) { + if _, ok := p.userSettings[clientID]; !ok { + p.userSettings[clientID] = &UserSettings{ + Volume: 1.0, + Muted: false, + Gains: make([]float64, 5), + } + } +} + +func (p *Player) ensureEQ(clientID uint16) { + if _, ok := p.userEQs[clientID]; !ok { + // New EQ chain + // Assume 48000 Hz, would be better to pass actual stream rate + p.userEQs[clientID] = NewEQChain(48000) + } +} + func (p *Player) playbackLoop() { ticker := time.NewTicker(10 * time.Millisecond) defer ticker.Stop()