Ariver
2026-07-12 33f00a1136c9f7e501b989d432b709d632905304
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
package audio
 
import (
    "errors"
    "os"
    "sync"
    "sync/atomic"
    "testing"
    "time"
 
    "github.com/gen2brain/malgo"
)
 
func TestMain(m *testing.M) {
    oldEnsure := ensureMicrophoneAuthorization
    ensureMicrophoneAuthorization = func() microphoneAuthorization {
        return microphoneAuthorization{granted: true, state: "granted"}
    }
    code := m.Run()
    ensureMicrophoneAuthorization = oldEnsure
    os.Exit(code)
}
 
func TestReadSamplesSinceReturnsOnlyNewSamples(t *testing.T) {
    r := &Recorder{
        pcmBuf: pcm16LE(0, 16384, -32768),
    }
 
    samples, nextOffset := r.ReadSamplesSince(1)
    if nextOffset != 3 {
        t.Fatalf("next offset = %d, want 3", nextOffset)
    }
    if len(samples) != 2 {
        t.Fatalf("sample count = %d, want 2", len(samples))
    }
    if samples[0] != 0.5 {
        t.Fatalf("samples[0] = %f, want 0.5", samples[0])
    }
    if samples[1] != -1 {
        t.Fatalf("samples[1] = %f, want -1", samples[1])
    }
}
 
func TestReadSamplesSinceClampsOffset(t *testing.T) {
    r := &Recorder{
        pcmBuf: pcm16LE(0, 16384),
    }
 
    samples, nextOffset := r.ReadSamplesSince(99)
    if nextOffset != 2 {
        t.Fatalf("next offset = %d, want 2", nextOffset)
    }
    if len(samples) != 0 {
        t.Fatalf("sample count = %d, want 0", len(samples))
    }
}
 
func TestOnDataCapsRecordingBuffer(t *testing.T) {
    r := &Recorder{
        isRecording: true,
        pcmBuf:      make([]byte, maxPCMBufferBytes-2),
    }
 
    r.onData(pcm16LE(1, 2))
 
    if got := len(r.pcmBuf); got != maxPCMBufferBytes {
        t.Fatalf("pcm buffer length = %d, want capped %d", got, maxPCMBufferBytes)
    }
    if !r.bufferLimitHit {
        t.Fatal("bufferLimitHit should be set after truncating at cap")
    }
 
    r.onData(pcm16LE(3))
    if got := len(r.pcmBuf); got != maxPCMBufferBytes {
        t.Fatalf("pcm buffer length after cap = %d, want %d", got, maxPCMBufferBytes)
    }
}
 
func TestStartWithoutMicrophonePermissionDoesNotInitializeDevice(t *testing.T) {
    oldEnsure := ensureMicrophoneAuthorization
    ensureMicrophoneAuthorization = func() microphoneAuthorization {
        return microphoneAuthorization{granted: false, state: "denied"}
    }
    defer func() {
        ensureMicrophoneAuthorization = oldEnsure
    }()
 
    device := newFakeRecorderDevice()
    ctx := &fakeRecorderContext{device: device}
    r := &Recorder{ctx: ctx}
 
    err := r.Start()
    if err == nil {
        t.Fatal("Start returned nil without microphone permission")
    }
    if ctx.initEntered.Load() {
        t.Fatal("initDevice should not run without microphone permission")
    }
    if device.startEntered.Load() {
        t.Fatal("device Start should not run without microphone permission")
    }
 
    r.mu.Lock()
    defer r.mu.Unlock()
    if r.startRequested || r.isStarting || r.isRecording || r.stopAfterStart || r.device != nil {
        t.Fatalf("recorder state leaked after microphone denial: startRequested=%t isStarting=%t isRecording=%t stopAfterStart=%t deviceNil=%t",
            r.startRequested, r.isStarting, r.isRecording, r.stopAfterStart, r.device == nil)
    }
}
 
