-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdecoder_decode.go
More file actions
534 lines (501 loc) · 15.5 KB
/
decoder_decode.go
File metadata and controls
534 lines (501 loc) · 15.5 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
package gopus
import (
"github.com/thesyncim/gopus/internal/extsupport"
"github.com/thesyncim/gopus/silk"
)
// Decode decodes an Opus packet into float32 PCM samples.
//
// data: Opus packet data, or nil for Packet Loss Concealment (PLC).
// pcm: Output buffer for decoded samples. Must be large enough to hold
// frameSize * frameCount * channels samples, where frameSize and frameCount
// are determined from the packet TOC and frame code.
//
// Returns the number of samples per channel decoded, or an error.
//
// When data is nil, the decoder performs packet loss concealment using
// the last successfully decoded frame parameters. Before the first packet has
// been decoded, cold PLC returns zeroed audio and a nil error.
//
// Buffer sizing: For 60ms frames at 48kHz stereo, pcm must have at least
// 2880 * 2 = 5760 elements. For multi-frame packets (code 1/2/3), the buffer
// must be large enough for all frames combined.
//
// Multi-frame packets (RFC 6716 Section 3.2):
// - Code 0: 1 frame (most common)
// - Code 1: 2 equal-sized frames
// - Code 2: 2 different-sized frames
// - Code 3: Arbitrary number of frames (1-48)
func (d *Decoder) Decode(data []byte, pcm []float32) (int, error) {
return d.decodeFloat32(data, pcm, true)
}
func (d *Decoder) decodeFloat32(data []byte, pcm []float32, clearSoftClipOnPacket bool) (int, error) {
channels := int(d.channels)
sampleRate := int(d.sampleRate)
dredPossible := false
if extsupport.DREDRuntime {
dredPossible = d.dredDecodeSidecarPossible()
if data != nil && len(data) > 0 && dredPossible && d.dredCachedPayloadActive() {
d.invalidateDREDPayloadState()
}
}
if data == nil || len(data) == 0 {
frameSize, err := d.plcOutputFrameSize(len(pcm))
if err != nil {
return 0, err
}
packetFrameSize := int(d.lastFrameSize)
if packetFrameSize <= 0 {
packetFrameSize = frameSize
}
neuralReady := dredPossible && d.dredNeuralConcealmentAvailable()
n := frameSize
usedNeuralConcealment := false
if neuralReady && d.prevMode == ModeSILK && channels >= 1 && channels <= 2 {
n, usedNeuralConcealment, err = d.decodeSILKNeuralPLCInto(pcm, frameSize, plcDecodeState{
packetFrameSize: packetFrameSize,
mode: d.prevMode,
bandwidth: d.lastBandwidth,
packetStereo: d.prevPacketStereo,
useDecoderPLCState: true,
})
}
if err != nil {
return 0, err
}
if !usedNeuralConcealment && neuralReady && sampleRate == 16000 && channels >= 1 && channels <= 2 && d.prevMode != ModeHybrid && d.prevMode != ModeSILK {
if len(pcm) < frameSize*channels {
return 0, ErrBufferTooSmall
}
usedNeuralConcealment = d.applyDREDNeuralConcealment(pcm[:frameSize*channels], frameSize)
}
if !usedNeuralConcealment && dredPossible {
n, usedNeuralConcealment, err = d.decodeDRED48kNeuralPLCInto(pcm, frameSize, plcDecodeState{
packetFrameSize: packetFrameSize,
mode: d.prevMode,
bandwidth: d.lastBandwidth,
packetStereo: d.prevPacketStereo,
useDecoderPLCState: true,
})
} else if !usedNeuralConcealment {
n, err = d.decodePLCChunksInto(pcm, frameSize, plcDecodeState{
packetFrameSize: packetFrameSize,
mode: d.prevMode,
bandwidth: d.lastBandwidth,
packetStereo: d.prevPacketStereo,
useDecoderPLCState: true,
})
}
if err != nil {
return 0, err
}
frameSize = n
if neuralReady && !usedNeuralConcealment && d.prevMode == ModeCELT {
usedNeuralConcealment = d.applyDREDNeuralConcealment(pcm[:frameSize*channels], frameSize)
}
// libopus enables OSCE_MODE_SILK_BBWE during PLC whenever the
// internal sample rate is 16 kHz and the API sample rate is 48 kHz
// (`data == NULL` branch in opus_decoder.c). The gopus equivalent
// gate uses the previous packet's mode/bandwidth as the BWE
// eligibility signal: only SILK WB carries the 16 kHz internal SR
// that BWE expects. Stereo and DRED neural concealment paths are
// intentionally excluded so the BWE never overwrites richer
// concealment output.
//
// LACE/NoLACE does not enhance packet-loss frames in libopus:
// `silk_decode_frame` calls `osce_reset` on the lost branch.
// Keep that state transition here before optional BWE runs on the
// concealed SILK lowband.
if extsupport.OSCERuntime {
packetStereoLocal := d.prevPacketStereo
if d.lastPacketMode == ModeSILK &&
d.lastBandwidth == BandwidthWideband &&
sampleRate == 48000 && d.osceLACEActive() {
d.resetOSCELACEPostfilterState(packetStereoLocal)
}
if !usedNeuralConcealment && d.lastPacketMode == ModeSILK &&
d.lastBandwidth == BandwidthWideband &&
sampleRate == 48000 && d.osceBWEActive() {
d.maybeApplyOSCEBWEPostSilk(pcm[:frameSize*channels], frameSize, ModeSILK, silk.BandwidthWideband, packetStereoLocal)
}
}
d.applyOutputGain(pcm[:frameSize*channels])
d.lastFrameSize = int32(packetFrameSize)
d.lastPacketDuration = int32(frameSize)
d.lastDataLen = 0
if dredPossible && !usedNeuralConcealment && d.dredGoodPacketMarkerActive() {
d.markDREDConcealed()
}
return frameSize, nil
}
if len(data) > d.maxPacketBytes {
return 0, ErrPacketTooLarge
}
tocValue, frameCount, err := packetFrameCount(data)
if err != nil {
return 0, err
}
toc := &tocValue
frameCode := data[0] & 0x03
frameSize := toc.FrameSize
if toc.Mode == ModeSILK || toc.Mode == ModeCELT || toc.Mode == ModeHybrid {
frameSize = packetTOCSamplesPerFrameAtRate(data[0], sampleRate)
}
totalSamples := frameSize * frameCount
if totalSamples > d.maxPacketSamples {
return 0, ErrPacketTooLarge
}
needed := totalSamples * channels
if len(pcm) < needed {
return 0, ErrBufferTooSmall
}
if dredPossible {
if endRawDREDCapture := d.beginDREDRawMonoGoodFrameCapture(toc.Mode); endRawDREDCapture != nil {
defer endRawDREDCapture()
}
}
if frameCode == 0 {
_, err := d.decodeOpusFrameIntoWithQEXT(
pcm,
data[1:],
frameSize,
frameSize,
toc.Mode,
toc.Bandwidth,
toc.Stereo,
nil,
)
if err != nil {
return 0, err
}
d.prevPacketStereo = toc.Stereo
} else {
_, err := d.decodeMultiFrameFloat32(pcm, data, toc, frameCode, frameSize)
if err != nil {
return 0, err
}
}
// OSCE BWE transition bookkeeping: when the current packet does not
// satisfy OSCE_MODE_SILK_BBWE (Hybrid or mono SILK NB/MB), clear the
// previous-BWE-active flag so the next SILK WB packet does not
// erroneously fade in. The SILK-only post-decode hook handles the
// SILK -> SILK cross-fade itself; this catches Hybrid and CELT
// transitions where the SILK helper is not invoked.
if extsupport.OSCERuntime {
d.osceBWEMarkInactiveIfModeIneligible(toc.Mode, toc.Bandwidth, pcm[:totalSamples*channels], totalSamples, toc.Stereo)
}
// OSCE LACE/NoLACE transition bookkeeping: clear the previous-LACE-
// active flag when the current packet bypasses the postfilter (Hybrid
// or CELT). Mirrors libopus `osce_reset` which gets called whenever
// `osce_enhance_frame` exits early (e.g. fs_kHz != 16), priming the
// reset counter so the next LACE-active frame runs the cross-fade.
if extsupport.OSCERuntime {
d.osceLACEMarkInactiveIfModeIneligible(toc.Mode, toc.Bandwidth)
}
d.lastFrameSize = int32(frameSize)
d.lastPacketDuration = int32(totalSamples)
d.lastBandwidth = toc.Bandwidth
d.lastPacketMode = toc.Mode
d.lastDataLen = int32(len(data))
d.clearFECState()
if dredPossible {
if d.dredPayloadScannerActive() {
d.maybeCacheDREDPayload(data)
}
if d.dredGoodPacketMarkerActive() {
if r := d.dredRecoveryState(); r != nil && d.dredNeuralModelsLoaded() {
r.dredRecovery = 0
}
d.markDREDUpdatedPCM(pcm[:totalSamples*channels], totalSamples, toc.Mode)
}
}
d.applyOutputGain(pcm[:totalSamples*channels])
if clearSoftClipOnPacket {
d.clearSoftClipMem()
}
return totalSamples, nil
}
func (d *Decoder) decodeMultiFrameFloat32(pcm []float32, data []byte, toc *TOC, frameCode byte, frameSize int) (int, error) {
channels := int(d.channels)
offsetSamples := 0
var qextPayloads decoderQEXTPayloads
decodeFrame := func(frameIndex int, frameData []byte) error {
var qextPayload []byte
if extsupport.QEXT && !d.ignoreExtensions {
qextPayload = qextPayloads.frame(frameIndex)
}
n, err := d.decodeOpusFrameIntoWithQEXT(
pcm[offsetSamples*channels:],
frameData,
frameSize,
frameSize,
toc.Mode,
toc.Bandwidth,
toc.Stereo,
qextPayload,
)
if err != nil {
return err
}
offsetSamples += n
d.prevPacketStereo = toc.Stereo
return nil
}
switch frameCode {
case 1:
frameDataLen := len(data) - 1
if frameDataLen%2 != 0 {
return 0, ErrInvalidPacket
}
frameLen := frameDataLen / 2
offset := 1
for i := 0; i < 2; i++ {
if offset+frameLen > len(data) {
return 0, ErrInvalidPacket
}
if err := decodeFrame(i, data[offset:offset+frameLen]); err != nil {
return 0, err
}
offset += frameLen
}
case 2:
if len(data) < 2 {
return 0, ErrPacketTooShort
}
frame1Len, bytesRead, err := parseFrameLength(data, 1)
if err != nil {
return 0, err
}
headerLen := 1 + bytesRead
frame2Len := len(data) - headerLen - frame1Len
if frame2Len < 0 {
return 0, ErrInvalidPacket
}
if headerLen+frame1Len > len(data) {
return 0, ErrInvalidPacket
}
if err := decodeFrame(0, data[headerLen:headerLen+frame1Len]); err != nil {
return 0, err
}
offset := headerLen + frame1Len
if offset+frame2Len > len(data) {
return 0, ErrInvalidPacket
}
if err := decodeFrame(1, data[offset:offset+frame2Len]); err != nil {
return 0, err
}
case 3:
if len(data) < 2 {
return 0, ErrPacketTooShort
}
frameCountByte := data[1]
vbr := (frameCountByte & 0x80) != 0
hasPadding := (frameCountByte & 0x40) != 0
m := int(frameCountByte & 0x3F)
if m == 0 || m > 48 {
return 0, ErrInvalidFrameCount
}
offset := 2
padding := 0
if hasPadding {
for {
if offset >= len(data) {
return 0, ErrPacketTooShort
}
padByte := int(data[offset])
offset++
if padByte == 255 {
padding += 254
} else {
padding += padByte
}
if padByte < 255 {
break
}
}
if extsupport.QEXT && !d.ignoreExtensions && toc.Mode != ModeSILK {
if padding > len(data) {
return 0, ErrInvalidPacket
}
qextPayloads.collect(data[len(data)-padding:], m, qextPacketExtensionID)
}
}
if vbr {
var frameLens [48]int
for i := 0; i < m-1; i++ {
frameLen, bytesRead, err := parseFrameLength(data, offset)
if err != nil {
return 0, err
}
offset += bytesRead
frameLens[i] = frameLen
}
frameDataOffset := offset
for i := 0; i < m-1; i++ {
frameLen := frameLens[i]
if frameDataOffset+frameLen > len(data)-padding {
return 0, ErrInvalidPacket
}
if err := decodeFrame(i, data[frameDataOffset:frameDataOffset+frameLen]); err != nil {
return 0, err
}
frameDataOffset += frameLen
}
lastFrameLen := len(data) - frameDataOffset - padding
if lastFrameLen < 0 {
return 0, ErrInvalidPacket
}
if frameDataOffset+lastFrameLen > len(data)-padding {
return 0, ErrInvalidPacket
}
if err := decodeFrame(m-1, data[frameDataOffset:frameDataOffset+lastFrameLen]); err != nil {
return 0, err
}
} else {
frameDataLen := len(data) - offset - padding
if frameDataLen < 0 {
return 0, ErrInvalidPacket
}
if frameDataLen%m != 0 {
return 0, ErrInvalidPacket
}
frameLen := frameDataLen / m
for i := 0; i < m; i++ {
if offset+frameLen > len(data)-padding {
return 0, ErrInvalidPacket
}
if err := decodeFrame(i, data[offset:offset+frameLen]); err != nil {
return 0, err
}
offset += frameLen
}
}
}
return offsetSamples, nil
}
// DecodeWithFEC decodes an Opus packet, optionally recovering a lost frame using FEC.
//
// This mirrors libopus decode_fec semantics: when fec is true, the decoder
// uses in-band LBRR data if present and otherwise falls back to packet loss
// concealment instead of returning a missing-FEC error.
func (d *Decoder) DecodeWithFEC(data []byte, pcm []float32, fec bool) (int, error) {
if !fec {
return d.Decode(data, pcm)
}
sampleRate := int(d.sampleRate)
if data != nil && len(data) > 0 {
toc, frameCount, err := packetFrameCount(data)
if err != nil {
return 0, err
}
requestedFrameSize, err := d.requestedOutputFrameSize(len(pcm))
if err != nil {
return 0, err
}
frameSize := toc.FrameSize
if toc.Mode == ModeSILK || toc.Mode == ModeCELT || toc.Mode == ModeHybrid {
frameSize = packetTOCSamplesPerFrameAtRate(data[0], sampleRate)
}
if frameSize <= 0 {
frameSize = int(d.lastFrameSize)
}
if frameSize <= 0 {
frameSize = sampleRate / 50
}
prevPacketMode := d.lastPacketMode
if requestedFrameSize < frameSize || toc.Mode == ModeCELT || prevPacketMode == ModeCELT {
d.clearFECState()
plcSize, err := d.plcOutputFrameSize(len(pcm))
if err != nil {
return 0, err
}
return d.decodePLCForFEC(pcm, plcSize)
}
d.lastPacketMode = toc.Mode
if toc.Mode == ModeSILK || toc.Mode == ModeHybrid {
firstFrameData, err := extractFirstFramePayload(data, toc)
if err != nil {
return 0, err
}
if !packetHasLBRR(firstFrameData, toc) {
d.clearFECState()
if extsupport.DREDRuntime && d.dredCachedPayloadActive() {
return d.decodePLCForFECWithState(pcm, requestedFrameSize, frameSize, toc.Mode, toc.Bandwidth, toc.Stereo)
}
return d.decodeNoLBRRFECFallback(pcm, requestedFrameSize, frameSize, toc.Mode, toc.Bandwidth, toc.Stereo)
}
d.storeFECData(firstFrameData, toc, frameCount, frameSize)
if n, err := d.decodeFECFrame(pcm, requestedFrameSize); err == nil {
return n, nil
}
d.clearFECState()
}
return d.decodePLCForFECWithState(pcm, requestedFrameSize, frameSize, toc.Mode, toc.Bandwidth, toc.Stereo)
}
d.clearFECState()
frameSize, err := d.plcOutputFrameSize(len(pcm))
if err != nil {
return 0, err
}
return d.decodePLCForFEC(pcm, frameSize)
}
// DecodeInt16 decodes an Opus packet into int16 PCM samples.
func (d *Decoder) DecodeInt16(data []byte, pcm []int16) (int, error) {
channels := int(d.channels)
sampleRate := int(d.sampleRate)
if data == nil || len(data) == 0 {
frameSize, err := d.plcOutputFrameSize(len(pcm))
if err != nil {
return 0, err
}
needed := frameSize * channels
d.ensureScratchPCM(needed)
n, err := d.decodeFloat32(data, d.scratchPCM, false)
if err != nil {
return 0, err
}
float32ToInt16NoSoftClip(pcm, d.scratchPCM, n, channels)
return n, nil
}
if len(data) > d.maxPacketBytes {
return 0, ErrPacketTooLarge
}
if len(pcm) >= d.maxPacketSamples*channels {
d.ensureScratchPCM(d.maxPacketSamples * channels)
n, err := d.decodeFloat32(data, d.scratchPCM, false)
if err != nil {
return 0, err
}
softClipAndFloat32ToInt16(pcm, d.scratchPCM, n, channels, d.softClipMem[:])
return n, nil
}
toc, frameCount, err := packetFrameCount(data)
if err != nil {
return 0, err
}
frameSize := toc.FrameSize
if toc.Mode == ModeSILK || toc.Mode == ModeCELT || toc.Mode == ModeHybrid {
frameSize = packetTOCSamplesPerFrameAtRate(data[0], sampleRate)
}
totalSamples := frameSize * frameCount
if totalSamples > d.maxPacketSamples {
return 0, ErrPacketTooLarge
}
needed := totalSamples * channels
if len(pcm) < needed {
return 0, ErrBufferTooSmall
}
d.ensureScratchPCM(needed)
n, err := d.decodeFloat32(data, d.scratchPCM, false)
if err != nil {
return 0, err
}
softClipAndFloat32ToInt16(pcm, d.scratchPCM, n, channels, d.softClipMem[:])
return n, nil
}
func (d *Decoder) ensureScratchPCM(needed int) {
if cap(d.scratchPCM) < needed {
d.scratchPCM = make([]float32, needed)
return
}
d.scratchPCM = d.scratchPCM[:needed]
}