-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathdecoder.go
More file actions
1325 lines (1188 loc) · 39 KB
/
decoder.go
File metadata and controls
1325 lines (1188 loc) · 39 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
// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package opus provides a Opus Audio Codec RFC 6716 implementation
package opus
import (
"fmt"
"github.com/pion/opus/internal/bitdepth"
"github.com/pion/opus/internal/celt"
"github.com/pion/opus/internal/rangecoding"
silkresample "github.com/pion/opus/internal/resample/silk"
"github.com/pion/opus/internal/silk"
)
const (
maxOpusFrameSize = 1275
maxOpusPacketDurationNanosecond = 120000000
maxSilkFrameSampleCount = 320
maxCeltFrameSampleCount = 960
celtSampleRate = 48000
hybridRedundantFrameSampleCount = celtSampleRate / 200
hybridFadeSampleCount = celtSampleRate / 400
)
// Decoder decodes the Opus bitstream into PCM.
type Decoder struct {
silkDecoder silk.Decoder
silkBuffer []float32
celtDecoder celt.Decoder
celtBuffer []float32
rangeDecoder rangecoding.Decoder
rangeFinal uint32
previousMode configurationMode
previousRedundancy bool
resampleBuffer []float32
resampleChannelIn [2][]float32
resampleChannelOut [2][]float32
silkResampler [2]silkresample.Resampler
silkResamplerBandwidth Bandwidth
silkResamplerChannels int
hybridSilkResampler [2]silkresample.Resampler
hybridSilkChannels int
silkRedundancyFades []silkRedundancyFade
silkCeltAdditions []silkCeltAddition
floatBuffer []float32
sampleRate int
channels int
}
type silkRedundancyFade struct {
celtToSilk bool
audio []float32
startSample int
frameSampleCount int
channelCount int
}
type silkCeltAddition struct {
audio []float32
startSample int
channelCount int
}
// NewDecoder creates a new Opus Decoder.
func NewDecoder() Decoder {
decoder, _ := NewDecoderWithOutput(BandwidthFullband.SampleRate(), 1)
return decoder
}
// NewDecoderWithOutput creates a new Opus Decoder with the requested output sample rate and channel count.
func NewDecoderWithOutput(sampleRate, channels int) (Decoder, error) {
decoder := Decoder{
silkDecoder: silk.NewDecoder(),
silkBuffer: make([]float32, maxSilkFrameSampleCount),
celtDecoder: celt.NewDecoder(),
}
if err := decoder.Init(sampleRate, channels); err != nil {
return Decoder{}, err
}
return decoder, nil
}
// Init initializes a pre-allocated Opus decoder.
func (d *Decoder) Init(sampleRate, channels int) error {
switch sampleRate {
case 8000, 12000, 16000, 24000, 48000:
default:
return errInvalidSampleRate
}
switch channels {
case 1, 2:
default:
return errInvalidChannelCount
}
d.sampleRate = sampleRate
d.channels = channels
d.silkDecoder = silk.NewDecoder()
d.celtDecoder.Reset()
d.celtBuffer = d.celtBuffer[:0]
d.rangeDecoder = rangecoding.Decoder{}
d.silkResampler = [2]silkresample.Resampler{}
d.silkResamplerBandwidth = 0
d.silkResamplerChannels = 0
d.hybridSilkResampler = [2]silkresample.Resampler{}
d.hybridSilkChannels = 0
d.silkRedundancyFades = d.silkRedundancyFades[:0]
d.silkCeltAdditions = d.silkCeltAdditions[:0]
d.rangeFinal = 0
d.previousMode = 0
d.previousRedundancy = false
return nil
}
// resampleSilk uses the RFC 6716 C reference's decoder-side SILK resampler.
func (d *Decoder) resampleSilk(in, out []float32, channelCount int, bandwidth Bandwidth) error {
if err := d.initSilkResampler(channelCount, bandwidth); err != nil {
return err
}
samplesPerChannel := len(in) / channelCount
resampledSamplesPerChannel := samplesPerChannel * d.sampleRate / bandwidth.SampleRate()
for channelIndex := range channelCount {
if err := d.resampleSilkChannel(
in,
out,
channelIndex,
channelCount,
samplesPerChannel,
resampledSamplesPerChannel,
); err != nil {
return err
}
}
return nil
}
func (d *Decoder) initSilkResampler(channelCount int, bandwidth Bandwidth) error {
if d.silkResamplerBandwidth != bandwidth {
for i := range d.silkResampler {
if err := d.silkResampler[i].Init(bandwidth.SampleRate(), d.sampleRate); err != nil {
return err
}
}
d.silkResamplerBandwidth = bandwidth
d.silkResamplerChannels = channelCount
}
if channelCount == 2 && d.silkResamplerChannels == 1 {
d.silkResampler[1].CopyStateFrom(&d.silkResampler[0])
}
d.silkResamplerChannels = channelCount
return nil
}
func (d *Decoder) resampleSilkChannel(
in, out []float32,
channelIndex, channelCount, samplesPerChannel, resampledSamplesPerChannel int,
) error {
if cap(d.resampleChannelIn[channelIndex]) < samplesPerChannel {
d.resampleChannelIn[channelIndex] = make([]float32, samplesPerChannel)
}
if cap(d.resampleChannelOut[channelIndex]) < resampledSamplesPerChannel {
d.resampleChannelOut[channelIndex] = make([]float32, resampledSamplesPerChannel)
}
channelIn := d.resampleChannelIn[channelIndex][:samplesPerChannel]
channelOut := d.resampleChannelOut[channelIndex][:resampledSamplesPerChannel]
for i := range samplesPerChannel {
channelIn[i] = in[(i*channelCount)+channelIndex]
}
if err := d.silkResampler[channelIndex].Resample(channelIn, channelOut); err != nil {
return err
}
for i := range resampledSamplesPerChannel {
out[(i*channelCount)+channelIndex] = channelOut[i]
}
return nil
}
// resetModeState applies the decoder resets required by RFC 6716 Section 4.5.2
// before the first frame decoded in a new operating mode.
func (d *Decoder) resetModeState(mode configurationMode) {
if d.previousMode == mode {
return
}
switch mode {
case configurationModeSilkOnly:
if d.previousMode == configurationModeCELTOnly {
d.silkDecoder = silk.NewDecoder()
}
if d.previousMode == configurationModeHybrid {
d.copyHybridSilkResamplerToSilk()
}
case configurationModeCELTOnly:
if !d.previousRedundancy {
d.celtDecoder.Reset()
clear(d.celtBuffer)
}
case configurationModeHybrid:
if d.previousMode == configurationModeCELTOnly {
d.silkDecoder = silk.NewDecoder()
d.hybridSilkResampler = [2]silkresample.Resampler{}
d.hybridSilkChannels = 0
}
if d.previousMode == configurationModeSilkOnly {
d.copySilkResamplerToHybrid()
}
}
}
// copySilkResamplerToHybrid preserves the WB SILK resampler history across the
// normatively continuous WB SILK -> Hybrid transition in RFC 6716 Section 4.5.
func (d *Decoder) copySilkResamplerToHybrid() {
if d.silkResamplerBandwidth != BandwidthWideband || d.silkResamplerChannels == 0 {
return
}
for i := range d.hybridSilkResampler {
d.hybridSilkResampler[i].CopyStateFrom(&d.silkResampler[i])
}
d.hybridSilkChannels = d.silkResamplerChannels
}
// copyHybridSilkResamplerToSilk preserves the same WB SILK history for the
// reverse Hybrid -> WB SILK transition described by RFC 6716 Section 4.5.
func (d *Decoder) copyHybridSilkResamplerToSilk() {
if d.hybridSilkChannels == 0 {
return
}
for i := range d.silkResampler {
d.silkResampler[i].CopyStateFrom(&d.hybridSilkResampler[i])
}
d.silkResamplerBandwidth = BandwidthWideband
d.silkResamplerChannels = d.hybridSilkChannels
}
func (c Configuration) silkFrameSampleCount() int {
if c.mode() != configurationModeSilkOnly {
return 0
}
switch c.bandwidth() {
case BandwidthNarrowband:
return 8 * c.frameDuration().nanoseconds() / 1000000
case BandwidthMediumband:
return 12 * c.frameDuration().nanoseconds() / 1000000
case BandwidthWideband:
return 16 * c.frameDuration().nanoseconds() / 1000000
case BandwidthSuperwideband, BandwidthFullband:
return 0
}
return 0
}
func (c Configuration) celtFrameSampleCount() int {
if c.mode() != configurationModeCELTOnly {
return 0
}
if c.frameDuration() == frameDuration20ms {
return maxCeltFrameSampleCount
}
return int(int64(c.frameDuration().nanoseconds()) * int64(celtSampleRate) / 1000000000)
}
func (c Configuration) hybridFrameSampleCount() int {
if c.mode() != configurationModeHybrid {
return 0
}
return int(int64(c.frameDuration().nanoseconds()) * int64(celtSampleRate) / 1000000000)
}
func (c Configuration) decodedSampleRate() int {
switch c.mode() {
case configurationModeSilkOnly:
return c.bandwidth().SampleRate()
case configurationModeCELTOnly, configurationModeHybrid:
return celtSampleRate
default:
return 0
}
}
// sampleCountAtRate converts a 48 kHz CELT-domain length into the caller's
// requested Opus API output rate.
func sampleCountAtRate(samples48 int, outputSampleRate int) int {
return samples48 * outputSampleRate / celtSampleRate
}
// celtFadeSampleCount returns the 2.5 ms CELT transition overlap at the
// caller's output rate.
func celtFadeSampleCount(outputSampleRate int) int {
return outputSampleRate / 400
}
// celtRedundantFrameSampleCount returns the 5 ms redundant CELT frame length
// at the caller's output rate.
func celtRedundantFrameSampleCount(outputSampleRate int) int {
return outputSampleRate / 200
}
func parseFrameLength(in []byte) (frameLength int, bytesRead int, err error) {
if len(in) < 1 {
return 0, 0, fmt.Errorf("%w: missing frame length", errMalformedPacket)
}
if in[0] < 252 {
return int(in[0]), 1, nil
}
if len(in) < 2 {
return 0, 0, fmt.Errorf("%w: truncated two-byte frame length", errMalformedPacket)
}
return int(in[0]) + 4*int(in[1]), 2, nil
}
func parsePacketFramesCode0(in []byte) ([][]byte, error) {
// [R2] Code 0 uses an implicit frame length for the whole payload, so it
// must not exceed the 1275-byte maximum.
if len(in[1:]) > maxOpusFrameSize {
return nil, fmt.Errorf("%w: frame size %d exceeds %d", errMalformedPacket, len(in[1:]), maxOpusFrameSize)
}
return [][]byte{in[1:]}, nil
}
func parsePacketFramesCode1(in []byte) ([][]byte, error) {
payload := in[1:]
// [R3] Code 1 packets have an odd total length so (N-1)/2 is integral.
if len(payload)%2 != 0 {
return nil, fmt.Errorf("%w: code 1 packet payload must be even-sized", errMalformedPacket)
}
// [R2] Code 1 uses an implicit length for both equal-sized frames.
frameSize := len(payload) / 2
if frameSize > maxOpusFrameSize {
return nil, fmt.Errorf("%w: frame size %d exceeds %d", errMalformedPacket, frameSize, maxOpusFrameSize)
}
return [][]byte{payload[:frameSize], payload[frameSize:]}, nil
}
func parsePacketFramesCode2(in []byte) ([][]byte, error) {
// [R4] Code 2 must have enough bytes after the TOC to decode a valid
// first-frame length.
frameSize, bytesRead, err := parseFrameLength(in[1:])
if err != nil {
return nil, err
}
firstFrameStart := 1 + bytesRead
firstFrameEnd := firstFrameStart + frameSize
// [R4] The signaled first-frame length must fit in the remaining bytes.
if firstFrameEnd > len(in) {
return nil, fmt.Errorf("%w: first frame overruns packet", errMalformedPacket)
}
// [R2] The second Code 2 frame has an implicit length from the remainder.
secondFrameSize := len(in) - firstFrameEnd
if secondFrameSize > maxOpusFrameSize {
return nil, fmt.Errorf("%w: frame size %d exceeds %d", errMalformedPacket, secondFrameSize, maxOpusFrameSize)
}
return [][]byte{in[firstFrameStart:firstFrameEnd], in[firstFrameEnd:]}, nil
}
func parsePacketPadding(in []byte, offset int) (newOffset int, payloadEnd int, err error) {
remaining := len(in) - offset
for {
// [R6][R7] Padding length bytes are part of the Code 3 header and
// must be present before any frame data.
if remaining <= 0 {
return 0, 0, fmt.Errorf("%w: truncated padding length", errMalformedPacket)
}
paddingByte := int(in[offset])
offset++
remaining--
paddingLength := paddingByte
if paddingByte == 255 {
paddingLength = 254
}
// RFC 8251 Section 4 hardens the reference parser by decrementing the
// remaining packet length as each padding byte is consumed, rather than
// accumulating a potentially overflowing padding total.
if paddingLength > remaining {
return 0, 0, fmt.Errorf("%w: padding overruns packet", errMalformedPacket)
}
remaining -= paddingLength
if paddingByte == 255 {
continue
}
break
}
return offset, offset + remaining, nil
}
func parsePacketFramesCode3(in []byte, tocHeader tableOfContentsHeader) ([][]byte, error) {
// [R6][R7] Code 3 packets need at least TOC + frame count bytes.
if len(in) < 2 {
return nil, fmt.Errorf("%w: code 3 packet missing frame count byte", errMalformedPacket)
}
isVBR, hasPadding, frameCount := parseFrameCountByte(in[1])
// [R5] Code 3 packets must contain at least one frame.
if frameCount == 0 {
return nil, fmt.Errorf("%w: code 3 frame count must not be zero", errMalformedPacket)
}
// [R5] Total audio duration in a packet is capped at 120 ms.
if int(frameCount)*tocHeader.configuration().frameDuration().nanoseconds() > maxOpusPacketDurationNanosecond {
return nil, fmt.Errorf("%w: packet duration exceeds 120 ms", errMalformedPacket)
}
offset := 2
payloadEnd := len(in)
var err error
if hasPadding {
offset, payloadEnd, err = parsePacketPadding(in, offset)
if err != nil {
return nil, err
}
}
// [R6] In CBR Code 3, the padding-length bytes plus trailing padding
// must fit within the packet, leaving at least TOC + frame count.
// [R7] In VBR Code 3, the same bound applies before frame data.
if payloadEnd < offset {
return nil, fmt.Errorf("%w: padding overruns packet", errMalformedPacket)
}
if !isVBR {
return parsePacketFramesCode3CBR(in, offset, payloadEnd, frameCount)
}
return parsePacketFramesCode3VBR(in, offset, payloadEnd, frameCount)
}
func parsePacketFramesCode3CBR(in []byte, offset, payloadEnd int, frameCount byte) ([][]byte, error) {
payloadSize := payloadEnd - offset
// [R6] CBR payload size must be an integer multiple of M frames.
if payloadSize%int(frameCount) != 0 {
return nil, fmt.Errorf("%w: CBR payload not divisible by frame count", errMalformedPacket)
}
// [R2] CBR Code 3 uses an implicit equal frame length.
frameSize := payloadSize / int(frameCount)
if frameSize > maxOpusFrameSize {
return nil, fmt.Errorf("%w: frame size %d exceeds %d", errMalformedPacket, frameSize, maxOpusFrameSize)
}
frames := make([][]byte, 0, frameCount)
for range int(frameCount) {
frames = append(frames, in[offset:offset+frameSize])
offset += frameSize
}
return frames, nil
}
func parsePacketFramesCode3VBR(in []byte, offset, payloadEnd int, frameCount byte) ([][]byte, error) {
frameSizes := make([]int, 0, frameCount)
for range int(frameCount) - 1 {
// [R7] VBR Code 3 must have enough header bytes to decode each of the
// first M-1 frame lengths.
frameSize, bytesRead, err := parseFrameLength(in[offset:payloadEnd])
if err != nil {
return nil, err
}
offset += bytesRead
frameSizes = append(frameSizes, frameSize)
}
frames := make([][]byte, 0, frameCount)
for _, frameSize := range frameSizes {
// [R7] The first M-1 VBR frames must fit before the final implicit
// frame and any trailing padding.
if offset+frameSize > payloadEnd {
return nil, fmt.Errorf("%w: VBR frame overruns packet", errMalformedPacket)
}
frames = append(frames, in[offset:offset+frameSize])
offset += frameSize
}
// [R2] The final VBR Code 3 frame has an implicit length from the
// remaining payload.
lastFrameSize := payloadEnd - offset
if lastFrameSize < 0 {
return nil, fmt.Errorf("%w: VBR payload underrun", errMalformedPacket)
}
if lastFrameSize > maxOpusFrameSize {
return nil, fmt.Errorf("%w: frame size %d exceeds %d", errMalformedPacket, lastFrameSize, maxOpusFrameSize)
}
frames = append(frames, in[offset:payloadEnd])
return frames, nil
}
func parsePacketFrames(in []byte, tocHeader tableOfContentsHeader) ([][]byte, error) {
// [R1] A well-formed Opus packet contains at least one byte for the TOC.
if len(in) < 1 {
return nil, fmt.Errorf("%w: %w", errMalformedPacket, errTooShortForTableOfContentsHeader)
}
switch tocHeader.frameCode() {
case frameCodeOneFrame:
return parsePacketFramesCode0(in)
case frameCodeTwoEqualFrames:
return parsePacketFramesCode1(in)
case frameCodeTwoDifferentFrames:
return parsePacketFramesCode2(in)
case frameCodeArbitraryFrames:
return parsePacketFramesCode3(in, tocHeader)
default:
return nil, fmt.Errorf("%w: %d", errUnsupportedFrameCode, tocHeader.frameCode())
}
}
func (d *Decoder) decode(
in []byte,
out []float32,
) (
bandwidth Bandwidth,
decodedSampleRate int,
isStereo bool,
sampleCount int,
decodedChannelCount int,
err error,
) {
if len(in) < 1 {
return 0, 0, false, 0, 0, errTooShortForTableOfContentsHeader
}
tocHeader := tableOfContentsHeader(in[0])
cfg := tocHeader.configuration()
encodedFrames, err := parsePacketFrames(in, tocHeader)
if err != nil {
return 0, 0, false, 0, 0, err
}
switch cfg.mode() {
case configurationModeSilkOnly:
d.resetModeState(configurationModeSilkOnly)
return d.decodeSilkFrames(cfg, tocHeader, encodedFrames, out)
case configurationModeCELTOnly:
d.resetModeState(configurationModeCELTOnly)
return d.decodeCeltFrames(cfg, tocHeader, encodedFrames, out)
case configurationModeHybrid:
d.resetModeState(configurationModeHybrid)
return d.decodeHybridFrames(cfg, tocHeader, encodedFrames, out)
default:
return 0, 0, false, 0, 0, fmt.Errorf("%w: %d", errUnsupportedConfigurationMode, cfg.mode())
}
}
// decodeCeltFrames keeps CELT synthesis in the internal 48 kHz mode while
// emitting PCM at the caller-requested Opus API output rate.
func (d *Decoder) decodeCeltFrames(
cfg Configuration,
tocHeader tableOfContentsHeader,
encodedFrames [][]byte,
out []float32,
) (
bandwidth Bandwidth,
decodedSampleRate int,
isStereo bool,
sampleCount int,
decodedChannelCount int,
err error,
) {
frameSampleCount := cfg.celtFrameSampleCount()
outputFrameSampleCount := sampleCountAtRate(frameSampleCount, d.sampleRate)
streamChannelCount := 1
if tocHeader.isStereo() {
streamChannelCount = 2
}
decodedChannelCount = d.channels
if decodedChannelCount == 0 {
decodedChannelCount = streamChannelCount
}
requiredSamples := outputFrameSampleCount * len(encodedFrames) * decodedChannelCount
if cap(out) < requiredSamples {
d.silkBuffer = make([]float32, requiredSamples)
out = d.silkBuffer
}
out = out[:requiredSamples]
for i := range out {
out[i] = 0
}
startBand, endBand, err := d.celtDecoder.Mode().BandRangeForSampleRate(cfg.bandwidth().SampleRate())
if err != nil {
return 0, 0, false, 0, 0, err
}
frameOutputSamples := outputFrameSampleCount * decodedChannelCount
for i, encodedFrame := range encodedFrames {
frameOut := out[i*frameOutputSamples : (i+1)*frameOutputSamples]
if err = d.celtDecoder.DecodeToSampleRate(
encodedFrame,
frameOut,
tocHeader.isStereo(),
decodedChannelCount,
frameSampleCount,
startBand,
endBand,
d.sampleRate,
); err != nil {
return 0, 0, false, 0, 0, err
}
d.previousMode = configurationModeCELTOnly
d.previousRedundancy = false
if len(encodedFrame) <= 1 {
d.rangeFinal = 0
} else {
d.rangeFinal = d.celtDecoder.FinalRange()
}
}
return cfg.bandwidth(), d.sampleRate, tocHeader.isStereo(), requiredSamples, decodedChannelCount, nil
}
// decodeHybridFrames combines the SILK and CELT layers for Hybrid packets.
func (d *Decoder) decodeHybridFrames(
cfg Configuration,
tocHeader tableOfContentsHeader,
encodedFrames [][]byte,
out []float32,
) (
bandwidth Bandwidth,
decodedSampleRate int,
isStereo bool,
sampleCount int,
decodedChannelCount int,
err error,
) {
frameSampleCount := cfg.hybridFrameSampleCount()
outputFrameSampleCount := sampleCountAtRate(frameSampleCount, d.sampleRate)
streamChannelCount := 1
if tocHeader.isStereo() {
streamChannelCount = 2
}
decodedChannelCount = d.channels
if decodedChannelCount == 0 {
decodedChannelCount = streamChannelCount
}
requiredSamples := outputFrameSampleCount * len(encodedFrames) * decodedChannelCount
if cap(out) < requiredSamples {
d.silkBuffer = make([]float32, requiredSamples)
out = d.silkBuffer
}
out = out[:requiredSamples]
for i := range out {
out[i] = 0
}
startBand, endBand, err := d.celtDecoder.Mode().HybridBandRange(cfg.bandwidth().SampleRate())
if err != nil {
return 0, 0, false, 0, 0, err
}
frameOutputSamples := outputFrameSampleCount * decodedChannelCount
silkSamplesPerChannel := frameSampleCount * BandwidthWideband.SampleRate() / celtSampleRate
for i, encodedFrame := range encodedFrames {
frameOut := out[i*frameOutputSamples : (i+1)*frameOutputSamples]
if err = d.decodeHybridFrame(
encodedFrame,
frameOut,
tocHeader.isStereo(),
streamChannelCount,
decodedChannelCount,
frameSampleCount,
outputFrameSampleCount,
silkSamplesPerChannel,
cfg.frameDuration().nanoseconds(),
startBand,
endBand,
); err != nil {
return 0, 0, false, 0, 0, err
}
}
return cfg.bandwidth(), d.sampleRate, tocHeader.isStereo(), requiredSamples, decodedChannelCount, nil
}
type hybridRedundancy struct {
present bool
celtToSilk bool
celtDataLen int
endBand int
data []byte
audio []float32
rng uint32
}
// decodeHybridFrame follows RFC 6716 Sections 4.5.1 and 4.5.2 for one Hybrid
// frame: decode shared-range SILK, split optional CELT redundancy, decode CELT,
// then apply the required transition cross-lap when redundancy is present.
//
//nolint:cyclop
func (d *Decoder) decodeHybridFrame(
encodedFrame []byte,
out []float32,
isStereo bool,
streamChannelCount int,
outputChannelCount int,
frameSampleCount int,
outputFrameSampleCount int,
silkSamplesPerChannel int,
frameNanoseconds int,
startBand int,
endBand int,
) error {
d.rangeDecoder.Init(encodedFrame)
silkOutputChannelCount := min(streamChannelCount, outputChannelCount)
silkInternal := make([]float32, silkSamplesPerChannel*silkOutputChannelCount)
if err := d.silkDecoder.DecodeWithRangeToChannels(
&d.rangeDecoder,
silkInternal,
isStereo,
silkOutputChannelCount,
frameNanoseconds,
silk.Bandwidth(BandwidthWideband),
); err != nil {
return err
}
var err error
redundancy := d.decodeHybridRedundancyHeader(encodedFrame)
if redundancy.present && redundancy.celtToSilk {
if err = d.decodeHybridRedundantFrame(&redundancy, isStereo, outputChannelCount, endBand); err != nil {
return err
}
}
if d.previousMode != configurationModeHybrid && d.previousMode != 0 && !d.previousRedundancy {
d.celtDecoder.Reset()
clear(d.celtBuffer)
}
if err = d.celtDecoder.DecodeWithRangeToSampleRate(
encodedFrame[:redundancy.celtDataLen],
out,
isStereo,
outputChannelCount,
frameSampleCount,
startBand,
endBand,
d.sampleRate,
&d.rangeDecoder,
); err != nil {
return err
}
silkPCM := make([]float32, outputFrameSampleCount*silkOutputChannelCount)
if err = d.resampleHybridSilk(silkInternal, silkPCM, silkOutputChannelCount); err != nil {
return err
}
d.addHybridSilk(out, silkPCM, silkOutputChannelCount, outputChannelCount, outputFrameSampleCount)
if redundancy.present && !redundancy.celtToSilk {
d.celtDecoder.Reset()
clear(d.celtBuffer)
if err = d.decodeHybridRedundantFrame(&redundancy, isStereo, outputChannelCount, endBand); err != nil {
return err
}
fadeSampleCount := celtFadeSampleCount(d.sampleRate)
fadeStart := (outputFrameSampleCount - fadeSampleCount) * outputChannelCount
redundantStart := fadeSampleCount * outputChannelCount
celt.SmoothFadeWithSampleRate(
out[fadeStart:],
redundancy.audio[redundantStart:],
out[fadeStart:],
fadeSampleCount,
outputChannelCount,
d.sampleRate,
)
}
if redundancy.present && redundancy.celtToSilk {
fadeSampleCount := celtFadeSampleCount(d.sampleRate)
for sample := range fadeSampleCount {
for channel := range outputChannelCount {
index := sample*outputChannelCount + channel
out[index] = redundancy.audio[index]
}
}
fadeStart := fadeSampleCount * outputChannelCount
celt.SmoothFadeWithSampleRate(
redundancy.audio[fadeStart:],
out[fadeStart:],
out[fadeStart:],
fadeSampleCount,
outputChannelCount,
d.sampleRate,
)
}
if len(encodedFrame) <= 1 {
d.rangeFinal = 0
} else {
d.rangeFinal = d.rangeDecoder.FinalRange() ^ redundancy.rng
}
d.previousMode = configurationModeHybrid
d.previousRedundancy = redundancy.present && !redundancy.celtToSilk
return nil
}
// decodeHybridRedundancyHeader parses the Hybrid transition side information
// from RFC 6716 Sections 4.5.1.1 through 4.5.1.3.
//
//nolint:gosec
func (d *Decoder) decodeHybridRedundancyHeader(
encodedFrame []byte,
) hybridRedundancy {
redundancy := hybridRedundancy{celtDataLen: len(encodedFrame)}
if int(d.rangeDecoder.Tell())+17+20 > 8*len(encodedFrame) {
return redundancy
}
if d.rangeDecoder.DecodeSymbolLogP(12) == 0 {
return redundancy
}
celtToSilk := d.rangeDecoder.DecodeSymbolLogP(1) != 0
redundancyBytesRaw, _ := d.rangeDecoder.DecodeUniform(256)
redundancyBytes := int(redundancyBytesRaw) + 2
redundancy.celtDataLen -= redundancyBytes
if redundancy.celtDataLen < 0 || redundancy.celtDataLen*8 < int(d.rangeDecoder.Tell()) {
return hybridRedundancy{celtDataLen: len(encodedFrame)}
}
d.rangeDecoder.SetStorageSize(redundancy.celtDataLen)
redundancy.present = true
redundancy.celtToSilk = celtToSilk
redundancy.data = encodedFrame[redundancy.celtDataLen:]
return redundancy
}
// decodeSilkOnlyRedundancyHeader parses the SILK-only variant of the transition
// side information defined by RFC 6716 Sections 4.5.1.1 and 4.5.1.2.
//
//nolint:gosec
func (d *Decoder) decodeSilkOnlyRedundancyHeader(
encodedFrame []byte,
bandwidth Bandwidth,
) (hybridRedundancy, error) {
redundancy := hybridRedundancy{celtDataLen: len(encodedFrame)}
if int(d.rangeDecoder.Tell())+17 > 8*len(encodedFrame) {
return redundancy, nil
}
celtToSilk := d.rangeDecoder.DecodeSymbolLogP(1) != 0
redundancyBytes := len(encodedFrame) - int((d.rangeDecoder.Tell()+7)>>3)
redundancy.celtDataLen -= redundancyBytes
if redundancyBytes <= 0 || redundancy.celtDataLen < 0 || redundancy.celtDataLen*8 < int(d.rangeDecoder.Tell()) {
return hybridRedundancy{celtDataLen: len(encodedFrame)}, nil
}
d.rangeDecoder.SetStorageSize(redundancy.celtDataLen)
endBand, err := d.celtEndBandForSilkBandwidth(bandwidth)
if err != nil {
return redundancy, err
}
redundancy.present = true
redundancy.celtToSilk = celtToSilk
redundancy.data = encodedFrame[redundancy.celtDataLen:]
redundancy.endBand = endBand
return redundancy, nil
}
// celtEndBandForSilkBandwidth selects the redundant CELT bandwidth required by
// RFC 6716 Section 4.5.1.4; MB SILK transitions use WB CELT bandwidth.
func (d *Decoder) celtEndBandForSilkBandwidth(bandwidth Bandwidth) (int, error) {
sampleRate := bandwidth.SampleRate()
if bandwidth == BandwidthMediumband {
sampleRate = BandwidthWideband.SampleRate()
}
_, endBand, err := d.celtDecoder.Mode().BandRangeForSampleRate(sampleRate)
return endBand, err
}
// decodeHybridRedundantFrame decodes the fixed 5 ms redundant CELT frame from
// RFC 6716 Section 4.5.1.4.
func (d *Decoder) decodeHybridRedundantFrame(
redundancy *hybridRedundancy,
isStereo bool,
outputChannelCount int,
endBand int,
) error {
redundantOutputSamples := celtRedundantFrameSampleCount(d.sampleRate)
redundancy.audio = make([]float32, redundantOutputSamples*outputChannelCount)
if err := d.celtDecoder.DecodeToSampleRate(
redundancy.data,
redundancy.audio,
isStereo,
outputChannelCount,
hybridRedundantFrameSampleCount,
0,
endBand,
d.sampleRate,
); err != nil {
return err
}
redundancy.rng = d.celtDecoder.FinalRange()
return nil
}
// resampleHybridSilk lifts the Hybrid packet's WB SILK layer into the decoder's
// output-rate domain before the two layers are summed.
func (d *Decoder) resampleHybridSilk(in []float32, out []float32, channelCount int) error {
if d.hybridSilkChannels == 0 {
for i := range d.hybridSilkResampler {
if err := d.hybridSilkResampler[i].Init(BandwidthWideband.SampleRate(), d.sampleRate); err != nil {
return err
}
}
}
if channelCount == 2 && d.hybridSilkChannels == 1 {
d.hybridSilkResampler[1].CopyStateFrom(&d.hybridSilkResampler[0])
}
d.hybridSilkChannels = channelCount
samplesPerChannel := len(in) / channelCount
resampledSamplesPerChannel := len(out) / channelCount
for channelIndex := range channelCount {
if err := d.resampleHybridSilkChannel(
in,
out,
channelIndex,
channelCount,
samplesPerChannel,
resampledSamplesPerChannel,
); err != nil {
return err
}
}
return nil
}
func (d *Decoder) resampleHybridSilkChannel(
in []float32,
out []float32,
channelIndex, channelCount, samplesPerChannel, resampledSamplesPerChannel int,
) error {
if cap(d.resampleChannelIn[channelIndex]) < samplesPerChannel {
d.resampleChannelIn[channelIndex] = make([]float32, samplesPerChannel)
}
if cap(d.resampleChannelOut[channelIndex]) < resampledSamplesPerChannel {
d.resampleChannelOut[channelIndex] = make([]float32, resampledSamplesPerChannel)
}
channelIn := d.resampleChannelIn[channelIndex][:samplesPerChannel]
channelOut := d.resampleChannelOut[channelIndex][:resampledSamplesPerChannel]
for i := range samplesPerChannel {
channelIn[i] = in[(i*channelCount)+channelIndex]
}
if err := d.hybridSilkResampler[channelIndex].Resample(channelIn, channelOut); err != nil {
return err
}
for i := range resampledSamplesPerChannel {
out[(i*channelCount)+channelIndex] = channelOut[i]
}
return nil
}
// addHybridSilk combines the decoded WB SILK contribution with the CELT layer
// after both are represented in the decoder's output-rate domain.
func (d *Decoder) addHybridSilk(
out []float32,
silkPCM []float32,
streamChannelCount int,
outputChannelCount int,
samplesPerChannel int,
) {
for i := range silkPCM {
silkPCM[i] = float32(bitdepth.Float32ToSigned16(silkPCM[i])) / 32768
}
for sample := range samplesPerChannel {
silkIndex := sample * streamChannelCount
outIndex := sample * outputChannelCount
switch {
case streamChannelCount == outputChannelCount:
for channel := range outputChannelCount {