func TestStopWhileMicrophoneAuthorizationPendingPreventsNativeStart(t *testing.T) {
    oldEnsure := ensureMicrophoneAuthorization
    entered := make(chan struct{})
    allow := make(chan struct{})
    var enteredOnce sync.Once
    ensureMicrophoneAuthorization = func() microphoneAuthorization {
        enteredOnce.Do(func() { close(entered) })
        <-allow
        return microphoneAuthorization{granted: true, state: "granted"}
    }
    defer func() {
        ensureMicrophoneAuthorization = oldEnsure
    }()
 
    device := newFakeRecorderDevice()
    ctx := &fakeRecorderContext{device: device}
    r := &Recorder{ctx: ctx}
 
    startDone := make(chan error, 1)
    go func() {
        startDone <- r.Start()
    }()
    select {
    case <-entered:
    case <-time.After(time.Second):
        t.Fatal("microphone authorization was not entered")
    }
 
    r.Stop()
    close(allow)
    if err := <-startDone; err != nil {
        t.Fatalf("Start returned error = %v", err)
    }
    if ctx.initEntered.Load() {
        t.Fatal("initDevice should not run after Stop during microphone authorization")
    }
    if device.startEntered.Load() {
        t.Fatal("device Start should not run after Stop during microphone authorization")
    }
 
    r.mu.Lock()
    defer r.mu.Unlock()
    if r.startRequested || r.isStarting || r.isRecording || r.stopAfterStart || r.device != nil {
        t.Fatalf("recorder state leaked after pending authorization stop: startRequested=%t isStarting=%t isRecording=%t stopAfterStart=%t deviceNil=%t",
            r.startRequested, r.isStarting, r.isRecording, r.stopAfterStart, r.device == nil)
    }
}
 
func TestStopAndGetSamplesWhileMicrophoneAuthorizationPendingPreventsNativeStart(t *testing.T) {
    oldEnsure := ensureMicrophoneAuthorization
    entered := make(chan struct{})
    allow := make(chan struct{})
    var enteredOnce sync.Once
    ensureMicrophoneAuthorization = func() microphoneAuthorization {
        enteredOnce.Do(func() { close(entered) })
        <-allow
        return microphoneAuthorization{granted: true, state: "granted"}
    }
    defer func() {
        ensureMicrophoneAuthorization = oldEnsure
    }()
 
    device := newFakeRecorderDevice()
    ctx := &fakeRecorderContext{device: device}
    r := &Recorder{ctx: ctx}
 
    startDone := make(chan error, 1)
    go func() {
        startDone <- r.Start()
    }()
    select {
    case <-entered:
    case <-time.After(time.Second):
        t.Fatal("microphone authorization was not entered")
    }
 
    samples := r.StopAndGetSamples()
    if len(samples) != 0 {
        t.Fatalf("samples while microphone authorization pending = %d, want 0", len(samples))
    }
    close(allow)
    if err := <-startDone; err != nil {
        t.Fatalf("Start returned error = %v", err)
    }
    if ctx.initEntered.Load() {
        t.Fatal("initDevice should not run after StopAndGetSamples during microphone authorization")
    }
    if device.startEntered.Load() {
        t.Fatal("device Start should not run after StopAndGetSamples during microphone authorization")
    }
 
    r.mu.Lock()
    defer r.mu.Unlock()
    if r.startRequested || r.isStarting || r.isRecording || r.stopAfterStart || r.device != nil {
        t.Fatalf("recorder state leaked after pending authorization samples stop: startRequested=%t isStarting=%t isRecording=%t stopAfterStart=%t deviceNil=%t",
            r.startRequested, r.isStarting, r.isRecording, r.stopAfterStart, r.device == nil)
    }
}
 
func TestCloseWaitsForBlockedStartBeforeFreeingContext(t *testing.T) {
    device := newFakeRecorderDevice()
    ctx := &fakeRecorderContext{device: device}
    r := &Recorder{ctx: ctx}
 
    startDone := make(chan error, 1)
    go func() {
        startDone <- r.Start()
    }()
    waitForRecorderTest(t, func() bool { return device.startEntered.Load() })
 
    closeDone := make(chan struct{})
    go func() {
        r.Close()
        close(closeDone)
    }()
 
    select {
    case <-closeDone:
        t.Fatal("Close returned while recorder Start was still blocked")
    case <-time.After(50 * time.Millisecond):
    }
    if got := ctx.freeCount.Load(); got != 0 {
        t.Fatalf("context freed before Start returned = %d, want 0", got)
    }
    if got := device.uninitCount.Load(); got != 0 {
        t.Fatalf("device uninitialized before Start returned = %d, want 0", got)
    }
 
    close(device.allowStart)
    if err := <-startDone; err == nil {
        t.Fatal("Start returned nil after Close was requested during startup")
    }
    waitForRecorderTest(t, func() bool {
        select {
        case <-closeDone:
            return true
        default:
            return false
        }
    })
    if got := ctx.freeCount.Load(); got != 1 {
        t.Fatalf("context free count = %d, want 1", got)
    }
    if got := device.stopCount.Load(); got != 1 {
        t.Fatalf("device stop count = %d, want 1", got)
    }
    if got := device.uninitCount.Load(); got != 1 {
        t.Fatalf("device uninit count = %d, want 1", got)
    }
}
 
