-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathencoder_test.go
More file actions
845 lines (679 loc) · 24.1 KB
/
Copy pathencoder_test.go
File metadata and controls
845 lines (679 loc) · 24.1 KB
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package opus
import (
"encoding/binary"
"math"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const encoderTestFrameSampleCount = 960
func TestNewEncoder(t *testing.T) {
encoder, err := NewEncoder()
require.NoError(t, err)
assert.Equal(t, 48000, encoder.sampleRate)
assert.Equal(t, 1, encoder.channels)
assert.Equal(t, defaultBitrate, encoder.bitrate)
_, err = NewEncoder(WithSampleRate(16000))
assert.ErrorIs(t, err, errInvalidSampleRate)
encoder, err = NewEncoder(WithChannels(2))
require.NoError(t, err)
assert.Equal(t, 2, encoder.channels)
}
func TestNewEncoderOptions(t *testing.T) {
encoder, err := NewEncoder(
WithSampleRate(48000),
WithChannels(1),
WithBitrate(64000),
WithComplexity(5),
)
require.NoError(t, err)
assert.Equal(t, 64000, encoder.bitrate)
assert.Equal(t, 5, encoder.complexity)
assert.Equal(t, 5, encoder.celtEncoder.Complexity())
_, err = NewEncoder(WithBitrate(1000))
assert.ErrorIs(t, err, errBitrateOutOfRange)
_, err = NewEncoder(WithComplexity(11))
assert.ErrorIs(t, err, errInvalidComplexity)
}
func TestEncodeFloat32RoundTrip(t *testing.T) {
encoder, err := NewEncoder()
require.NoError(t, err)
decoder, err := NewDecoderWithOutput(48000, 1)
require.NoError(t, err)
pcm := testEncoderSineFloat32()
packet := make([]byte, 256)
n, err := encoder.EncodeFloat32(pcm, packet)
require.NoError(t, err)
require.Positive(t, n)
assert.Equal(t, byte(celtOnlyFullband20msConfig<<3)|byte(frameCodeOneFrame), packet[0])
out := make([]float32, encoderTestFrameSampleCount)
bandwidth, isStereo, err := decoder.DecodeFloat32(packet[:n], out)
require.NoError(t, err)
assert.Equal(t, BandwidthFullband, bandwidth)
assert.False(t, isStereo)
assert.Greater(t, vectorEnergyFloat32(out), 1e-6)
// Output amplitude must stay in a sane range. Opus is perceptual so some
// overshoot above the input peak is expected; the decoder's post-filter
// can push peaks slightly above the input. A sample reaching ±2.5
// indicates a gain or scaling defect.
for i, sample := range out {
require.InDelta(t, 0, sample, 2.5, "decoded sample %d out of sane amplitude range", i)
}
}
func TestEncodeS16LERoundTrip(t *testing.T) {
encoder, err := NewEncoder()
require.NoError(t, err)
decoder, err := NewDecoderWithOutput(48000, 1)
require.NoError(t, err)
pcm := testEncoderSineS16LE()
packet := make([]byte, 256)
n, err := encoder.Encode(pcm, packet)
require.NoError(t, err)
require.Positive(t, n)
out := make([]float32, encoderTestFrameSampleCount)
_, _, err = decoder.DecodeFloat32(packet[:n], out)
require.NoError(t, err)
assert.Greater(t, vectorEnergyFloat32(out), 1e-6)
}
func TestEncodeFloat32StereoRoundTrip(t *testing.T) {
encoder, err := NewEncoder(WithChannels(2))
require.NoError(t, err)
decoder, err := NewDecoderWithOutput(48000, 2)
require.NoError(t, err)
pcm := testEncoderStereoSineFloat32()
packet := make([]byte, 256)
n, err := encoder.EncodeFloat32(pcm, packet)
require.NoError(t, err)
require.Positive(t, n)
assert.Equal(t, byte(celtOnlyFullband20msConfig<<3)|byte(frameCodeOneFrame)|(1<<2), packet[0])
out := make([]float32, encoderTestFrameSampleCount*2)
bandwidth, isStereo, err := decoder.DecodeFloat32(packet[:n], out)
require.NoError(t, err)
assert.Equal(t, BandwidthFullband, bandwidth)
assert.True(t, isStereo)
assert.Greater(t, vectorEnergyFloat32(out), 1e-6)
L := make([]float32, encoderTestFrameSampleCount)
R := make([]float32, encoderTestFrameSampleCount)
for i := range encoderTestFrameSampleCount {
L[i] = out[i*2]
R[i] = out[i*2+1]
}
L440 := freqEnergy(L, 440)
L660 := freqEnergy(L, 660)
R440 := freqEnergy(R, 440)
R660 := freqEnergy(R, 660)
assert.Greater(t, L440, L660*1.5, "L channel: 440 Hz should dominate over 660 Hz")
assert.Greater(t, R660, R440*1.5, "R channel: 660 Hz should dominate over 440 Hz")
}
func TestEncodeS16LEStereoRoundTrip(t *testing.T) {
encoder, err := NewEncoder(WithChannels(2))
require.NoError(t, err)
decoder, err := NewDecoderWithOutput(48000, 2)
require.NoError(t, err)
pcm := testEncoderStereoSineS16LE()
packet := make([]byte, 256)
n, err := encoder.Encode(pcm, packet)
require.NoError(t, err)
require.Positive(t, n)
out := make([]float32, encoderTestFrameSampleCount*2)
_, isStereo, err := decoder.DecodeFloat32(packet[:n], out)
require.NoError(t, err)
assert.True(t, isStereo)
assert.Greater(t, vectorEnergyFloat32(out), 1e-6)
}
func TestStereoMultiFramePersistence(t *testing.T) {
encoder, err := NewEncoder(WithChannels(2))
require.NoError(t, err)
decoder, err := NewDecoderWithOutput(48000, 2)
require.NoError(t, err)
pcm := testEncoderStereoSineFloat32()
packet := make([]byte, 256)
out := make([]float32, encoderTestFrameSampleCount*2)
const frames = 10
energies := make([]float64, frames)
for i := range frames {
n, encErr := encoder.EncodeFloat32(pcm, packet)
require.NoError(t, encErr, "frame %d encode failed", i)
require.Positive(t, n)
_, _, decErr := decoder.DecodeFloat32(packet[:n], out)
require.NoError(t, decErr, "frame %d decode failed", i)
energies[i] = vectorEnergyFloat32(out)
assert.Greater(t, energies[i], 1e-6, "frame %d should have non-zero energy", i)
}
for i := 1; i < frames; i++ {
ratio := energies[i] / energies[0]
assert.InDelta(t, 1.0, ratio, 0.75,
"frame %d energy ratio %.3f deviates too far from frame 0", i, ratio)
}
}
func TestEncodeRejectsInvalidS16LEInputLength(t *testing.T) {
encoder, err := NewEncoder()
require.NoError(t, err)
_, err = encoder.Encode(make([]byte, 3), make([]byte, 64))
assert.ErrorIs(t, err, errInvalidInputLength)
}
func TestEncodeFloat32RejectsInvalidFrameSize(t *testing.T) {
encoder, err := NewEncoder()
require.NoError(t, err)
_, err = encoder.EncodeFloat32(make([]float32, encoderTestFrameSampleCount-1), make([]byte, 64))
assert.ErrorIs(t, err, errInvalidFrameSize)
}
func TestEncodeRejectsSmallOutputBuffer(t *testing.T) {
encoder, err := NewEncoder()
require.NoError(t, err)
pcm := testEncoderSineFloat32()
packet := make([]byte, 8)
_, err = encoder.EncodeFloat32(pcm, packet)
assert.ErrorIs(t, err, errOutBufferTooSmall)
}
func TestSetBitrate(t *testing.T) {
encoder, err := NewEncoder()
require.NoError(t, err)
require.NoError(t, encoder.SetBitrate(32000))
assert.Equal(t, 32000, encoder.bitrate)
assert.ErrorIs(t, encoder.SetBitrate(1000), errBitrateOutOfRange)
assert.ErrorIs(t, encoder.SetBitrate(999999), errBitrateOutOfRange)
}
func TestSetComplexity(t *testing.T) {
encoder, err := NewEncoder()
require.NoError(t, err)
require.NoError(t, encoder.SetComplexity(10))
assert.Equal(t, 10, encoder.complexity)
assert.Equal(t, 10, encoder.Complexity())
assert.Equal(t, 10, encoder.celtEncoder.Complexity())
assert.ErrorIs(t, encoder.SetComplexity(-1), errInvalidComplexity)
assert.ErrorIs(t, encoder.SetComplexity(11), errInvalidComplexity)
}
func TestComplexityRoundTrip(t *testing.T) {
// Verify that encoding at complexity 0 and 10 both produce valid packets.
for _, complexity := range []int{0, 10} {
enc, err := NewEncoder(
WithComplexity(complexity),
WithBitrate(64000),
)
require.NoError(t, err)
dec, err := NewDecoderWithOutput(48000, 1)
require.NoError(t, err)
pcm := testEncoderSineFloat32()
packet := make([]byte, 256)
n, err := enc.EncodeFloat32(pcm, packet)
require.NoError(t, err)
require.Greater(t, n, 0)
out := make([]float32, encoderTestFrameSampleCount)
_, _, err = dec.DecodeFloat32(packet[:n], out)
require.NoError(t, err)
}
}
func TestNewEncoderDefaultApplication(t *testing.T) {
encoder, err := NewEncoder()
require.NoError(t, err)
assert.Equal(t, ApplicationAudio, encoder.Application())
assert.False(t, encoder.VBR())
assert.True(t, encoder.ConstrainedVBR())
assert.Equal(t, 0, encoder.LossRate())
}
func TestWithApplication(t *testing.T) {
encoder, err := NewEncoder(WithApplication(ApplicationVoIP))
require.NoError(t, err)
assert.Equal(t, ApplicationVoIP, encoder.Application())
encoder, err = NewEncoder(WithApplication(ApplicationRestrictedLowDelay))
require.NoError(t, err)
assert.Equal(t, ApplicationRestrictedLowDelay, encoder.Application())
_, err = NewEncoder(WithApplication(Application(9999)))
assert.ErrorIs(t, err, errInvalidApplication)
}
func TestSetApplication(t *testing.T) {
encoder, err := NewEncoder()
require.NoError(t, err)
require.NoError(t, encoder.SetApplication(ApplicationVoIP))
assert.Equal(t, ApplicationVoIP, encoder.Application())
assert.ErrorIs(t, encoder.SetApplication(Application(0)), errInvalidApplication)
}
func TestWithVBR(t *testing.T) {
encoder, err := NewEncoder(WithVBR(true))
require.NoError(t, err)
assert.True(t, encoder.VBR())
encoder, err = NewEncoder(WithVBR(false))
require.NoError(t, err)
assert.False(t, encoder.VBR())
}
func TestSetVBR(t *testing.T) {
encoder, err := NewEncoder()
require.NoError(t, err)
require.False(t, encoder.VBR())
encoder.SetVBR(true)
assert.True(t, encoder.VBR())
encoder.SetVBR(false)
assert.False(t, encoder.VBR())
}
func TestWithConstrainedVBR(t *testing.T) {
encoder, err := NewEncoder(WithConstrainedVBR(false))
require.NoError(t, err)
assert.False(t, encoder.ConstrainedVBR())
}
func TestSetConstrainedVBR(t *testing.T) {
encoder, err := NewEncoder()
require.NoError(t, err)
require.True(t, encoder.ConstrainedVBR())
encoder.SetConstrainedVBR(false)
assert.False(t, encoder.ConstrainedVBR())
encoder.SetConstrainedVBR(true)
assert.True(t, encoder.ConstrainedVBR())
}
func TestWithBandwidth(t *testing.T) {
enc, err := NewEncoder(WithBandwidth(BandwidthWideband))
require.NoError(t, err)
assert.Equal(t, BandwidthWideband, enc.Bandwidth())
_, err = NewEncoder(WithBandwidth(BandwidthAuto))
assert.ErrorIs(t, err, errInvalidBandwidth)
_, err = NewEncoder(WithBandwidth(BandwidthMediumband))
assert.ErrorIs(t, err, errInvalidBandwidth)
_, err = NewEncoder(WithBandwidth(Bandwidth(255)))
assert.ErrorIs(t, err, errInvalidBandwidth)
}
func TestSetBandwidth(t *testing.T) {
enc, err := NewEncoder()
require.NoError(t, err)
assert.Equal(t, BandwidthAuto, enc.Bandwidth())
require.NoError(t, enc.SetBandwidth(BandwidthWideband))
assert.Equal(t, BandwidthWideband, enc.Bandwidth())
assert.ErrorIs(t, enc.SetBandwidth(BandwidthMediumband), errInvalidBandwidth)
}
func TestBandwidthRoundTrip(t *testing.T) {
for _, bw := range []Bandwidth{
BandwidthNarrowband, BandwidthWideband,
BandwidthSuperwideband, BandwidthFullband,
} {
enc, err := NewEncoder(
WithBandwidth(bw),
WithBitrate(24000),
)
require.NoError(t, err)
dec, err := NewDecoderWithOutput(48000, 1)
require.NoError(t, err)
pcm := testEncoderSineFloat32()
packet := make([]byte, 256)
n, err := enc.EncodeFloat32(pcm, packet)
require.NoError(t, err)
require.Greater(t, n, 0)
out := make([]float32, encoderTestFrameSampleCount)
decBandwidth, _, err := dec.DecodeFloat32(packet[:n], out)
require.NoError(t, err)
assert.Equal(t, bw, decBandwidth, "decoded bandwidth should match encoded bandwidth")
}
}
func TestBandwidthChangesTOC(t *testing.T) {
for _, tc := range []struct {
bw Bandwidth
config byte
}{
{BandwidthNarrowband, 19},
{BandwidthWideband, 23},
{BandwidthSuperwideband, 27},
{BandwidthFullband, 31},
} {
enc, err := NewEncoder(WithBandwidth(tc.bw))
require.NoError(t, err)
pcm := testEncoderSineFloat32()
packet := make([]byte, 256)
n, err := enc.EncodeFloat32(pcm, packet)
require.NoError(t, err)
require.Greater(t, n, 0)
expectedTOC := tc.config<<3 | byte(frameCodeOneFrame)
assert.Equal(t, expectedTOC, packet[0], "TOC byte for bandwidth %v", tc.bw)
}
}
func TestWithMaxBandwidth(t *testing.T) {
enc, err := NewEncoder(WithMaxBandwidth(BandwidthWideband))
require.NoError(t, err)
assert.Equal(t, BandwidthWideband, enc.MaxBandwidth())
_, err = NewEncoder(WithMaxBandwidth(BandwidthAuto))
assert.ErrorIs(t, err, errInvalidBandwidth)
_, err = NewEncoder(WithMaxBandwidth(BandwidthMediumband))
assert.ErrorIs(t, err, errInvalidBandwidth)
_, err = NewEncoder(WithMaxBandwidth(Bandwidth(255)))
assert.ErrorIs(t, err, errInvalidBandwidth)
}
func TestAutoSelectBandwidth(t *testing.T) {
for _, tc := range []struct {
name string
bitrate int
maxBW Bandwidth
expected Bandwidth
}{
// Boundaries are in equivRate() space (CBR + default complexity 5
// dock the raw bitrate by ~13%), not raw bitrate — see equivRate.
{"NB at low bitrate", 6000, BandwidthFullband, BandwidthNarrowband},
{"NB at threshold", 10334, BandwidthFullband, BandwidthNarrowband}, // equiv=8999
{"WB just above threshold", 10335, BandwidthFullband, BandwidthWideband}, // equiv=9000
{"WB at 12kbps", 12000, BandwidthFullband, BandwidthWideband},
{"WB at threshold", 15501, BandwidthFullband, BandwidthWideband}, // equiv=13499
{"SWB just above threshold", 15502, BandwidthFullband, BandwidthSuperwideband}, // equiv=13500
{"SWB at threshold", 16075, BandwidthFullband, BandwidthSuperwideband}, // equiv=13999
{"FB just above threshold", 16076, BandwidthFullband, BandwidthFullband}, // equiv=14000
{"FB at 24kbps", 24000, BandwidthFullband, BandwidthFullband},
{"clamped by maxBandwidth", 24000, BandwidthWideband, BandwidthWideband},
{"clamped to NB", 24000, BandwidthNarrowband, BandwidthNarrowband},
} {
t.Run(tc.name, func(t *testing.T) {
enc, err := NewEncoder(
WithBitrate(tc.bitrate),
WithMaxBandwidth(tc.maxBW),
)
require.NoError(t, err)
assert.Equal(t, tc.expected, enc.autoSelectBandwidth())
})
}
}
func TestEquivRate(t *testing.T) {
enc, err := NewEncoder(WithBitrate(13500))
require.NoError(t, err)
// CBR (default) docks ~8%, complexity 5 (default) docks another ~5%.
assert.Equal(t, 11756, enc.equivRate())
enc.SetVBR(true)
assert.Equal(t, 12825, enc.equivRate(), "VBR should skip the CBR penalty")
enc.SetVBR(false)
require.NoError(t, enc.SetComplexity(0))
assert.Equal(t, 11137, enc.equivRate(), "complexity 0 should dock closer to 10%")
}
func TestAutoBandwidthDefault(t *testing.T) {
enc, err := NewEncoder()
require.NoError(t, err)
assert.Equal(t, BandwidthAuto, enc.Bandwidth())
assert.Equal(t, BandwidthFullband, enc.MaxBandwidth())
// At default 24 kbps, auto should select fullband.
assert.Equal(t, BandwidthFullband, enc.autoSelectBandwidth())
}
func TestAutoBandwidthExplicitOverrides(t *testing.T) {
enc, err := NewEncoder(
WithBandwidth(BandwidthWideband),
WithMaxBandwidth(BandwidthFullband),
)
require.NoError(t, err)
// Explicit bandwidth should be returned regardless of maxBandwidth.
assert.Equal(t, BandwidthWideband, enc.autoSelectBandwidth())
}
func TestAutoBandwidthTOC(t *testing.T) {
// At 6000 bps, auto should select NB → config 19.
enc, err := NewEncoder(WithBitrate(6000))
require.NoError(t, err)
pcm := testEncoderSineFloat32()
packet := make([]byte, 256)
n, err := enc.EncodeFloat32(pcm, packet)
require.NoError(t, err)
require.Greater(t, n, 0)
expectedTOC := byte(19<<3) | byte(frameCodeOneFrame)
assert.Equal(t, expectedTOC, packet[0], "auto NB TOC")
}
func TestAutoBandwidthRoundTrip(t *testing.T) {
for _, tc := range []struct {
name string
bitrate int
maxBW Bandwidth
wantBW Bandwidth
}{
{"NB round-trip", 6000, BandwidthFullband, BandwidthNarrowband},
{"WB round-trip", 12000, BandwidthFullband, BandwidthWideband},
{"FB round-trip", 24000, BandwidthFullband, BandwidthFullband},
} {
t.Run(tc.name, func(t *testing.T) {
enc, err := NewEncoder(
WithBitrate(tc.bitrate),
WithMaxBandwidth(tc.maxBW),
)
require.NoError(t, err)
dec, err := NewDecoderWithOutput(48000, 1)
require.NoError(t, err)
pcm := testEncoderSineFloat32()
packet := make([]byte, 256)
n, err := enc.EncodeFloat32(pcm, packet)
require.NoError(t, err)
require.Greater(t, n, 0)
out := make([]float32, encoderTestFrameSampleCount)
decBandwidth, _, err := dec.DecodeFloat32(packet[:n], out)
require.NoError(t, err)
assert.Equal(t, tc.wantBW, decBandwidth, "decoded bandwidth should match auto-selected bandwidth")
})
}
}
func TestSetMaxBandwidth(t *testing.T) {
enc, err := NewEncoder()
require.NoError(t, err)
assert.Equal(t, BandwidthFullband, enc.MaxBandwidth())
require.NoError(t, enc.SetMaxBandwidth(BandwidthWideband))
assert.Equal(t, BandwidthWideband, enc.MaxBandwidth())
assert.ErrorIs(t, enc.SetMaxBandwidth(BandwidthAuto), errInvalidBandwidth)
assert.ErrorIs(t, enc.SetMaxBandwidth(BandwidthMediumband), errInvalidBandwidth)
}
func TestSetLossRate(t *testing.T) {
encoder, err := NewEncoder()
require.NoError(t, err)
require.NoError(t, encoder.SetLossRate(50))
assert.Equal(t, 50, encoder.LossRate())
assert.ErrorIs(t, encoder.SetLossRate(-1), errInvalidLossRate)
assert.ErrorIs(t, encoder.SetLossRate(101), errInvalidLossRate)
}
func TestVBRPacketRoundTrip(t *testing.T) {
encoder, err := NewEncoder(WithVBR(true), WithConstrainedVBR(false))
require.NoError(t, err)
pcm := testEncoderSineFloat32()
packet := make([]byte, 256)
n, err := encoder.EncodeFloat32(pcm, packet)
require.NoError(t, err)
require.Greater(t, n, 1)
// TOC byte is unchanged by VBR for single-frame (c=0) packets.
// The VBR bit lives in the frame count byte, which is absent for c=0.
assert.Equal(t, byte(celtOnlyFullband20msConfig<<3)|byte(frameCodeOneFrame), packet[0])
decoder, err := NewDecoderWithOutput(48000, 1)
require.NoError(t, err)
out := make([]float32, encoderTestFrameSampleCount)
_, _, err = decoder.DecodeFloat32(packet[:n], out)
require.NoError(t, err)
assert.Greater(t, vectorEnergyFloat32(out), 1e-6)
}
func TestConstrainedVBRPacketRoundTrip(t *testing.T) {
encoder, err := NewEncoder(WithVBR(true), WithConstrainedVBR(true))
require.NoError(t, err)
pcm := testEncoderSineFloat32()
packet := make([]byte, 256)
n, err := encoder.EncodeFloat32(pcm, packet)
require.NoError(t, err)
require.Greater(t, n, 1)
decoder, err := NewDecoderWithOutput(48000, 1)
require.NoError(t, err)
out := make([]float32, encoderTestFrameSampleCount)
_, _, err = decoder.DecodeFloat32(packet[:n], out)
require.NoError(t, err)
assert.Greater(t, vectorEnergyFloat32(out), 1e-6)
}
func TestVBRProducesVaryingPacketSizes(t *testing.T) {
enc, err := NewEncoder(WithVBR(true), WithConstrainedVBR(false))
require.NoError(t, err)
sizes := make(map[int]bool)
for i := range 20 {
pcm := make([]float32, encoderTestFrameSampleCount)
if i%2 == 0 {
for j := range pcm {
pcm[j] = float32(j%100) / 100
}
} else {
for j := range pcm {
pcm[j] = 0.0001
}
}
packet := make([]byte, 256)
n, err := enc.EncodeFloat32(pcm, packet)
require.NoError(t, err)
sizes[n] = true
}
assert.Greater(t, len(sizes), 1, "VBR should produce varying packet sizes")
}
func TestVBRPacketRoundTripMultiFrame(t *testing.T) {
enc, err := NewEncoder(WithVBR(true), WithConstrainedVBR(false))
require.NoError(t, err)
dec, err := NewDecoderWithOutput(48000, 1)
require.NoError(t, err)
for i := range 10 {
pcm := make([]float32, encoderTestFrameSampleCount)
for j := range pcm {
pcm[j] = float32(math.Sin(2*math.Pi*440*float64(j)/48000)) * float32(i%3) * 0.3
}
packet := make([]byte, 256)
n, err := enc.EncodeFloat32(pcm, packet)
require.NoError(t, err)
out := make([]float32, encoderTestFrameSampleCount)
_, _, err = dec.DecodeFloat32(packet[:n], out)
require.NoError(t, err)
assert.Greater(t, vectorEnergyFloat32(out), 1e-6)
}
}
func TestCVBRBoundsVariation(t *testing.T) {
enc, err := NewEncoder(WithVBR(true), WithConstrainedVBR(true))
require.NoError(t, err)
var minSize, maxSize int
for i := range 30 {
pcm := make([]float32, encoderTestFrameSampleCount)
for j := range pcm {
switch i % 3 {
case 0:
pcm[j] = float32(j%50) / 50
case 1:
pcm[j] = 0.0001
case 2:
pcm[j] = float32(j%200-100) / 200
}
}
packet := make([]byte, 256)
n, err := enc.EncodeFloat32(pcm, packet)
require.NoError(t, err)
if i == 0 || n < minSize {
minSize = n
}
if i == 0 || n > maxSize {
maxSize = n
}
}
assert.LessOrEqual(t, maxSize, minSize*3,
"CVBR should bound packet size variation")
}
func TestCBRUnchanged(t *testing.T) {
enc, err := NewEncoder()
require.NoError(t, err)
sizes := make(map[int]bool)
for i := range 10 {
pcm := make([]float32, encoderTestFrameSampleCount)
for j := range pcm {
pcm[j] = float32(i%3-1) * 0.1
}
packet := make([]byte, 256)
n, err := enc.EncodeFloat32(pcm, packet)
require.NoError(t, err)
sizes[n] = true
}
assert.Equal(t, 1, len(sizes), "CBR should produce constant packet sizes")
}
func TestVBRWithStereo(t *testing.T) {
enc, err := NewEncoder(WithChannels(2), WithVBR(true))
require.NoError(t, err)
dec, err := NewDecoderWithOutput(48000, 2)
require.NoError(t, err)
pcm := testEncoderStereoSineFloat32()
packet := make([]byte, 256)
n, err := enc.EncodeFloat32(pcm, packet)
require.NoError(t, err)
out := make([]float32, encoderTestFrameSampleCount*2)
_, _, err = dec.DecodeFloat32(packet[:n], out)
require.NoError(t, err)
assert.Greater(t, vectorEnergyFloat32(out), 1e-6)
}
func TestVBRDefaultIsCBR(t *testing.T) {
enc, err := NewEncoder()
require.NoError(t, err)
assert.False(t, enc.VBR(), "default encoder should be CBR")
}
func TestApplicationRoundTrip(t *testing.T) {
encoder, err := NewEncoder(
WithApplication(ApplicationVoIP),
WithVBR(true),
)
require.NoError(t, err)
assert.Equal(t, ApplicationVoIP, encoder.Application())
assert.True(t, encoder.VBR())
decoder, err := NewDecoderWithOutput(48000, 1)
require.NoError(t, err)
pcm := testEncoderSineFloat32()
packet := make([]byte, 256)
n, err := encoder.EncodeFloat32(pcm, packet)
require.NoError(t, err)
out := make([]float32, encoderTestFrameSampleCount)
_, _, err = decoder.DecodeFloat32(packet[:n], out)
require.NoError(t, err)
assert.Greater(t, vectorEnergyFloat32(out), 1e-6)
}
func TestLossRateGetterSetter(t *testing.T) {
encoder, err := NewEncoder()
require.NoError(t, err)
require.NoError(t, encoder.SetLossRate(0))
assert.Equal(t, 0, encoder.LossRate())
require.NoError(t, encoder.SetLossRate(100))
assert.Equal(t, 100, encoder.LossRate())
require.NoError(t, encoder.SetLossRate(25))
assert.Equal(t, 25, encoder.LossRate())
}
func testEncoderSineFloat32() []float32 {
pcm := make([]float32, encoderTestFrameSampleCount)
for i := range pcm {
pcm[i] = float32(math.Sin(2 * math.Pi * 440 * float64(i) / 48000))
}
return pcm
}
func testEncoderStereoSineFloat32() []float32 {
pcm := make([]float32, encoderTestFrameSampleCount*2)
for i := range encoderTestFrameSampleCount {
left := float32(math.Sin(2 * math.Pi * 440 * float64(i) / 48000))
right := float32(math.Sin(2 * math.Pi * 660 * float64(i) / 48000))
pcm[i*2] = left
pcm[i*2+1] = right
}
return pcm
}
func testEncoderSineS16LE() []byte {
pcm := make([]byte, encoderTestFrameSampleCount*2)
for i := range encoderTestFrameSampleCount {
// math.Round breaks gosec's constant-folding so the int16() conversion
// is analyzed against a runtime float, not a constant expression.
sample := int16(math.Round(math.Sin(2*math.Pi*440*float64(i)/48000) * 16000))
binary.LittleEndian.PutUint16(pcm[i*2:], uint16(sample)) //nolint:gosec // G115: little-endian s16 round-trip.
}
return pcm
}
func testEncoderStereoSineS16LE() []byte {
pcm := make([]byte, encoderTestFrameSampleCount*4) // 2 channels × 2 bytes each
for i := range encoderTestFrameSampleCount {
left := int16(math.Round(math.Sin(2*math.Pi*440*float64(i)/48000) * 16000))
right := int16(math.Round(math.Sin(2*math.Pi*660*float64(i)/48000) * 16000))
binary.LittleEndian.PutUint16(pcm[i*4:], uint16(left)) //nolint:gosec // G115
binary.LittleEndian.PutUint16(pcm[i*4+2:], uint16(right)) //nolint:gosec // G115
}
return pcm
}
func vectorEnergyFloat32(x []float32) float64 {
var e float64
for _, v := range x {
e += float64(v * v)
}
return math.Sqrt(e)
}
// freqEnergy returns the DFT magnitude at freq Hz over a 48 kHz signal.
// It is phase-invariant so it survives the CELT analysis/synthesis delay.
func freqEnergy(samples []float32, freq float64) float64 {
var re, im float64
for i, s := range samples {
angle := 2 * math.Pi * freq * float64(i) / 48000
re += float64(s) * math.Cos(angle)
im += float64(s) * math.Sin(angle)
}
return math.Sqrt(re*re+im*im) / float64(len(samples))
}