Compare commits
2 Commits
0010bc6cf7
...
be929ce55a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
be929ce55a | ||
|
|
711eb148df |
@@ -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...)
|
||||
}
|
||||
|
||||
1
go.mod
1
go.mod
@@ -30,6 +30,7 @@ require (
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-localereader v0.0.1 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/moutend/go-equalizer v0.1.0 // indirect
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
|
||||
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||
github.com/muesli/termenv v0.16.0 // indirect
|
||||
|
||||
2
go.sum
2
go.sum
@@ -32,6 +32,8 @@ github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2J
|
||||
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
|
||||
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/moutend/go-equalizer v0.1.0 h1:FDFsTr/zKUpLbNXZQmCMRDgisQhXxFOnX2q0PllJvxs=
|
||||
github.com/moutend/go-equalizer v0.1.0/go.mod h1:iahcZcStDm66TNtrkMIhrQuhWdiWbFKSVjZ8yn+7Cgw=
|
||||
github.com/moutend/go-wca v0.3.0 h1:IzhsQ44zBzMdT42xlBjiLSVya9cPYOoKx9E+yXVhFo8=
|
||||
github.com/moutend/go-wca v0.3.0/go.mod h1:7VrPO512jnjFGJ6rr+zOoCfiYjOHRPNfbttJuxAurcw=
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
|
||||
|
||||
135
pkg/audio/biquad.go
Normal file
135
pkg/audio/biquad.go
Normal file
@@ -0,0 +1,135 @@
|
||||
package audio
|
||||
|
||||
import (
|
||||
"github.com/moutend/go-equalizer/pkg/equalizer"
|
||||
)
|
||||
|
||||
// EQChain manages a cascade of filters using go-equalizer library
|
||||
// Now supports Stereo processing (Left/Right)
|
||||
// EQChain manages a cascade of filters using go-equalizer library
|
||||
// Now supports Stereo processing (Left/Right)
|
||||
type EQChain struct {
|
||||
FiltersLeft []*equalizer.Filter
|
||||
FiltersRight []*equalizer.Filter
|
||||
buffer []float64 // Reusable scratch buffer for processing
|
||||
currentGains []float64 // Cache of current gain values
|
||||
}
|
||||
|
||||
// NewEQChain creates the standard 5-band EQ chain (Stereo)
|
||||
func NewEQChain(sampleRate float64) *EQChain {
|
||||
// Standard bands: 100, 350, 1000, 3000, 8000
|
||||
// Width = 1.0 (approx 1 octave)
|
||||
|
||||
createChain := func() []*equalizer.Filter {
|
||||
f1 := equalizer.NewPeaking(sampleRate, 100, 1.0, 0)
|
||||
f2 := equalizer.NewPeaking(sampleRate, 350, 1.0, 0)
|
||||
f3 := equalizer.NewPeaking(sampleRate, 1000, 1.0, 0)
|
||||
f4 := equalizer.NewPeaking(sampleRate, 3000, 1.0, 0)
|
||||
f5 := equalizer.NewPeaking(sampleRate, 8000, 1.0, 0)
|
||||
return []*equalizer.Filter{f1, f2, f3, f4, f5}
|
||||
}
|
||||
|
||||
return &EQChain{
|
||||
FiltersLeft: createChain(),
|
||||
FiltersRight: createChain(),
|
||||
buffer: make([]float64, 1920), // Pre-allocate for Stereo 20ms frame (960*2)
|
||||
currentGains: make([]float64, 5), // Initialize cache with 0.0
|
||||
}
|
||||
}
|
||||
|
||||
// SetGain sets the gain for a specific band index (0-4)
|
||||
func (e *EQChain) SetGain(bandIdx int, dbGain float64) {
|
||||
if bandIdx < 0 || bandIdx >= 5 {
|
||||
return
|
||||
}
|
||||
|
||||
// Optimization: If gain hasn't changed, DO NOT recreate filter.
|
||||
// Recreating the filter resets its internal history state (bi-quad delay buffers),
|
||||
// causing audible clicks/pops (discontinuities) at every 20ms frame boundary.
|
||||
const epsilon = 0.001
|
||||
if delta := dbGain - e.currentGains[bandIdx]; delta > -epsilon && delta < epsilon {
|
||||
return
|
||||
}
|
||||
|
||||
rate := 48000.0 // Assuming fixed rate for now
|
||||
// Frequencies map to our standard bands
|
||||
freqs := []float64{100, 350, 1000, 3000, 8000}
|
||||
|
||||
// Create new filter with updated gain
|
||||
// We use width=1.0 consistent with constructor
|
||||
// Update BOTH Left and Right to keep balance
|
||||
e.FiltersLeft[bandIdx] = equalizer.NewPeaking(rate, freqs[bandIdx], 1.0, dbGain)
|
||||
e.FiltersRight[bandIdx] = equalizer.NewPeaking(rate, freqs[bandIdx], 1.0, dbGain)
|
||||
|
||||
// Update cache
|
||||
e.currentGains[bandIdx] = dbGain
|
||||
}
|
||||
|
||||
// Reset clears history of all filters
|
||||
func (e *EQChain) Reset() {
|
||||
// The library does not expose a Reset method.
|
||||
}
|
||||
|
||||
// Process processes a slice of samples (Interleaved Stereo)
|
||||
func (e *EQChain) Process(samples []int16) []int16 {
|
||||
// Grow buffer if needed
|
||||
if cap(e.buffer) < len(samples) {
|
||||
e.buffer = make([]float64, len(samples))
|
||||
}
|
||||
e.buffer = e.buffer[:len(samples)]
|
||||
|
||||
// Float conversion with normalization (-1.0 to 1.0)
|
||||
// We also apply a slight pre-attenuation (Headroom) to avoid clipping when boosting EQ.
|
||||
// -3dB = 0.707
|
||||
const headroom = 0.707
|
||||
const norm = 1.0 / 32768.0
|
||||
|
||||
for i, s := range samples {
|
||||
e.buffer[i] = float64(s) * norm * headroom
|
||||
}
|
||||
|
||||
// Filter processing
|
||||
// Input is assumed to be Interleaved Stereo: L, R, L, R...
|
||||
// We iterate by 2 to process pairs.
|
||||
|
||||
for i := 0; i < len(e.buffer); i += 2 {
|
||||
if i+1 >= len(e.buffer) {
|
||||
break
|
||||
}
|
||||
|
||||
valL := e.buffer[i]
|
||||
valR := e.buffer[i+1]
|
||||
|
||||
// Run through LEFT chain
|
||||
for _, f := range e.FiltersLeft {
|
||||
valL = f.Apply(valL)
|
||||
}
|
||||
|
||||
// Run through RIGHT chain
|
||||
for _, f := range e.FiltersRight {
|
||||
valR = f.Apply(valR)
|
||||
}
|
||||
|
||||
// Write back to buffer
|
||||
e.buffer[i] = valL
|
||||
e.buffer[i+1] = valR
|
||||
}
|
||||
|
||||
// Convert back to int16
|
||||
for i, val := range e.buffer {
|
||||
// Denormalize
|
||||
val = val * 32767.0
|
||||
|
||||
// Hard clipping
|
||||
if val > 32767 {
|
||||
val = 32767
|
||||
} else if val < -32768 {
|
||||
val = -32768
|
||||
}
|
||||
|
||||
// Write back directly to samples
|
||||
samples[i] = int16(val)
|
||||
}
|
||||
|
||||
return samples
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
138
pkg/audio/fft.go
Normal file
138
pkg/audio/fft.go
Normal file
@@ -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 = 10.0 // Reduced from 50.0 to fix saturation
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -66,11 +69,11 @@ func NewPlayer() (*Player, error) {
|
||||
|
||||
waveFormat := &wca.WAVEFORMATEX{
|
||||
WFormatTag: wca.WAVE_FORMAT_PCM,
|
||||
NChannels: 1,
|
||||
NChannels: 2, // STEREO
|
||||
NSamplesPerSec: 48000,
|
||||
WBitsPerSample: 16,
|
||||
NBlockAlign: 2,
|
||||
NAvgBytesPerSec: 96000,
|
||||
NBlockAlign: 4, // 16bit * 2 channels / 8 = 4 bytes
|
||||
NAvgBytesPerSec: 192000, // 48000 * 4
|
||||
CbSize: 0,
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -163,22 +167,112 @@ func (p *Player) PlayPCM(senderID uint16, samples []int16) {
|
||||
return
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------
|
||||
// PHASE 1: Read Configuration (Safe Copy)
|
||||
// ---------------------------------------------------------
|
||||
p.bufferMu.Lock()
|
||||
defer p.bufferMu.Unlock()
|
||||
|
||||
// Check per-user mute
|
||||
if settings, ok := p.userSettings[senderID]; ok && settings.Muted {
|
||||
settings, hasSettings := p.userSettings[senderID]
|
||||
if hasSettings && settings.Muted {
|
||||
p.bufferMu.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
// Append to user's specific buffer
|
||||
// This ensures sequential playback for the same user
|
||||
p.userBuffers[senderID] = append(p.userBuffers[senderID], samples...)
|
||||
// Get EQ Instance (Create if needed)
|
||||
if _, ok := p.userEQs[senderID]; !ok {
|
||||
p.userEQs[senderID] = NewEQChain(48000)
|
||||
}
|
||||
userEQ := p.userEQs[senderID]
|
||||
|
||||
// Limit buffer size per user to avoid memory leaks if stalled
|
||||
if len(p.userBuffers[senderID]) > 48000*2 { // 2 seconds max
|
||||
// Check/Copy Gains
|
||||
var gains []float64
|
||||
hasActiveEQ := false
|
||||
if hasSettings && len(settings.Gains) == 5 {
|
||||
// Copy gains to avoid race if UI changes them while we process
|
||||
gains = make([]float64, 5)
|
||||
copy(gains, settings.Gains)
|
||||
|
||||
for _, g := range gains {
|
||||
if g != 0 {
|
||||
hasActiveEQ = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
p.bufferMu.Unlock()
|
||||
// ---------------------------------------------------------
|
||||
// END PHASE 1 (Lock Released)
|
||||
// ---------------------------------------------------------
|
||||
|
||||
// ---------------------------------------------------------
|
||||
// PHASE 2: Heavy Processing (Concurrent)
|
||||
// ---------------------------------------------------------
|
||||
|
||||
// Normalize to Stereo (Interleaved)
|
||||
// If input is Mono (960 samples), expand to Stereo (1920 samples)
|
||||
// If input is already Stereo, using it as is.
|
||||
var stereoSamples []int16
|
||||
|
||||
if len(samples) < 1500 { // Heuristic for Mono (960)
|
||||
stereoSamples = make([]int16, len(samples)*2)
|
||||
for i, s := range samples {
|
||||
stereoSamples[i*2] = s
|
||||
stereoSamples[i*2+1] = s
|
||||
}
|
||||
} else {
|
||||
// Already stereo (assumed)
|
||||
stereoSamples = make([]int16, len(samples))
|
||||
copy(stereoSamples, samples)
|
||||
}
|
||||
|
||||
// Apply EQ Filters if needed
|
||||
if hasActiveEQ {
|
||||
// Update gains on the private EQ instance (Thread-safe per user)
|
||||
for i, g := range gains {
|
||||
userEQ.SetGain(i, g)
|
||||
}
|
||||
// Process Stereo
|
||||
stereoSamples = userEQ.Process(stereoSamples)
|
||||
}
|
||||
|
||||
// Calculate EQ bands for visualization
|
||||
// Downmix to Mono for FFT visualization to save CPU and complexity
|
||||
vizSamples := make([]int16, len(stereoSamples)/2)
|
||||
for i := 0; i < len(vizSamples); i++ {
|
||||
// Average L+R
|
||||
val := (int32(stereoSamples[i*2]) + int32(stereoSamples[i*2+1])) / 2
|
||||
vizSamples[i] = int16(val)
|
||||
}
|
||||
bands := CalculateEQBands(vizSamples, 48000)
|
||||
|
||||
// ---------------------------------------------------------
|
||||
// PHASE 3: Write Output (Lock Acquired)
|
||||
// ---------------------------------------------------------
|
||||
p.bufferMu.Lock()
|
||||
defer p.bufferMu.Unlock()
|
||||
|
||||
// Re-check existence (could have disconnected?)
|
||||
// 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
|
||||
p.userBuffers[senderID] = append(p.userBuffers[senderID], stereoSamples...)
|
||||
|
||||
// Limit buffer size per user (Stereo 2sec = 48000*2*2 = 192000 items)
|
||||
// frameSamples is 960 (20ms). 2sec = 100 frames * 960 * 2 = 192000
|
||||
const maxBufferSize = 48000 * 2 * 2 // 2 seconds stereo
|
||||
if len(p.userBuffers[senderID]) > maxBufferSize {
|
||||
// Drop oldest
|
||||
drop := len(p.userBuffers[senderID]) - 48000
|
||||
drop := len(p.userBuffers[senderID]) - maxBufferSize
|
||||
// Ensure we drop aligned to stereo frame (even number)
|
||||
if drop%2 != 0 {
|
||||
drop++
|
||||
}
|
||||
p.userBuffers[senderID] = p.userBuffers[senderID][drop:]
|
||||
}
|
||||
}
|
||||
@@ -249,6 +343,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()
|
||||
@@ -278,7 +432,8 @@ func (p *Player) writeFrame() {
|
||||
p.bufferMu.Lock()
|
||||
|
||||
// Mix audio from all active user buffers
|
||||
mixed := make([]int32, frameSamples)
|
||||
// Stereo mixing: buffer size is frameSamples * 2
|
||||
mixed := make([]int32, frameSamples*2)
|
||||
activeUsers := 0
|
||||
hasAnyAudio := false
|
||||
|
||||
@@ -286,12 +441,15 @@ func (p *Player) writeFrame() {
|
||||
if len(buf) > 0 {
|
||||
hasAnyAudio = true
|
||||
activeUsers++
|
||||
// Take up to frameSamples from this user
|
||||
toTake := frameSamples
|
||||
if len(buf) < frameSamples {
|
||||
// Take up to frameSamples*2 (Stereo) from this user
|
||||
toTake := frameSamples * 2
|
||||
if len(buf) < int(frameSamples)*2 {
|
||||
toTake = len(buf)
|
||||
}
|
||||
|
||||
// Ensure we take pairs (alignment)
|
||||
toTake = toTake &^ 1 // clear lowest bit
|
||||
|
||||
for i := 0; i < toTake; i++ {
|
||||
sample := int32(buf[i])
|
||||
|
||||
@@ -304,10 +462,10 @@ func (p *Player) writeFrame() {
|
||||
}
|
||||
|
||||
// Advance buffer
|
||||
if len(buf) <= frameSamples {
|
||||
delete(p.userBuffers, id)
|
||||
if len(buf) <= toTake {
|
||||
delete(p.userBuffers, id) // Finished this buffer
|
||||
} else {
|
||||
p.userBuffers[id] = buf[frameSamples:]
|
||||
p.userBuffers[id] = buf[toTake:]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -330,8 +488,19 @@ func (p *Player) writeFrame() {
|
||||
p.mu.Unlock()
|
||||
|
||||
// Write mixed samples with clipping protection and volume application
|
||||
bufSlice := unsafe.Slice(buffer, int(frameSamples)*2)
|
||||
for i := 0; i < int(frameSamples); i++ {
|
||||
// Output buffer is for Stereo (frameSamples * 2 channels)
|
||||
bufSlice := unsafe.Slice(buffer, int(frameSamples)*2*2) // *2 channels *2 bytes? No, unsafe.Slice takes count of Type.
|
||||
// If buffer is *byte, we need bytes. frameSamples * 2 channels * 2 bytes/sample.
|
||||
// Wait, GetBuffer returns BYTE pointer.
|
||||
// Let's use uint16 slice.
|
||||
|
||||
// The logic below was: binary.LittleEndian.PutUint16(bufSlice[i*2:], ...)
|
||||
// frameSamples was 960. loop 0..960.
|
||||
// Now we have Stereo mixed buffer. Length = frameSamples * 2.
|
||||
// We need to write frameSamples * 2 samples.
|
||||
|
||||
// Correct loop for Stereo:
|
||||
for i := 0; i < int(frameSamples)*2; i++ { // Iterate over all samples (L, R, L, R...)
|
||||
val := mixed[i]
|
||||
|
||||
// Apply master volume
|
||||
@@ -343,6 +512,10 @@ func (p *Player) writeFrame() {
|
||||
} else if val < -32768 {
|
||||
val = -32768
|
||||
}
|
||||
|
||||
// Map to output byte buffer
|
||||
// i is sample index. Each sample is 2 bytes.
|
||||
// Offset = i * 2.
|
||||
binary.LittleEndian.PutUint16(bufSlice[i*2:], uint16(val))
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user