-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdecoder_test.go
More file actions
1643 lines (1429 loc) · 49.1 KB
/
decoder_test.go
File metadata and controls
1643 lines (1429 loc) · 49.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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gopus
import (
"bytes"
"fmt"
"math"
"slices"
"strings"
"testing"
internalenc "github.com/thesyncim/gopus/encoder"
internaldred "github.com/thesyncim/gopus/internal/dred"
"github.com/thesyncim/gopus/rangecoding"
"github.com/thesyncim/gopus/types"
)
func makeExperimentalDREDPayloadBodyForTest(t *testing.T, dredFrameOffset, dredOffset int) []byte {
t.Helper()
rawOffset := 16 - dredOffset + dredFrameOffset
if rawOffset < 0 || rawOffset >= 32 {
t.Fatalf("rawOffset=%d out of range for dredOffset=%d frameOffset=%d", rawOffset, dredOffset, dredFrameOffset)
}
var enc rangecoding.Encoder
enc.Init(make([]byte, internaldred.MinBytes))
enc.EncodeUniform(6, 16)
enc.EncodeUniform(3, 8)
enc.EncodeUniform(0, 2)
enc.EncodeUniform(uint32(rawOffset), 32)
enc.Shrink(internaldred.MinBytes)
return enc.Done()
}
func makeValidDREDDecoderTestDNNBlob() []byte {
blob := makeValidDecoderTestDNNBlob()
return appendTestBlobRecord(blob, "dec_dense1_bias", 0, 64*4)
}
func makeValidCELTPacketForDREDTest(t *testing.T) []byte {
t.Helper()
enc := internalenc.NewEncoder(48000, 2)
enc.SetMode(internalenc.ModeCELT)
enc.SetBandwidth(types.BandwidthFullband)
enc.SetBitrate(256000)
pcm := make([]float64, 960*2)
for i := 0; i < 960; i++ {
phase := 2 * math.Pi * 997 * float64(i) / 48000.0
pcm[2*i] = 0.45 * math.Sin(phase)
pcm[2*i+1] = 0.35 * math.Sin(phase+0.37)
}
packet, err := enc.Encode(pcm, 960)
if err != nil {
t.Fatalf("Encode(CELT): %v", err)
}
if len(packet) == 0 {
t.Fatal("Encode(CELT) returned empty packet")
}
return packet
}
func buildSingleFramePacketWithExtensionsForDREDTest(t *testing.T, packet []byte, extensions []packetExtensionData) []byte {
t.Helper()
if len(packet) < 2 {
t.Fatal("packet too short for extension test")
}
dst := make([]byte, len(packet)+16)
n, err := buildPacketWithOptions(packet[0]&0xFC, [][]byte{packet[1:]}, dst, 0, false, extensions, false)
if err != nil {
t.Fatalf("buildPacketWithOptions: %v", err)
}
return dst[:n]
}
func TestNewDecoder_ValidParams(t *testing.T) {
tests := []struct {
name string
sampleRate int
channels int
}{
{"48kHz_mono", 48000, 1},
{"48kHz_stereo", 48000, 2},
{"24kHz_mono", 24000, 1},
{"24kHz_stereo", 24000, 2},
{"16kHz_mono", 16000, 1},
{"16kHz_stereo", 16000, 2},
{"12kHz_mono", 12000, 1},
{"12kHz_stereo", 12000, 2},
{"8kHz_mono", 8000, 1},
{"8kHz_stereo", 8000, 2},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
dec, err := NewDecoder(DefaultDecoderConfig(tt.sampleRate, tt.channels))
if err != nil {
t.Fatalf("NewDecoder(%d, %d) unexpected error: %v", tt.sampleRate, tt.channels, err)
}
if dec == nil {
t.Fatal("NewDecoder returned nil decoder")
}
if dec.SampleRate() != tt.sampleRate {
t.Errorf("SampleRate() = %d, want %d", dec.SampleRate(), tt.sampleRate)
}
if dec.Channels() != tt.channels {
t.Errorf("Channels() = %d, want %d", dec.Channels(), tt.channels)
}
})
}
}
func TestNewDecoder_InvalidSampleRate(t *testing.T) {
invalidRates := []int{0, 1000, 7999, 8001, 44100, 96000, -1}
for _, rate := range invalidRates {
t.Run(fmt.Sprintf("rate_%d", rate), func(t *testing.T) {
dec, err := NewDecoder(DefaultDecoderConfig(rate, 1))
if err != ErrInvalidSampleRate {
t.Errorf("NewDecoder(%d, 1) error = %v, want ErrInvalidSampleRate", rate, err)
}
if dec != nil {
t.Error("NewDecoder returned non-nil decoder on error")
}
})
}
}
func TestNewDecoder_InvalidChannels(t *testing.T) {
invalidChannels := []int{0, -1, 3, 4, 100}
for _, ch := range invalidChannels {
t.Run(fmt.Sprintf("channels_%d", ch), func(t *testing.T) {
dec, err := NewDecoder(DefaultDecoderConfig(48000, ch))
if err != ErrInvalidChannels {
t.Errorf("NewDecoder(48000, %d) error = %v, want ErrInvalidChannels", ch, err)
}
if dec != nil {
t.Error("NewDecoder returned non-nil decoder on error")
}
})
}
}
func TestNewDecoder_DefaultMaxPacketLimits(t *testing.T) {
dec, err := NewDecoder(DecoderConfig{
SampleRate: 48000,
Channels: 2,
})
if err != nil {
t.Fatalf("NewDecoder() unexpected error: %v", err)
}
if dec.maxPacketSamples != defaultMaxPacketSamples {
t.Fatalf("maxPacketSamples=%d want %d", dec.maxPacketSamples, defaultMaxPacketSamples)
}
if dec.maxPacketBytes != defaultMaxPacketBytes {
t.Fatalf("maxPacketBytes=%d want %d", dec.maxPacketBytes, defaultMaxPacketBytes)
}
}
func TestDecoderCachesDREDPayloadWhenDREDModelLoaded(t *testing.T) {
base := makeValidCELTPacketForDREDTest(t)
body := makeExperimentalDREDPayloadBodyForTest(t, 0, 4)
extended := buildSingleFramePacketWithExtensionsForDREDTest(t, base, []packetExtensionData{
{ID: internaldred.ExtensionID, Frame: 0, Data: append([]byte{'D', internaldred.ExperimentalVersion}, body...)},
})
dec, err := NewDecoder(DefaultDecoderConfig(48000, 2))
if err != nil {
t.Fatalf("NewDecoder error: %v", err)
}
if err := dec.SetDNNBlob(makeValidDREDDecoderTestDNNBlob()); err != nil {
t.Fatalf("SetDNNBlob error: %v", err)
}
pcm := make([]float32, 960*2)
n, err := dec.Decode(extended, pcm)
if err != nil {
t.Fatalf("Decode error: %v", err)
}
if n == 0 {
t.Fatal("Decode returned zero samples")
}
if dec.dredCache.Len != len(body) {
t.Fatalf("dredCache.Len=%d want %d", dec.dredCache.Len, len(body))
}
if dec.dredCache.Parsed.Header.DredOffset != 4 {
t.Fatalf("dredCache.Parsed.Header.DredOffset=%d want 4", dec.dredCache.Parsed.Header.DredOffset)
}
if dec.dredCache.Parsed.Header.DredFrameOffset != 0 || dec.dredCache.Parsed.Header.Q0 != 6 || dec.dredCache.Parsed.Header.DQ != 3 || dec.dredCache.Parsed.Header.QMax != 15 {
t.Fatalf("dredCache.Parsed.Header=(frame=%d q0=%d dq=%d qmax=%d) want (0,6,3,15)", dec.dredCache.Parsed.Header.DredFrameOffset, dec.dredCache.Parsed.Header.Q0, dec.dredCache.Parsed.Header.DQ, dec.dredCache.Parsed.Header.QMax)
}
if !bytes.Equal(dec.dredData[:dec.dredCache.Len], body) {
t.Fatalf("cached dred payload=%x want %x", dec.dredData[:dec.dredCache.Len], body)
}
result := dec.cachedDREDResult(960)
if result.Availability.FeatureFrames != 4 || result.Availability.MaxLatents != 1 || result.Availability.OffsetSamples != 480 || result.Availability.EndSamples != 0 || result.Availability.AvailableSamples != 1440 {
t.Fatalf("cachedDREDResult=%+v want availability {FeatureFrames:4 MaxLatents:1 OffsetSamples:480 EndSamples:0 AvailableSamples:1440}", result)
}
if got := dec.cachedDREDMaxAvailableSamples(960); got != 1440 {
t.Fatalf("cachedDREDMaxAvailableSamples=%d want 1440", got)
}
quant := make([]int, 6)
if n := dec.cachedDREDResult(10080).FillQuantizerLevels(quant); n != len(quant) {
t.Fatalf("cachedDREDResult.FillQuantizerLevels count=%d want %d", n, len(quant))
}
if want := []int{6, 6, 7, 7, 7, 7}; !slices.Equal(quant, want) {
t.Fatalf("cachedDREDResult.FillQuantizerLevels=%v want %v", quant, want)
}
window := dec.cachedDREDFeatureWindow(960, 960, 960, 0)
if window.FeatureOffsetBase != 1 || window.RecoverableFeatureFrames != 2 || window.MissingPositiveFrames != 0 {
t.Fatalf("cachedDREDFeatureWindow=%+v want base=1 recoverable=2 missing=0", window)
}
dec.Reset()
if dec.dredCache != (internaldred.Cache{}) {
t.Fatalf("Reset left DRED cache=%+v want zero state", dec.dredCache)
}
if got := dec.cachedDREDMaxAvailableSamples(960); got != 0 {
t.Fatalf("cachedDREDMaxAvailableSamples after Reset=%d want 0", got)
}
}
func TestDecoderCachesDREDSampleTimingForLaterFrame(t *testing.T) {
base := makeValidCELTPacketForDREDTest(t)
if len(base) < 2 {
t.Fatal("base packet too short")
}
body := makeExperimentalDREDPayloadBodyForTest(t, 8, -4)
packet := make([]byte, len(base)*2+16)
n, err := buildPacketWithOptions(base[0]&0xFC, [][]byte{base[1:], base[1:]}, packet, 0, false, []packetExtensionData{
{ID: internaldred.ExtensionID, Frame: 1, Data: append([]byte{'D', internaldred.ExperimentalVersion}, body...)},
}, false)
if err != nil {
t.Fatalf("buildPacketWithOptions error: %v", err)
}
dec, err := NewDecoder(DefaultDecoderConfig(48000, 2))
if err != nil {
t.Fatalf("NewDecoder error: %v", err)
}
if err := dec.SetDNNBlob(makeValidDREDDecoderTestDNNBlob()); err != nil {
t.Fatalf("SetDNNBlob error: %v", err)
}
pcm := make([]float32, 1920*2)
got, err := dec.Decode(packet[:n], pcm)
if err != nil {
t.Fatalf("Decode error: %v", err)
}
if got != 1920 {
t.Fatalf("Decode samples=%d want 1920", got)
}
if dec.dredCache.Parsed.Header.DredOffset != -4 {
t.Fatalf("dredCache.Parsed.Header.DredOffset=%d want -4", dec.dredCache.Parsed.Header.DredOffset)
}
if dec.dredCache.Parsed.Header.DredFrameOffset != 8 {
t.Fatalf("dredCache.Parsed.Header.DredFrameOffset=%d want 8", dec.dredCache.Parsed.Header.DredFrameOffset)
}
if dec.dredCache.Parsed.Header.QMax != 15 {
t.Fatalf("dredCache.Parsed.Header.QMax=%d want 15", dec.dredCache.Parsed.Header.QMax)
}
result := dec.cachedDREDResult(960)
if result.Availability.FeatureFrames != 4 || result.Availability.MaxLatents != 1 || result.Availability.OffsetSamples != -480 || result.Availability.EndSamples != 480 || result.Availability.AvailableSamples != 2400 {
t.Fatalf("cachedDREDResult=%+v want availability {FeatureFrames:4 MaxLatents:1 OffsetSamples:-480 EndSamples:480 AvailableSamples:2400}", result)
}
window := dec.cachedDREDFeatureWindow(960, 3840, 960, 0)
if window.FeatureOffsetBase != 5 || window.RecoverableFeatureFrames != 0 || window.MissingPositiveFrames != 2 {
t.Fatalf("cachedDREDFeatureWindow=%+v want base=5 recoverable=0 missing=2", window)
}
if got := dec.cachedDREDMaxAvailableSamples(960); got != 2400 {
t.Fatalf("cachedDREDMaxAvailableSamples=%d want 2400", got)
}
}
func TestDecoderLeavesDREDPayloadDormantWithoutDREDModel(t *testing.T) {
base := makeValidCELTPacketForDREDTest(t)
body := makeExperimentalDREDPayloadBodyForTest(t, 0, 4)
extended := buildSingleFramePacketWithExtensionsForDREDTest(t, base, []packetExtensionData{
{ID: internaldred.ExtensionID, Frame: 0, Data: append([]byte{'D', internaldred.ExperimentalVersion}, body...)},
})
dec, err := NewDecoder(DefaultDecoderConfig(48000, 2))
if err != nil {
t.Fatalf("NewDecoder error: %v", err)
}
if err := dec.SetDNNBlob(makeValidDecoderTestDNNBlob()); err != nil {
t.Fatalf("SetDNNBlob error: %v", err)
}
pcm := make([]float32, 960*2)
n, err := dec.Decode(extended, pcm)
if err != nil {
t.Fatalf("Decode error: %v", err)
}
if n == 0 {
t.Fatal("Decode returned zero samples")
}
if dec.dredCache != (internaldred.Cache{}) {
t.Fatalf("decoder cached dormant DRED cache=%+v want zero state", dec.dredCache)
}
if got := dec.cachedDREDMaxAvailableSamples(960); got != 0 {
t.Fatalf("cachedDREDMaxAvailableSamples without model=%d want 0", got)
}
}
func TestDecoderLeavesDREDPayloadDormantWhenIgnoringExtensions(t *testing.T) {
base := makeValidCELTPacketForDREDTest(t)
body := makeExperimentalDREDPayloadBodyForTest(t, 0, 4)
extended := buildSingleFramePacketWithExtensionsForDREDTest(t, base, []packetExtensionData{
{ID: internaldred.ExtensionID, Frame: 0, Data: append([]byte{'D', internaldred.ExperimentalVersion}, body...)},
})
dec, err := NewDecoder(DefaultDecoderConfig(48000, 2))
if err != nil {
t.Fatalf("NewDecoder error: %v", err)
}
if err := dec.SetDNNBlob(makeValidDREDDecoderTestDNNBlob()); err != nil {
t.Fatalf("SetDNNBlob error: %v", err)
}
dec.SetIgnoreExtensions(true)
pcm := make([]float32, 960*2)
n, err := dec.Decode(extended, pcm)
if err != nil {
t.Fatalf("Decode error: %v", err)
}
if n == 0 {
t.Fatal("Decode returned zero samples")
}
if dec.dredCache != (internaldred.Cache{}) {
t.Fatalf("decoder cached ignored DRED cache=%+v want zero state", dec.dredCache)
}
if got := dec.cachedDREDMaxAvailableSamples(960); got != 0 {
t.Fatalf("cachedDREDMaxAvailableSamples while ignoring=%d want 0", got)
}
}
func TestDecoderClearsDREDPayloadWhenDowngradingBlobOrIgnoringExtensions(t *testing.T) {
base := makeValidCELTPacketForDREDTest(t)
body := makeExperimentalDREDPayloadBodyForTest(t, 0, 4)
extended := buildSingleFramePacketWithExtensionsForDREDTest(t, base, []packetExtensionData{
{ID: internaldred.ExtensionID, Frame: 0, Data: append([]byte{'D', internaldred.ExperimentalVersion}, body...)},
})
dec, err := NewDecoder(DefaultDecoderConfig(48000, 2))
if err != nil {
t.Fatalf("NewDecoder error: %v", err)
}
if err := dec.SetDNNBlob(makeValidDREDDecoderTestDNNBlob()); err != nil {
t.Fatalf("SetDNNBlob error: %v", err)
}
pcm := make([]float32, 960*2)
if _, err := dec.Decode(extended, pcm); err != nil {
t.Fatalf("Decode error: %v", err)
}
if dec.dredCache.Empty() {
t.Fatal("expected cached DRED payload before downgrade")
}
if err := dec.SetDNNBlob(makeValidDecoderTestDNNBlob()); err != nil {
t.Fatalf("SetDNNBlob(non_dred) error: %v", err)
}
if dec.dredCache != (internaldred.Cache{}) {
t.Fatalf("downgraded blob left DRED cache=%+v want zero state", dec.dredCache)
}
if err := dec.SetDNNBlob(makeValidDREDDecoderTestDNNBlob()); err != nil {
t.Fatalf("SetDNNBlob(redred) error: %v", err)
}
if _, err := dec.Decode(extended, pcm); err != nil {
t.Fatalf("Decode after redred error: %v", err)
}
if dec.dredCache.Empty() {
t.Fatal("expected cached DRED payload before ignore toggle")
}
dec.SetIgnoreExtensions(true)
if dec.dredCache != (internaldred.Cache{}) {
t.Fatalf("SetIgnoreExtensions(true) left DRED cache=%+v want zero state", dec.dredCache)
}
}
// minimalHybridTestPacket20ms creates a test packet for Hybrid FB 20ms mono (config 15).
// This is a manually constructed packet that produces valid decoder output.
// The TOC byte (0x78) indicates: config=15 (Hybrid FB 20ms), mono, code 0 (single frame).
func minimalHybridTestPacket20ms() []byte {
// TOC byte: config=15 (Hybrid FB 20ms), mono, code 0
// 15 << 3 | 0 << 2 | 0 = 0x78
toc := byte(0x78)
// Frame data: minimal valid hybrid data
// These bytes are designed to produce valid (if near-silence) SILK+CELT decode
frameData := []byte{
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
}
return append([]byte{toc}, frameData...)
}
// minimalHybridTestPacket20msStereo creates a test packet for Hybrid FB 20ms stereo.
// TOC byte (0x7C) indicates: config=15 (Hybrid FB 20ms), stereo, code 0.
func minimalHybridTestPacket20msStereo() []byte {
// TOC byte: config=15 (Hybrid FB 20ms), stereo, code 0
// 15 << 3 | 1 << 2 | 0 = 0x7C
toc := byte(0x7C)
// Frame data for stereo
frameData := []byte{
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF,
}
return append([]byte{toc}, frameData...)
}
func TestDecoder_Decode_Float32(t *testing.T) {
dec, err := NewDecoder(DefaultDecoderConfig(48000, 1))
if err != nil {
t.Fatalf("NewDecoder error: %v", err)
}
packet := minimalHybridTestPacket20ms()
frameSize := 960 // 20ms at 48kHz
pcmOut := make([]float32, frameSize)
n, err := dec.Decode(packet, pcmOut)
if err != nil {
t.Fatalf("Decode error: %v", err)
}
if n != frameSize {
t.Errorf("Decode returned %d samples, want %d", n, frameSize)
}
// Check that output buffer was written to (decoder ran without panic)
t.Logf("Decoded %d samples successfully", n)
}
func TestDecoder_Decode_Int16(t *testing.T) {
dec := newMonoTestDecoder(t)
pcmOut := make([]int16, 960)
n, err := dec.DecodeInt16(minimalHybridTestPacket20ms(), pcmOut)
if err != nil {
t.Fatalf("DecodeInt16 error: %v", err)
}
if n != 960 {
t.Errorf("DecodeInt16 returned %d samples, want %d", n, 960)
}
// Verify samples are in valid int16 range (clamping works)
for i, s := range pcmOut {
if s < -32768 || s > 32767 {
t.Errorf("Sample %d = %d, out of int16 range", i, s)
}
}
}
func TestDecoder_Decode_BufferTooSmall(t *testing.T) {
dec := newMonoTestDecoder(t)
// Buffer too small for float32
pcmOut := make([]float32, 480)
_, err := dec.Decode(minimalHybridTestPacket20ms(), pcmOut)
if err != ErrBufferTooSmall {
t.Errorf("Decode with small buffer: got %v, want ErrBufferTooSmall", err)
}
// Buffer too small for int16
pcmOut16 := make([]int16, 480)
_, err = dec.DecodeInt16(minimalHybridTestPacket20ms(), pcmOut16)
if err != ErrBufferTooSmall {
t.Errorf("DecodeInt16 with small buffer: got %v, want ErrBufferTooSmall", err)
}
}
func TestDecoder_Decode_PLC(t *testing.T) {
dec, err := NewDecoder(DefaultDecoderConfig(48000, 1))
if err != nil {
t.Fatalf("NewDecoder error: %v", err)
}
// First decode a valid frame to set up state
packet := minimalHybridTestPacket20ms()
frameSize := 960
pcmOut := make([]float32, frameSize)
_, err = dec.Decode(packet, pcmOut)
if err != nil {
t.Fatalf("Decode error: %v", err)
}
// Now simulate packet loss by passing nil
pcmPLC := make([]float32, frameSize)
n, err := dec.Decode(nil, pcmPLC)
if err != nil {
t.Fatalf("Decode PLC error: %v", err)
}
if n != frameSize {
t.Errorf("PLC returned %d samples, want %d", n, frameSize)
}
t.Logf("PLC produced %d samples", n)
}
func TestDecoder_Reset(t *testing.T) {
dec, err := NewDecoder(DefaultDecoderConfig(48000, 1))
if err != nil {
t.Fatalf("NewDecoder error: %v", err)
}
packet := minimalHybridTestPacket20ms()
frameSize := 960
// Decode a frame
pcmOut := make([]float32, frameSize)
_, err = dec.Decode(packet, pcmOut)
if err != nil {
t.Fatalf("Decode error: %v", err)
}
// Reset
dec.Reset()
// Decode again should work
_, err = dec.Decode(packet, pcmOut)
if err != nil {
t.Fatalf("Decode after Reset error: %v", err)
}
}
func TestDecoder_Stereo(t *testing.T) {
dec, err := NewDecoder(DefaultDecoderConfig(48000, 2))
if err != nil {
t.Fatalf("NewDecoder error: %v", err)
}
packet := minimalHybridTestPacket20msStereo()
frameSize := 960
pcmOut := make([]float32, frameSize*2) // Stereo: 2 channels
n, err := dec.Decode(packet, pcmOut)
if err != nil {
t.Fatalf("Decode error: %v", err)
}
if n != frameSize {
t.Errorf("Decode returned %d samples per channel, want %d", n, frameSize)
}
}
func TestDecoder_TOCParsing(t *testing.T) {
// Test that the decoder correctly parses the TOC byte to determine frame size
tests := []struct {
name string
toc byte
frameSize int
}{
// Hybrid FB 20ms: config 15
{"hybrid_fb_20ms", 0x78, 960},
// Hybrid FB 10ms: config 14
{"hybrid_fb_10ms", 0x70, 480},
// SILK WB 20ms: config 9
{"silk_wb_20ms", 0x48, 960},
// CELT FB 20ms: config 31
{"celt_fb_20ms", 0xF8, 960},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
toc := ParseTOC(tt.toc)
if toc.FrameSize != tt.frameSize {
t.Errorf("TOC %02X: FrameSize = %d, want %d", tt.toc, toc.FrameSize, tt.frameSize)
}
})
}
}
// TestDecode_ModeRouting verifies that packets are routed to the correct decoder
// based on their TOC mode field.
func TestDecode_ModeRouting(t *testing.T) {
tests := []struct {
name string
config uint8 // TOC config (0-31)
frameSize int // Expected frame size at 48kHz
mode Mode // Expected mode
}{
// SILK-only (configs 0-11)
{"SILK NB 10ms", 0, 480, ModeSILK},
{"SILK NB 20ms", 1, 960, ModeSILK},
{"SILK NB 40ms", 2, 1920, ModeSILK},
{"SILK NB 60ms", 3, 2880, ModeSILK},
{"SILK MB 20ms", 5, 960, ModeSILK},
{"SILK WB 20ms", 9, 960, ModeSILK},
{"SILK WB 40ms", 10, 1920, ModeSILK},
{"SILK WB 60ms", 11, 2880, ModeSILK},
// Hybrid (configs 12-15)
{"Hybrid SWB 10ms", 12, 480, ModeHybrid},
{"Hybrid SWB 20ms", 13, 960, ModeHybrid},
{"Hybrid FB 10ms", 14, 480, ModeHybrid},
{"Hybrid FB 20ms", 15, 960, ModeHybrid},
// CELT-only (configs 16-31)
{"CELT NB 2.5ms", 16, 120, ModeCELT},
{"CELT NB 5ms", 17, 240, ModeCELT},
{"CELT NB 10ms", 18, 480, ModeCELT},
{"CELT NB 20ms", 19, 960, ModeCELT},
{"CELT FB 2.5ms", 28, 120, ModeCELT},
{"CELT FB 5ms", 29, 240, ModeCELT},
{"CELT FB 10ms", 30, 480, ModeCELT},
{"CELT FB 20ms", 31, 960, ModeCELT},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Verify TOC parsing
toc := ParseTOC(GenerateTOC(tt.config, false, 0))
if toc.Mode != tt.mode {
t.Errorf("Mode mismatch: got %v, want %v", toc.Mode, tt.mode)
}
if toc.FrameSize != tt.frameSize {
t.Errorf("FrameSize mismatch: got %d, want %d", toc.FrameSize, tt.frameSize)
}
// Test decoder accepts the packet (may fail on decode but should not fail on routing)
dec, err := NewDecoder(DefaultDecoderConfig(48000, 1))
if err != nil {
t.Fatalf("NewDecoder failed: %v", err)
}
// Create minimal valid packet (TOC + some data)
packet := make([]byte, 100)
packet[0] = GenerateTOC(tt.config, false, 0)
// Fill with minimal valid data for range decoder
for i := 1; i < len(packet); i++ {
packet[i] = byte(i)
}
// Decode should not panic and should not return "hybrid: invalid frame size"
pcm := make([]float32, tt.frameSize*2) // Extra buffer
_, err = dec.Decode(packet, pcm)
// For extended frame sizes, we expect decode to succeed (no routing error)
// The decode may still fail for other reasons (invalid bitstream) but
// should NOT fail with "hybrid: invalid frame size"
if err != nil {
errStr := err.Error()
if strings.Contains(errStr, "hybrid: invalid frame size") {
t.Errorf("Mode routing failed: SILK/CELT packet incorrectly routed to hybrid decoder: %v", err)
}
// Log other errors but don't fail - bitstream content may be invalid
t.Logf("Decode error (non-routing): %v", err)
}
})
}
}
// TestDecode_ExtendedFrameSizes verifies that extended frame sizes (CELT 2.5/5ms,
// SILK 40/60ms) are accepted without being rejected by the hybrid decoder.
func TestDecode_ExtendedFrameSizes(t *testing.T) {
// Test that extended frame sizes don't trigger hybrid validation error
extendedConfigs := []struct {
name string
config uint8
frameSize int
}{
{"CELT 2.5ms", 28, 120}, // CELT FB 2.5ms
{"CELT 5ms", 29, 240}, // CELT FB 5ms
{"SILK 40ms", 10, 1920}, // SILK WB 40ms
{"SILK 60ms", 11, 2880}, // SILK WB 60ms
}
for _, tt := range extendedConfigs {
t.Run(tt.name, func(t *testing.T) {
dec, _ := NewDecoder(DefaultDecoderConfig(48000, 1))
packet := make([]byte, 100)
packet[0] = GenerateTOC(tt.config, false, 0)
for i := 1; i < len(packet); i++ {
packet[i] = byte(i * 7) // Different pattern
}
pcm := make([]float32, tt.frameSize*2)
_, err := dec.Decode(packet, pcm)
// Critical: should NOT fail with hybrid frame size error
if err != nil && strings.Contains(err.Error(), "hybrid: invalid frame size") {
t.Errorf("Extended frame size incorrectly rejected as hybrid: %v", err)
}
})
}
}
// TestDecode_PLC_ModeTracking verifies that PLC uses the last decoded mode,
// not defaulting to Hybrid mode.
func TestDecode_PLC_ModeTracking(t *testing.T) {
dec, _ := NewDecoder(DefaultDecoderConfig(48000, 1))
// First: decode a SILK packet to set mode
silkPacket := make([]byte, 50)
silkPacket[0] = GenerateTOC(9, false, 0) // SILK WB 20ms
for i := 1; i < len(silkPacket); i++ {
silkPacket[i] = byte(i)
}
pcm := make([]float32, 960*2)
_, _ = dec.Decode(silkPacket, pcm)
// PLC should use last mode (SILK)
_, err := dec.Decode(nil, pcm)
if err != nil && strings.Contains(err.Error(), "hybrid") {
t.Errorf("PLC should use SILK mode, not hybrid: %v", err)
}
}
// TestDecodeWithFEC_FallbackToPLC verifies that DecodeWithFEC falls back to PLC
// when no FEC data is available (e.g., when no previous packet was decoded,
// or the previous packet was CELT-only mode).
func TestDecodeWithFEC_FallbackToPLC(t *testing.T) {
dec, err := NewDecoder(DefaultDecoderConfig(48000, 1))
if err != nil {
t.Fatalf("NewDecoder error: %v", err)
}
// Attempt FEC decode without any previous packet - should fall back to PLC
frameSize := 960
pcm := make([]float32, frameSize)
// First FEC decode with no prior data - should use PLC and produce silence/zeros
n, err := dec.DecodeWithFEC(nil, pcm, true)
if err != nil {
t.Fatalf("DecodeWithFEC error (expected PLC fallback): %v", err)
}
if n != frameSize {
t.Errorf("DecodeWithFEC returned %d samples, want %d", n, frameSize)
}
t.Logf("DecodeWithFEC fell back to PLC successfully, produced %d samples", n)
}
// TestDecodeWithFEC_CELTNoFEC verifies that CELT-only packets don't have FEC data.
// DecodeWithFEC should fall back to PLC after decoding a CELT packet.
func TestDecodeWithFEC_CELTNoFEC(t *testing.T) {
dec, err := NewDecoder(DefaultDecoderConfig(48000, 1))
if err != nil {
t.Fatalf("NewDecoder error: %v", err)
}
// Create a CELT packet (config 31 = CELT FB 20ms)
celtPacket := make([]byte, 100)
celtPacket[0] = GenerateTOC(31, false, 0) // CELT FB 20ms
for i := 1; i < len(celtPacket); i++ {
celtPacket[i] = byte(i)
}
frameSize := 960
pcm := make([]float32, frameSize)
// Decode the CELT packet normally
_, err = dec.Decode(celtPacket, pcm)
if err != nil {
t.Fatalf("Decode CELT packet error: %v", err)
}
// Check that no FEC data was stored (CELT doesn't have LBRR)
if dec.hasFEC {
t.Error("hasFEC should be false after CELT packet decode")
}
// Attempt FEC decode - should fall back to PLC since no FEC available
n, err := dec.DecodeWithFEC(nil, pcm, true)
if err != nil {
t.Fatalf("DecodeWithFEC error (expected PLC fallback): %v", err)
}
if n != frameSize {
t.Errorf("DecodeWithFEC returned %d samples, want %d", n, frameSize)
}
t.Logf("DecodeWithFEC correctly fell back to PLC for CELT mode")
}
// TestDecodeWithFEC_SILKStoresFEC verifies that SILK packets store FEC data.
func TestDecodeWithFEC_SILKStoresFEC(t *testing.T) {
dec, err := NewDecoder(DefaultDecoderConfig(48000, 1))
if err != nil {
t.Fatalf("NewDecoder error: %v", err)
}
// Create a SILK packet (config 9 = SILK WB 20ms)
silkPacket := make([]byte, 100)
silkPacket[0] = GenerateTOC(9, false, 0) // SILK WB 20ms
for i := 1; i < len(silkPacket); i++ {
silkPacket[i] = byte(i)
}
frameSize := 960
pcm := make([]float32, frameSize)
// Decode the SILK packet normally
_, err = dec.Decode(silkPacket, pcm)
if err != nil {
t.Fatalf("Decode SILK packet error: %v", err)
}
// Check that FEC data was stored (SILK packets can have LBRR)
if !dec.hasFEC {
t.Error("hasFEC should be true after SILK packet decode")
}
if dec.fecMode != ModeSILK {
t.Errorf("fecMode = %v, want ModeSILK", dec.fecMode)
}
t.Log("DecodeWithFEC correctly stored FEC data for SILK mode")
}
func TestStoreFECData_ReusesBackingBuffer(t *testing.T) {
dec, err := NewDecoder(DefaultDecoderConfig(48000, 1))
if err != nil {
t.Fatalf("NewDecoder error: %v", err)
}
initialCap := cap(dec.fecData)
if initialCap == 0 {
t.Fatal("expected preallocated fecData backing buffer")
}
toc := TOC{
Mode: ModeSILK,
Bandwidth: BandwidthWideband,
Stereo: false,
}
packetSmall := make([]byte, 32)
packetLarge := make([]byte, 512)
for i := range packetSmall {
packetSmall[i] = byte(i)
}
for i := range packetLarge {
packetLarge[i] = byte(255 - (i % 255))
}
dec.storeFECData(packetSmall, toc, 1, 960)
if cap(dec.fecData) != initialCap {
t.Fatalf("fecData cap changed after small packet: got %d want %d", cap(dec.fecData), initialCap)
}
dec.storeFECData(packetLarge, toc, 1, 960)
if cap(dec.fecData) != initialCap {
t.Fatalf("fecData cap changed after large packet: got %d want %d", cap(dec.fecData), initialCap)
}
if len(dec.fecData) != len(packetLarge) {
t.Fatalf("fecData len = %d, want %d", len(dec.fecData), len(packetLarge))
}
if dec.fecData[0] != packetLarge[0] || dec.fecData[len(dec.fecData)-1] != packetLarge[len(packetLarge)-1] {
t.Fatal("fecData content mismatch after copy")
}
}
func TestDecodeFECFrame_BufferSizingUsesSingleFrame(t *testing.T) {
dec, err := NewDecoder(DefaultDecoderConfig(48000, 1))
if err != nil {
t.Fatalf("NewDecoder error: %v", err)
}
// Simulate stored FEC metadata from a 2-frame packet. decode_fec should still
// only require one frame of output buffer.
dec.hasFEC = true
dec.fecData = []byte{0x01, 0x02, 0x03, 0x04}
dec.fecMode = ModeSILK
dec.fecBandwidth = BandwidthWideband
dec.fecStereo = false
dec.fecFrameSize = 960
dec.fecFrameCount = 2
pcm := make([]float32, 960)
_, err = dec.decodeFECFrame(pcm)
if err == ErrBufferTooSmall {
t.Fatal("decodeFECFrame rejected single-frame output buffer for multi-frame packet metadata")
}
}
// TestDecodeWithFEC_HybridStoresFEC verifies that Hybrid packets store FEC data.
func TestDecodeWithFEC_HybridStoresFEC(t *testing.T) {
dec, err := NewDecoder(DefaultDecoderConfig(48000, 1))
if err != nil {
t.Fatalf("NewDecoder error: %v", err)
}
// Use the minimal hybrid test packet
packet := minimalHybridTestPacket20ms()
frameSize := 960
pcm := make([]float32, frameSize)
// Decode the Hybrid packet normally
_, err = dec.Decode(packet, pcm)
if err != nil {
t.Fatalf("Decode Hybrid packet error: %v", err)
}
// Check that FEC data was stored (Hybrid packets can have LBRR)
if !dec.hasFEC {
t.Error("hasFEC should be true after Hybrid packet decode")
}
if dec.fecMode != ModeHybrid {
t.Errorf("fecMode = %v, want ModeHybrid", dec.fecMode)
}
t.Log("DecodeWithFEC correctly stored FEC data for Hybrid mode")
}
// TestDecodeWithFEC_Recovery tests FEC recovery flow.
// This test simulates packet loss and FEC recovery.
func TestDecodeWithFEC_Recovery(t *testing.T) {
dec, err := NewDecoder(DefaultDecoderConfig(48000, 1))
if err != nil {
t.Fatalf("NewDecoder error: %v", err)
}
// Decode a series of SILK packets to build up state
silkPacket := make([]byte, 100)
silkPacket[0] = GenerateTOC(9, false, 0) // SILK WB 20ms
for i := 1; i < len(silkPacket); i++ {
silkPacket[i] = byte(i * 3)
}
frameSize := 960
pcm1 := make([]float32, frameSize)
pcm2 := make([]float32, frameSize)
// Decode packet 1
_, err = dec.Decode(silkPacket, pcm1)
if err != nil {
t.Fatalf("Decode packet 1 error: %v", err)
}
// Simulate packet 2 is lost - use FEC to recover
// In real usage, we'd use the NEXT packet's LBRR to recover the lost one.
// For this test, we just verify DecodeWithFEC works without crashing.
n, err := dec.DecodeWithFEC(nil, pcm2, true)
if err != nil {
t.Fatalf("DecodeWithFEC error: %v", err)
}
if n != frameSize {
t.Errorf("DecodeWithFEC returned %d samples, want %d", n, frameSize)
}
t.Logf("FEC recovery produced %d samples", n)
}
func TestDecodeWithFEC_UsesProvidedPacketAndPreservesNormalDecode(t *testing.T) {
enc, err := NewEncoder(EncoderConfig{SampleRate: 48000, Channels: 1, Application: ApplicationVoIP})
if err != nil {
t.Fatalf("NewEncoder error: %v", err)
}
enc.SetFEC(true)
if err := enc.SetPacketLoss(15); err != nil {
t.Fatalf("SetPacketLoss error: %v", err)
}
if err := enc.SetBitrate(24000); err != nil {
t.Fatalf("SetBitrate error: %v", err)
}
frameSize := 960
makeFrame := func(phase float64) []float32 {
pcm := make([]float32, frameSize)
for i := range pcm {
tm := (float64(i) + phase) / 48000.0
pcm[i] = float32(0.5*math.Sin(2*math.Pi*440*tm) + 0.2*math.Sin(2*math.Pi*880*tm))
}
return pcm
}