func TestStopWhileStartBlockedDefersDeviceCleanup(t *testing.T) {
    device := newFakeRecorderDevice()
    ctx := &fakeRecorderContext{device: device}
    r := &Recorder{ctx: ctx}
 
    startDone := make(chan error, 1)
    go func() {
        startDone <- r.Start()
    }()
    waitForRecorderTest(t, func() bool { return device.startEntered.Load() })
 
    stopDone := make(chan struct{})
    go func() {
        r.Stop()
        close(stopDone)
    }()
 
    select {
    case <-stopDone:
    case <-time.After(time.Second):
        t.Fatal("Stop should return while recorder Start is still blocked")
    }
    if got := device.stopCount.Load(); got != 0 {
        t.Fatalf("device stopped before Start returned = %d, want 0", got)
    }
    if got := device.uninitCount.Load(); got != 0 {
        t.Fatalf("device uninitialized before Start returned = %d, want 0", got)
    }
 
    close(device.allowStart)
    if err := <-startDone; err != nil {
        t.Fatalf("Start returned error = %v", err)
    }
    waitForRecorderTest(t, func() bool { return device.uninitCount.Load() == 1 })
    if got := device.stopCount.Load(); got != 1 {
        t.Fatalf("device stop count = %d, want 1", got)
    }
}
 
func TestStopAndGetSamplesWhileStartBlockedReturnsBufferedPCM(t *testing.T) {
    device := newFakeRecorderDevice()
    ctx := &fakeRecorderContext{device: device}
    r := &Recorder{ctx: ctx}
 
    startDone := make(chan error, 1)
    go func() {
        startDone <- r.Start()
    }()
    waitForRecorderTest(t, func() bool { return device.startEntered.Load() })
 
    r.onData(pcm16LE(16384, -32768))
    samples := r.StopAndGetSamples()
    if len(samples) != 2 {
        t.Fatalf("samples len = %d, want 2", len(samples))
    }
    if samples[0] != 0.5 || samples[1] != -1 {
        t.Fatalf("samples = %#v, want [0.5 -1]", samples)
    }
    if got := device.stopCount.Load(); got != 0 {
        t.Fatalf("device stopped before Start returned = %d, want 0", got)
    }
    if got := device.uninitCount.Load(); got != 0 {
        t.Fatalf("device uninitialized before Start returned = %d, want 0", got)
    }
 
    close(device.allowStart)
    if err := <-startDone; err != nil {
        t.Fatalf("Start returned error = %v", err)
    }
    if got := device.stopCount.Load(); got != 1 {
        t.Fatalf("device stop count after Start returned = %d, want 1", got)
    }
    if got := device.uninitCount.Load(); got != 1 {
        t.Fatalf("device uninit count after Start returned = %d, want 1", got)
    }
}
 
func TestStopAndGetSamplesBeforeDevicePublishDefersIntentAndCleansInitializedDevice(t *testing.T) {
    device := newFakeRecorderDevice()
    initBlock := make(chan struct{})
    ctx := &fakeRecorderContext{device: device, initBlock: initBlock}
    r := &Recorder{ctx: ctx}
 
    startDone := make(chan error, 1)
    go func() {
        startDone <- r.Start()
    }()
    waitForRecorderTest(t, func() bool { return ctx.initEntered.Load() })
 
    samples := r.StopAndGetSamples()
    if len(samples) != 0 {
        t.Fatalf("samples len before device publish = %d, want 0", len(samples))
    }
    if device.startEntered.Load() {
        t.Fatal("device Start should not be entered while initDevice is blocked")
    }
    if got := device.stopCount.Load(); got != 0 {
        t.Fatalf("device stopped before it was published = %d, want 0", got)
    }
    if got := device.uninitCount.Load(); got != 0 {
        t.Fatalf("device uninit before initDevice returned = %d, want 0", got)
    }
 
    close(initBlock)
    if err := <-startDone; err != nil {
        t.Fatalf("Start returned error = %v", err)
    }
    if device.startEntered.Load() {
        t.Fatal("device Start should not run after stop intent arrived before publish")
    }
    if got := device.stopCount.Load(); got != 0 {
        t.Fatalf("device stop count = %d, want 0 for never-started device", got)
    }
    if got := device.uninitCount.Load(); got != 1 {
        t.Fatalf("device uninit count = %d, want 1", got)
    }
 
    r.mu.Lock()
    defer r.mu.Unlock()
    if r.startRequested || r.isStarting || r.isRecording || r.stopAfterStart || r.device != nil {
        t.Fatalf("recorder state leaked after pre-publish stop: startRequested=%t isStarting=%t isRecording=%t stopAfterStart=%t deviceNil=%t",
            r.startRequested, r.isStarting, r.isRecording, r.stopAfterStart, r.device == nil)
    }
}
 
