Ariver
2026-06-05 cfe4d647b4d7cc1ae41d7e193d45d546ae15b244
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package audio
 
import (
    "math"
    "sync"
    "time"
    "voicesnap/internal/logger"
 
    "github.com/gen2brain/malgo"
)
 
const (
    sampleRate       = 16000
    channels         = 1
    bitsPerSample    = 16
    silenceThreshold = 0.05
)
 
// InputDevice represents an audio input device.
type InputDevice struct {
    Name      string `json:"name"`
    IsDefault bool   `json:"isDefault"`
}
 
// Recorder captures audio from the default input device using malgo (miniaudio).
type Recorder struct {
    mu sync.Mutex
 
    ctx    *malgo.AllocatedContext
    device *malgo.Device
 
    // PCM buffer (16-bit signed, little-endian)
    pcmBuf []byte
 
    // Preferred device name (empty = system default)
    preferredDevice string
 
    // State
    isRecording    bool
    maxVolume      float64
    currentVolume  float64
    volumeCallback func(float64)
    deviceChangeCb func(string)
}
 
// NewRecorder creates a new audio recorder backed by malgo.
func NewRecorder() *Recorder {
    ctxConfig := malgo.ContextConfig{}
    ctx, err := malgo.InitContext(nil, ctxConfig, nil)
    if err != nil {
        logger.Error("Failed to init malgo context: %v", err)
        return &Recorder{}
    }
    return &Recorder{ctx: ctx}
}
 
// OnVolume registers a callback for real-time volume updates.
func (r *Recorder) OnVolume(fn func(float64)) {
    r.mu.Lock()
    defer r.mu.Unlock()
    r.volumeCallback = fn
}
 
// OnDeviceChange registers a callback for audio device changes.
func (r *Recorder) OnDeviceChange(fn func(string)) {
    r.mu.Lock()
    defer r.mu.Unlock()
    r.deviceChangeCb = fn
}
 
// ListInputDevices returns all available audio capture devices.
func (r *Recorder) ListInputDevices() []InputDevice {
    if r.ctx == nil {
        return nil
    }
    infos, err := r.ctx.Context.Devices(malgo.Capture)
    if err != nil {
        logger.Error("Failed to list devices: %v", err)
        return nil
    }
    var result []InputDevice
    for i, info := range infos {
        result = append(result, InputDevice{
            Name:      info.Name(),
            IsDefault: i == 0,
        })
    }
    return result
}
 
// SetPreferredDevice sets the preferred device by name. Empty string = system default.
func (r *Recorder) SetPreferredDevice(name string) {
    r.mu.Lock()
    defer r.mu.Unlock()
    r.preferredDevice = name
    logger.Info("Preferred device set to: %q", name)
}
 
// Start begins recording from the preferred (or default) capture device.
func (r *Recorder) Start() error {
    r.mu.Lock()
    defer r.mu.Unlock()
 
    if r.isRecording {
        return nil
    }
 
    r.pcmBuf = nil
    r.maxVolume = 0
    r.currentVolume = 0
 
    deviceConfig := malgo.DefaultDeviceConfig(malgo.Capture)
    deviceConfig.Capture.Format = malgo.FormatS16
    deviceConfig.Capture.Channels = channels
    deviceConfig.SampleRate = sampleRate
    deviceConfig.PeriodSizeInMilliseconds = 50
 
    // Use preferred device if set
    if r.preferredDevice != "" {
        infos, err := r.ctx.Context.Devices(malgo.Capture)
        if err == nil {
            for _, info := range infos {
                if info.Name() == r.preferredDevice {
                    deviceConfig.Capture.DeviceID = info.ID.Pointer()
                    break
                }
            }
        }
    }
 
    callbacks := malgo.DeviceCallbacks{
        Data: func(outputSamples, inputSamples []byte, framecount uint32) {
            r.onData(inputSamples)
        },
    }
 
    device, err := malgo.InitDevice(r.ctx.Context, deviceConfig, callbacks)
    if err != nil {
        return err
    }
 
    if err := device.Start(); err != nil {
        device.Uninit()
        return err
    }
 
    r.device = device
    r.isRecording = true
    logger.Info("Recording started (16kHz/16-bit/mono)")
    return nil
}
 