func TestStopBeforeDevicePublishDefersIntentAndCleansInitializedDevice(t *testing.T) {
    device := newFakeRecorderDevice()
    initBlock := make(chan struct{})
    ctx := &fakeRecorderContext{device: device, initBlock: initBlock}
    r := &Recorder{ctx: ctx}
 
    startDone := make(chan error, 1)
    go func() {
        startDone <- r.Start()
    }()
    waitForRecorderTest(t, func() bool { return ctx.initEntered.Load() })
 
    r.Stop()
    if device.startEntered.Load() {
        t.Fatal("device Start should not be entered while initDevice is blocked")
    }
    if got := device.stopCount.Load(); got != 0 {
        t.Fatalf("device stopped before it was published = %d, want 0", got)
    }
    if got := device.uninitCount.Load(); got != 0 {
        t.Fatalf("device uninit before initDevice returned = %d, want 0", got)
    }
 
    close(initBlock)
    if err := <-startDone; err != nil {
        t.Fatalf("Start returned error = %v", err)
    }
    if device.startEntered.Load() {
        t.Fatal("device Start should not run after stop intent arrived before publish")
    }
    if got := device.stopCount.Load(); got != 0 {
        t.Fatalf("device stop count = %d, want 0 for never-started device", got)
    }
    if got := device.uninitCount.Load(); got != 1 {
        t.Fatalf("device uninit count = %d, want 1", got)
    }
}
 
func TestStopWhileStartBlockedLetsStartErrorCleanup(t *testing.T) {
    startErr := errors.New("start failed")
    device := newFakeRecorderDevice()
    device.startErr = startErr
    ctx := &fakeRecorderContext{device: device}
    r := &Recorder{ctx: ctx}
 
    startDone := make(chan error, 1)
    go func() {
        startDone <- r.Start()
    }()
    waitForRecorderTest(t, func() bool { return device.startEntered.Load() })
 
    stopDone := make(chan struct{})
    go func() {
        r.Stop()
        close(stopDone)
    }()
 
    select {
    case <-stopDone:
    case <-time.After(time.Second):
        t.Fatal("Stop should return while recorder Start is still blocked")
    }
    if got := device.uninitCount.Load(); got != 0 {
        t.Fatalf("device uninit before Start error returned = %d, want 0", got)
    }
    close(device.allowStart)
    if err := <-startDone; !errors.Is(err, startErr) {
        t.Fatalf("Start error = %v, want %v", err, startErr)
    }
    if got := device.uninitCount.Load(); got != 1 {
        t.Fatalf("device uninit count = %d, want 1", got)
    }
}
 
func pcm16LE(values ...int16) []byte {
    buf := make([]byte, len(values)*2)
    for i, value := range values {
        buf[i*2] = byte(value)
        buf[i*2+1] = byte(value >> 8)
    }
    return buf
}
 
type fakeRecorderContext struct {
    device      *fakeRecorderDevice
    initErr     error
    initBlock   <-chan struct{}
    initEntered atomic.Bool
    freeCount   atomic.Int32
}
 
func (c *fakeRecorderContext) devices(malgo.DeviceType) ([]malgo.DeviceInfo, error) {
    return nil, nil
}
 
func (c *fakeRecorderContext) initDevice(malgo.DeviceConfig, malgo.DeviceCallbacks) (recorderDevice, error) {
    c.initEntered.Store(true)
    if c.initBlock != nil {
        <-c.initBlock
    }
    if c.initErr != nil {
        return nil, c.initErr
    }
    return c.device, nil
}
 
func (c *fakeRecorderContext) free() {
    c.freeCount.Add(1)
}
 
type fakeRecorderDevice struct {
    startEntered atomic.Bool
    startOnce    sync.Once
    allowStart   chan struct{}
    startErr     error
    stopCount    atomic.Int32
    uninitCount  atomic.Int32
}
 
func newFakeRecorderDevice() *fakeRecorderDevice {
    return &fakeRecorderDevice{allowStart: make(chan struct{})}
}
 
func (d *fakeRecorderDevice) Start() error {
    d.startOnce.Do(func() {
        d.startEntered.Store(true)
    })
    <-d.allowStart
    return d.startErr
}
 
func (d *fakeRecorderDevice) Stop() error {
    d.stopCount.Add(1)
    return nil
}
 
func (d *fakeRecorderDevice) Uninit() {
    d.uninitCount.Add(1)
}
 
func waitForRecorderTest(t *testing.T, cond func() bool) {
    t.Helper()
    deadline := time.Now().Add(2 * time.Second)
    for time.Now().Before(deadline) {
        if cond() {
            return
        }
        time.Sleep(10 * time.Millisecond)
    }
    t.Fatal("condition not met before timeout")
}