// Stop stops recording and discards audio data.
func (r *Recorder) Stop() {
    device, _ := r.detachDeviceAndPCM()
    stopAndUninitDeviceAsync(device)
}
 
// StopAndGetSamples stops recording and returns the captured audio as float32 samples.
func (r *Recorder) StopAndGetSamples() []float32 {
    device, pcm := r.detachDeviceAndPCM()
    stopAndUninitDeviceAsync(device)
 
    if len(pcm) < 2 {
        return nil
    }
 
    // Convert 16-bit PCM to float32
    numSamples := len(pcm) / 2
    samples := make([]float32, numSamples)
    for i := 0; i < numSamples; i++ {
        sample := int16(pcm[i*2]) | int16(pcm[i*2+1])<<8
        samples[i] = float32(sample) / 32768.0
    }
 
    logger.Info("Recording stopped, %d samples captured", numSamples)
    return samples
}
 
// HasVoiceActivity returns true if the max volume exceeded the silence threshold.
func (r *Recorder) HasVoiceActivity() bool {
    r.mu.Lock()
    defer r.mu.Unlock()
    return r.maxVolume > silenceThreshold
}
 
// GetDeviceName returns the name of the current capture device.
func (r *Recorder) GetDeviceName() string {
    if r.ctx == nil {
        return "Default"
    }
    devices, err := r.ctx.Context.Devices(malgo.Capture)
    if err != nil || len(devices) == 0 {
        return "Default"
    }
    return devices[0].Name()
}
 
// Close releases all audio resources.
func (r *Recorder) Close() {
    device := r.detachDevice()
    stopAndUninitDevice(device)
 
    r.mu.Lock()
    defer r.mu.Unlock()
    if r.ctx != nil {
        r.ctx.Free()
        r.ctx = nil
    }
}
 
func (r *Recorder) detachDevice() *malgo.Device {
    r.mu.Lock()
    defer r.mu.Unlock()
 
    device := r.device
    r.device = nil
    r.isRecording = false
    return device
}
 
func (r *Recorder) detachDeviceAndPCM() (*malgo.Device, []byte) {
    r.mu.Lock()
    defer r.mu.Unlock()
 
    device := r.device
    r.device = nil
    r.isRecording = false
    pcm := append([]byte(nil), r.pcmBuf...)
    r.pcmBuf = nil
    return device, pcm
}
 
func stopAndUninitDeviceAsync(device *malgo.Device) {
    if device == nil {
        return
    }
    done := make(chan struct{})
    go func() {
        stopAndUninitDevice(device)
        close(done)
    }()
    go func() {
        select {
        case <-done:
        case <-time.After(2 * time.Second):
            logger.Error("Audio device stop is still pending; continuing without blocking UI")
        }
    }()
}
 
func stopAndUninitDevice(device *malgo.Device) {
    if device == nil {
        return
    }
    logger.Info("Stopping audio device")
    device.Stop()
    logger.Info("Audio device stopped")
    device.Uninit()
    logger.Info("Audio device uninitialized")
}
 
func (r *Recorder) onData(input []byte) {
    r.mu.Lock()
 
    if !r.isRecording {
        r.mu.Unlock()
        return
    }
 
    // Append raw PCM data
    r.pcmBuf = append(r.pcmBuf, input...)
 
    // Calculate RMS volume
    numSamples := len(input) / 2
    if numSamples == 0 {
        r.mu.Unlock()
        return
    }
 
    var sum float64
    for i := 0; i < len(input)-1; i += 2 {
        sample := int16(input[i]) | int16(input[i+1])<<8
        normalized := float64(sample) / 32768.0
        sum += normalized * normalized
    }
    rms := math.Sqrt(sum / float64(numSamples))
    volume := math.Min(1.0, rms*8)
 
    r.currentVolume = volume
    if volume > r.maxVolume {
        r.maxVolume = volume
    }
 
    cb := r.volumeCallback
    r.mu.Unlock()
 
    // Invoke callback outside lock to prevent deadlock with app mutex
    if cb != nil {
        cb(volume)
    }
}