]> git.sesse.net Git - ffmpeg/blob - libavcodec/opus_silk.c
Merge commit '4476027d93680cd88d2f75ef1cef5b0c276a8704'
[ffmpeg] / libavcodec / opus_silk.c
1 /*
2  * Copyright (c) 2012 Andrew D'Addesio
3  * Copyright (c) 2013-2014 Mozilla Corporation
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * Opus SILK decoder
25  */
26
27 #include <stdint.h>
28
29 #include "opus.h"
30 #include "opustab.h"
31
32 typedef struct SilkFrame {
33     int coded;
34     int log_gain;
35     int16_t nlsf[16];
36     float    lpc[16];
37
38     float output     [2 * SILK_HISTORY];
39     float lpc_history[2 * SILK_HISTORY];
40     int primarylag;
41
42     int prev_voiced;
43 } SilkFrame;
44
45 struct SilkContext {
46     AVCodecContext *avctx;
47     int output_channels;
48
49     int midonly;
50     int subframes;
51     int sflength;
52     int flength;
53     int nlsf_interp_factor;
54
55     enum OpusBandwidth bandwidth;
56     int wb;
57
58     SilkFrame frame[2];
59     float prev_stereo_weights[2];
60     float stereo_weights[2];
61
62     int prev_coded_channels;
63 };
64
65 static inline void silk_stabilize_lsf(int16_t nlsf[16], int order, const uint16_t min_delta[17])
66 {
67     int pass, i;
68     for (pass = 0; pass < 20; pass++) {
69         int k, min_diff = 0;
70         for (i = 0; i < order+1; i++) {
71             int low  = i != 0     ? nlsf[i-1] : 0;
72             int high = i != order ? nlsf[i]   : 32768;
73             int diff = (high - low) - (min_delta[i]);
74
75             if (diff < min_diff) {
76                 min_diff = diff;
77                 k = i;
78
79                 if (pass == 20)
80                     break;
81             }
82         }
83         if (min_diff == 0) /* no issues; stabilized */
84             return;
85
86         /* wiggle one or two LSFs */
87         if (k == 0) {
88             /* repel away from lower bound */
89             nlsf[0] = min_delta[0];
90         } else if (k == order) {
91             /* repel away from higher bound */
92             nlsf[order-1] = 32768 - min_delta[order];
93         } else {
94             /* repel away from current position */
95             int min_center = 0, max_center = 32768, center_val;
96
97             /* lower extent */
98             for (i = 0; i < k; i++)
99                 min_center += min_delta[i];
100             min_center += min_delta[k] >> 1;
101
102             /* upper extent */
103             for (i = order; i > k; i--)
104                 max_center -= min_delta[i];
105             max_center -= min_delta[k] >> 1;
106
107             /* move apart */
108             center_val = nlsf[k - 1] + nlsf[k];
109             center_val = (center_val >> 1) + (center_val & 1); // rounded divide by 2
110             center_val = FFMIN(max_center, FFMAX(min_center, center_val));
111
112             nlsf[k - 1] = center_val - (min_delta[k] >> 1);
113             nlsf[k]     = nlsf[k - 1] + min_delta[k];
114         }
115     }
116
117     /* resort to the fall-back method, the standard method for LSF stabilization */
118
119     /* sort; as the LSFs should be nearly sorted, use insertion sort */
120     for (i = 1; i < order; i++) {
121         int j, value = nlsf[i];
122         for (j = i - 1; j >= 0 && nlsf[j] > value; j--)
123             nlsf[j + 1] = nlsf[j];
124         nlsf[j + 1] = value;
125     }
126
127     /* push forwards to increase distance */
128     if (nlsf[0] < min_delta[0])
129         nlsf[0] = min_delta[0];
130     for (i = 1; i < order; i++)
131         nlsf[i] = FFMAX(nlsf[i], FFMIN(nlsf[i - 1] + min_delta[i], 32767));
132
133     /* push backwards to increase distance */
134     if (nlsf[order-1] > 32768 - min_delta[order])
135         nlsf[order-1] = 32768 - min_delta[order];
136     for (i = order-2; i >= 0; i--)
137         if (nlsf[i] > nlsf[i + 1] - min_delta[i+1])
138             nlsf[i] = nlsf[i + 1] - min_delta[i+1];
139
140     return;
141 }
142
143 static inline int silk_is_lpc_stable(const int16_t lpc[16], int order)
144 {
145     int k, j, DC_resp = 0;
146     int32_t lpc32[2][16];       // Q24
147     int totalinvgain = 1 << 30; // 1.0 in Q30
148     int32_t *row = lpc32[0], *prevrow;
149
150     /* initialize the first row for the Levinson recursion */
151     for (k = 0; k < order; k++) {
152         DC_resp += lpc[k];
153         row[k] = lpc[k] * 4096;
154     }
155
156     if (DC_resp >= 4096)
157         return 0;
158
159     /* check if prediction gain pushes any coefficients too far */
160     for (k = order - 1; 1; k--) {
161         int rc;      // Q31; reflection coefficient
162         int gaindiv; // Q30; inverse of the gain (the divisor)
163         int gain;    // gain for this reflection coefficient
164         int fbits;   // fractional bits used for the gain
165         int error;   // Q29; estimate of the error of our partial estimate of 1/gaindiv
166
167         if (FFABS(row[k]) > 16773022)
168             return 0;
169
170         rc      = -(row[k] * 128);
171         gaindiv = (1 << 30) - MULH(rc, rc);
172
173         totalinvgain = MULH(totalinvgain, gaindiv) << 2;
174         if (k == 0)
175             return (totalinvgain >= 107374);
176
177         /* approximate 1.0/gaindiv */
178         fbits = opus_ilog(gaindiv);
179         gain  = ((1 << 29) - 1) / (gaindiv >> (fbits + 1 - 16)); // Q<fbits-16>
180         error = (1 << 29) - MULL(gaindiv << (15 + 16 - fbits), gain, 16);
181         gain  = ((gain << 16) + (error * gain >> 13));
182
183         /* switch to the next row of the LPC coefficients */
184         prevrow = row;
185         row = lpc32[k & 1];
186
187         for (j = 0; j < k; j++) {
188             int x = prevrow[j] - ROUND_MULL(prevrow[k - j - 1], rc, 31);
189             row[j] = ROUND_MULL(x, gain, fbits);
190         }
191     }
192 }
193
194 static void silk_lsp2poly(const int32_t lsp[16], int32_t pol[16], int half_order)
195 {
196     int i, j;
197
198     pol[0] = 65536; // 1.0 in Q16
199     pol[1] = -lsp[0];
200
201     for (i = 1; i < half_order; i++) {
202         pol[i + 1] = pol[i - 1] * 2 - ROUND_MULL(lsp[2 * i], pol[i], 16);
203         for (j = i; j > 1; j--)
204             pol[j] += pol[j - 2] - ROUND_MULL(lsp[2 * i], pol[j - 1], 16);
205
206         pol[1] -= lsp[2 * i];
207     }
208 }
209
210 static void silk_lsf2lpc(const int16_t nlsf[16], float lpcf[16], int order)
211 {
212     int i, k;
213     int32_t lsp[16];     // Q17; 2*cos(LSF)
214     int32_t p[9], q[9];  // Q16
215     int32_t lpc32[16];   // Q17
216     int16_t lpc[16];     // Q12
217
218     /* convert the LSFs to LSPs, i.e. 2*cos(LSF) */
219     for (k = 0; k < order; k++) {
220         int index = nlsf[k] >> 8;
221         int offset = nlsf[k] & 255;
222         int k2 = (order == 10) ? ff_silk_lsf_ordering_nbmb[k] : ff_silk_lsf_ordering_wb[k];
223
224         /* interpolate and round */
225         lsp[k2]  = ff_silk_cosine[index] * 256;
226         lsp[k2] += (ff_silk_cosine[index + 1] - ff_silk_cosine[index]) * offset;
227         lsp[k2]  = (lsp[k2] + 4) >> 3;
228     }
229
230     silk_lsp2poly(lsp    , p, order >> 1);
231     silk_lsp2poly(lsp + 1, q, order >> 1);
232
233     /* reconstruct A(z) */
234     for (k = 0; k < order>>1; k++) {
235         lpc32[k]         = -p[k + 1] - p[k] - q[k + 1] + q[k];
236         lpc32[order-k-1] = -p[k + 1] - p[k] + q[k + 1] - q[k];
237     }
238
239     /* limit the range of the LPC coefficients to each fit within an int16_t */
240     for (i = 0; i < 10; i++) {
241         int j;
242         unsigned int maxabs = 0;
243         for (j = 0, k = 0; j < order; j++) {
244             unsigned int x = FFABS(lpc32[k]);
245             if (x > maxabs) {
246                 maxabs = x; // Q17
247                 k      = j;
248             }
249         }
250
251         maxabs = (maxabs + 16) >> 5; // convert to Q12
252
253         if (maxabs > 32767) {
254             /* perform bandwidth expansion */
255             unsigned int chirp, chirp_base; // Q16
256             maxabs = FFMIN(maxabs, 163838); // anything above this overflows chirp's numerator
257             chirp_base = chirp = 65470 - ((maxabs - 32767) << 14) / ((maxabs * (k+1)) >> 2);
258
259             for (k = 0; k < order; k++) {
260                 lpc32[k] = ROUND_MULL(lpc32[k], chirp, 16);
261                 chirp    = (chirp_base * chirp + 32768) >> 16;
262             }
263         } else break;
264     }
265
266     if (i == 10) {
267         /* time's up: just clamp */
268         for (k = 0; k < order; k++) {
269             int x = (lpc32[k] + 16) >> 5;
270             lpc[k] = av_clip_int16(x);
271             lpc32[k] = lpc[k] << 5; // shortcut mandated by the spec; drops lower 5 bits
272         }
273     } else {
274         for (k = 0; k < order; k++)
275             lpc[k] = (lpc32[k] + 16) >> 5;
276     }
277
278     /* if the prediction gain causes the LPC filter to become unstable,
279        apply further bandwidth expansion on the Q17 coefficients */
280     for (i = 1; i <= 16 && !silk_is_lpc_stable(lpc, order); i++) {
281         unsigned int chirp, chirp_base;
282         chirp_base = chirp = 65536 - (1 << i);
283
284         for (k = 0; k < order; k++) {
285             lpc32[k] = ROUND_MULL(lpc32[k], chirp, 16);
286             lpc[k]   = (lpc32[k] + 16) >> 5;
287             chirp    = (chirp_base * chirp + 32768) >> 16;
288         }
289     }
290
291     for (i = 0; i < order; i++)
292         lpcf[i] = lpc[i] / 4096.0f;
293 }
294
295 static inline void silk_decode_lpc(SilkContext *s, SilkFrame *frame,
296                                    OpusRangeCoder *rc,
297                                    float lpc_leadin[16], float lpc[16],
298                                    int *lpc_order, int *has_lpc_leadin, int voiced)
299 {
300     int i;
301     int order;                   // order of the LP polynomial; 10 for NB/MB and 16 for WB
302     int8_t  lsf_i1, lsf_i2[16];  // stage-1 and stage-2 codebook indices
303     int16_t lsf_res[16];         // residual as a Q10 value
304     int16_t nlsf[16];            // Q15
305
306     *lpc_order = order = s->wb ? 16 : 10;
307
308     /* obtain LSF stage-1 and stage-2 indices */
309     lsf_i1 = ff_opus_rc_dec_cdf(rc, ff_silk_model_lsf_s1[s->wb][voiced]);
310     for (i = 0; i < order; i++) {
311         int index = s->wb ? ff_silk_lsf_s2_model_sel_wb  [lsf_i1][i] :
312                             ff_silk_lsf_s2_model_sel_nbmb[lsf_i1][i];
313         lsf_i2[i] = ff_opus_rc_dec_cdf(rc, ff_silk_model_lsf_s2[index]) - 4;
314         if (lsf_i2[i] == -4)
315             lsf_i2[i] -= ff_opus_rc_dec_cdf(rc, ff_silk_model_lsf_s2_ext);
316         else if (lsf_i2[i] == 4)
317             lsf_i2[i] += ff_opus_rc_dec_cdf(rc, ff_silk_model_lsf_s2_ext);
318     }
319
320     /* reverse the backwards-prediction step */
321     for (i = order - 1; i >= 0; i--) {
322         int qstep = s->wb ? 9830 : 11796;
323
324         lsf_res[i] = lsf_i2[i] * 1024;
325         if (lsf_i2[i] < 0)      lsf_res[i] += 102;
326         else if (lsf_i2[i] > 0) lsf_res[i] -= 102;
327         lsf_res[i] = (lsf_res[i] * qstep) >> 16;
328
329         if (i + 1 < order) {
330             int weight = s->wb ? ff_silk_lsf_pred_weights_wb  [ff_silk_lsf_weight_sel_wb  [lsf_i1][i]][i] :
331                                  ff_silk_lsf_pred_weights_nbmb[ff_silk_lsf_weight_sel_nbmb[lsf_i1][i]][i];
332             lsf_res[i] += (lsf_res[i+1] * weight) >> 8;
333         }
334     }
335
336     /* reconstruct the NLSF coefficients from the supplied indices */
337     for (i = 0; i < order; i++) {
338         const uint8_t * codebook = s->wb ? ff_silk_lsf_codebook_wb  [lsf_i1] :
339                                            ff_silk_lsf_codebook_nbmb[lsf_i1];
340         int cur, prev, next, weight_sq, weight, ipart, fpart, y, value;
341
342         /* find the weight of the residual */
343         /* TODO: precompute */
344         cur = codebook[i];
345         prev = i ? codebook[i - 1] : 0;
346         next = i + 1 < order ? codebook[i + 1] : 256;
347         weight_sq = (1024 / (cur - prev) + 1024 / (next - cur)) << 16;
348
349         /* approximate square-root with mandated fixed-point arithmetic */
350         ipart = opus_ilog(weight_sq);
351         fpart = (weight_sq >> (ipart-8)) & 127;
352         y = ((ipart & 1) ? 32768 : 46214) >> ((32 - ipart)>>1);
353         weight = y + ((213 * fpart * y) >> 16);
354
355         value = cur * 128 + (lsf_res[i] * 16384) / weight;
356         nlsf[i] = av_clip_uintp2(value, 15);
357     }
358
359     /* stabilize the NLSF coefficients */
360     silk_stabilize_lsf(nlsf, order, s->wb ? ff_silk_lsf_min_spacing_wb :
361                                             ff_silk_lsf_min_spacing_nbmb);
362
363     /* produce an interpolation for the first 2 subframes, */
364     /* and then convert both sets of NLSFs to LPC coefficients */
365     *has_lpc_leadin = 0;
366     if (s->subframes == 4) {
367         int offset = ff_opus_rc_dec_cdf(rc, ff_silk_model_lsf_interpolation_offset);
368         if (offset != 4 && frame->coded) {
369             *has_lpc_leadin = 1;
370             if (offset != 0) {
371                 int16_t nlsf_leadin[16];
372                 for (i = 0; i < order; i++)
373                     nlsf_leadin[i] = frame->nlsf[i] +
374                         ((nlsf[i] - frame->nlsf[i]) * offset >> 2);
375                 silk_lsf2lpc(nlsf_leadin, lpc_leadin, order);
376             } else  /* avoid re-computation for a (roughly) 1-in-4 occurrence */
377                 memcpy(lpc_leadin, frame->lpc, 16 * sizeof(float));
378         } else
379             offset = 4;
380         s->nlsf_interp_factor = offset;
381
382         silk_lsf2lpc(nlsf, lpc, order);
383     } else {
384         s->nlsf_interp_factor = 4;
385         silk_lsf2lpc(nlsf, lpc, order);
386     }
387
388     memcpy(frame->nlsf, nlsf, order * sizeof(nlsf[0]));
389     memcpy(frame->lpc,  lpc,  order * sizeof(lpc[0]));
390 }
391
392 static inline void silk_count_children(OpusRangeCoder *rc, int model, int32_t total,
393                                        int32_t child[2])
394 {
395     if (total != 0) {
396         child[0] = ff_opus_rc_dec_cdf(rc,
397                        ff_silk_model_pulse_location[model] + (((total - 1 + 5) * (total - 1)) >> 1));
398         child[1] = total - child[0];
399     } else {
400         child[0] = 0;
401         child[1] = 0;
402     }
403 }
404
405 static inline void silk_decode_excitation(SilkContext *s, OpusRangeCoder *rc,
406                                           float* excitationf,
407                                           int qoffset_high, int active, int voiced)
408 {
409     int i;
410     uint32_t seed;
411     int shellblocks;
412     int ratelevel;
413     uint8_t pulsecount[20];     // total pulses in each shell block
414     uint8_t lsbcount[20] = {0}; // raw lsbits defined for each pulse in each shell block
415     int32_t excitation[320];    // Q23
416
417     /* excitation parameters */
418     seed = ff_opus_rc_dec_cdf(rc, ff_silk_model_lcg_seed);
419     shellblocks = ff_silk_shell_blocks[s->bandwidth][s->subframes >> 2];
420     ratelevel = ff_opus_rc_dec_cdf(rc, ff_silk_model_exc_rate[voiced]);
421
422     for (i = 0; i < shellblocks; i++) {
423         pulsecount[i] = ff_opus_rc_dec_cdf(rc, ff_silk_model_pulse_count[ratelevel]);
424         if (pulsecount[i] == 17) {
425             while (pulsecount[i] == 17 && ++lsbcount[i] != 10)
426                 pulsecount[i] = ff_opus_rc_dec_cdf(rc, ff_silk_model_pulse_count[9]);
427             if (lsbcount[i] == 10)
428                 pulsecount[i] = ff_opus_rc_dec_cdf(rc, ff_silk_model_pulse_count[10]);
429         }
430     }
431
432     /* decode pulse locations using PVQ */
433     for (i = 0; i < shellblocks; i++) {
434         if (pulsecount[i] != 0) {
435             int a, b, c, d;
436             int32_t * location = excitation + 16*i;
437             int32_t branch[4][2];
438             branch[0][0] = pulsecount[i];
439
440             /* unrolled tail recursion */
441             for (a = 0; a < 1; a++) {
442                 silk_count_children(rc, 0, branch[0][a], branch[1]);
443                 for (b = 0; b < 2; b++) {
444                     silk_count_children(rc, 1, branch[1][b], branch[2]);
445                     for (c = 0; c < 2; c++) {
446                         silk_count_children(rc, 2, branch[2][c], branch[3]);
447                         for (d = 0; d < 2; d++) {
448                             silk_count_children(rc, 3, branch[3][d], location);
449                             location += 2;
450                         }
451                     }
452                 }
453             }
454         } else
455             memset(excitation + 16*i, 0, 16*sizeof(int32_t));
456     }
457
458     /* decode least significant bits */
459     for (i = 0; i < shellblocks << 4; i++) {
460         int bit;
461         for (bit = 0; bit < lsbcount[i >> 4]; bit++)
462             excitation[i] = (excitation[i] << 1) |
463                             ff_opus_rc_dec_cdf(rc, ff_silk_model_excitation_lsb);
464     }
465
466     /* decode signs */
467     for (i = 0; i < shellblocks << 4; i++) {
468         if (excitation[i] != 0) {
469             int sign = ff_opus_rc_dec_cdf(rc, ff_silk_model_excitation_sign[active +
470                                          voiced][qoffset_high][FFMIN(pulsecount[i >> 4], 6)]);
471             if (sign == 0)
472                 excitation[i] *= -1;
473         }
474     }
475
476     /* assemble the excitation */
477     for (i = 0; i < shellblocks << 4; i++) {
478         int value = excitation[i];
479         excitation[i] = value * 256 | ff_silk_quant_offset[voiced][qoffset_high];
480         if (value < 0)      excitation[i] += 20;
481         else if (value > 0) excitation[i] -= 20;
482
483         /* invert samples pseudorandomly */
484         seed = 196314165 * seed + 907633515;
485         if (seed & 0x80000000)
486             excitation[i] *= -1;
487         seed += value;
488
489         excitationf[i] = excitation[i] / 8388608.0f;
490     }
491 }
492
493 /** Maximum residual history according to 4.2.7.6.1 */
494 #define SILK_MAX_LAG  (288 + LTP_ORDER / 2)
495
496 /** Order of the LTP filter */
497 #define LTP_ORDER 5
498
499 static void silk_decode_frame(SilkContext *s, OpusRangeCoder *rc,
500                               int frame_num, int channel, int coded_channels, int active, int active1)
501 {
502     /* per frame */
503     int voiced;       // combines with active to indicate inactive, active, or active+voiced
504     int qoffset_high;
505     int order;                             // order of the LPC coefficients
506     float lpc_leadin[16], lpc_body[16], residual[SILK_MAX_LAG + SILK_HISTORY];
507     int has_lpc_leadin;
508     float ltpscale;
509
510     /* per subframe */
511     struct {
512         float gain;
513         int pitchlag;
514         float ltptaps[5];
515     } sf[4];
516
517     SilkFrame * const frame = s->frame + channel;
518
519     int i;
520
521     /* obtain stereo weights */
522     if (coded_channels == 2 && channel == 0) {
523         int n, wi[2], ws[2], w[2];
524         n     = ff_opus_rc_dec_cdf(rc, ff_silk_model_stereo_s1);
525         wi[0] = ff_opus_rc_dec_cdf(rc, ff_silk_model_stereo_s2) + 3 * (n / 5);
526         ws[0] = ff_opus_rc_dec_cdf(rc, ff_silk_model_stereo_s3);
527         wi[1] = ff_opus_rc_dec_cdf(rc, ff_silk_model_stereo_s2) + 3 * (n % 5);
528         ws[1] = ff_opus_rc_dec_cdf(rc, ff_silk_model_stereo_s3);
529
530         for (i = 0; i < 2; i++)
531             w[i] = ff_silk_stereo_weights[wi[i]] +
532                    (((ff_silk_stereo_weights[wi[i] + 1] - ff_silk_stereo_weights[wi[i]]) * 6554) >> 16)
533                     * (ws[i]*2 + 1);
534
535         s->stereo_weights[0] = (w[0] - w[1]) / 8192.0;
536         s->stereo_weights[1] = w[1]          / 8192.0;
537
538         /* and read the mid-only flag */
539         s->midonly = active1 ? 0 : ff_opus_rc_dec_cdf(rc, ff_silk_model_mid_only);
540     }
541
542     /* obtain frame type */
543     if (!active) {
544         qoffset_high = ff_opus_rc_dec_cdf(rc, ff_silk_model_frame_type_inactive);
545         voiced = 0;
546     } else {
547         int type = ff_opus_rc_dec_cdf(rc, ff_silk_model_frame_type_active);
548         qoffset_high = type & 1;
549         voiced = type >> 1;
550     }
551
552     /* obtain subframe quantization gains */
553     for (i = 0; i < s->subframes; i++) {
554         int log_gain;     //Q7
555         int ipart, fpart, lingain;
556
557         if (i == 0 && (frame_num == 0 || !frame->coded)) {
558             /* gain is coded absolute */
559             int x = ff_opus_rc_dec_cdf(rc, ff_silk_model_gain_highbits[active + voiced]);
560             log_gain = (x<<3) | ff_opus_rc_dec_cdf(rc, ff_silk_model_gain_lowbits);
561
562             if (frame->coded)
563                 log_gain = FFMAX(log_gain, frame->log_gain - 16);
564         } else {
565             /* gain is coded relative */
566             int delta_gain = ff_opus_rc_dec_cdf(rc, ff_silk_model_gain_delta);
567             log_gain = av_clip_uintp2(FFMAX((delta_gain<<1) - 16,
568                                      frame->log_gain + delta_gain - 4), 6);
569         }
570
571         frame->log_gain = log_gain;
572
573         /* approximate 2**(x/128) with a Q7 (i.e. non-integer) input */
574         log_gain = (log_gain * 0x1D1C71 >> 16) + 2090;
575         ipart = log_gain >> 7;
576         fpart = log_gain & 127;
577         lingain = (1 << ipart) + ((-174 * fpart * (128-fpart) >>16) + fpart) * ((1<<ipart) >> 7);
578         sf[i].gain = lingain / 65536.0f;
579     }
580
581     /* obtain LPC filter coefficients */
582     silk_decode_lpc(s, frame, rc, lpc_leadin, lpc_body, &order, &has_lpc_leadin, voiced);
583
584     /* obtain pitch lags, if this is a voiced frame */
585     if (voiced) {
586         int lag_absolute = (!frame_num || !frame->prev_voiced);
587         int primarylag;         // primary pitch lag for the entire SILK frame
588         int ltpfilter;
589         const int8_t * offsets;
590
591         if (!lag_absolute) {
592             int delta = ff_opus_rc_dec_cdf(rc, ff_silk_model_pitch_delta);
593             if (delta)
594                 primarylag = frame->primarylag + delta - 9;
595             else
596                 lag_absolute = 1;
597         }
598
599         if (lag_absolute) {
600             /* primary lag is coded absolute */
601             int highbits, lowbits;
602             static const uint16_t * const model[] = {
603                 ff_silk_model_pitch_lowbits_nb, ff_silk_model_pitch_lowbits_mb,
604                 ff_silk_model_pitch_lowbits_wb
605             };
606             highbits = ff_opus_rc_dec_cdf(rc, ff_silk_model_pitch_highbits);
607             lowbits  = ff_opus_rc_dec_cdf(rc, model[s->bandwidth]);
608
609             primarylag = ff_silk_pitch_min_lag[s->bandwidth] +
610                          highbits*ff_silk_pitch_scale[s->bandwidth] + lowbits;
611         }
612         frame->primarylag = primarylag;
613
614         if (s->subframes == 2)
615             offsets = (s->bandwidth == OPUS_BANDWIDTH_NARROWBAND)
616                      ? ff_silk_pitch_offset_nb10ms[ff_opus_rc_dec_cdf(rc,
617                                                 ff_silk_model_pitch_contour_nb10ms)]
618                      : ff_silk_pitch_offset_mbwb10ms[ff_opus_rc_dec_cdf(rc,
619                                                 ff_silk_model_pitch_contour_mbwb10ms)];
620         else
621             offsets = (s->bandwidth == OPUS_BANDWIDTH_NARROWBAND)
622                      ? ff_silk_pitch_offset_nb20ms[ff_opus_rc_dec_cdf(rc,
623                                                 ff_silk_model_pitch_contour_nb20ms)]
624                      : ff_silk_pitch_offset_mbwb20ms[ff_opus_rc_dec_cdf(rc,
625                                                 ff_silk_model_pitch_contour_mbwb20ms)];
626
627         for (i = 0; i < s->subframes; i++)
628             sf[i].pitchlag = av_clip(primarylag + offsets[i],
629                                      ff_silk_pitch_min_lag[s->bandwidth],
630                                      ff_silk_pitch_max_lag[s->bandwidth]);
631
632         /* obtain LTP filter coefficients */
633         ltpfilter = ff_opus_rc_dec_cdf(rc, ff_silk_model_ltp_filter);
634         for (i = 0; i < s->subframes; i++) {
635             int index, j;
636             static const uint16_t * const filter_sel[] = {
637                 ff_silk_model_ltp_filter0_sel, ff_silk_model_ltp_filter1_sel,
638                 ff_silk_model_ltp_filter2_sel
639             };
640             static const int8_t (* const filter_taps[])[5] = {
641                 ff_silk_ltp_filter0_taps, ff_silk_ltp_filter1_taps, ff_silk_ltp_filter2_taps
642             };
643             index = ff_opus_rc_dec_cdf(rc, filter_sel[ltpfilter]);
644             for (j = 0; j < 5; j++)
645                 sf[i].ltptaps[j] = filter_taps[ltpfilter][index][j] / 128.0f;
646         }
647     }
648
649     /* obtain LTP scale factor */
650     if (voiced && frame_num == 0)
651         ltpscale = ff_silk_ltp_scale_factor[ff_opus_rc_dec_cdf(rc,
652                                          ff_silk_model_ltp_scale_index)] / 16384.0f;
653     else ltpscale = 15565.0f/16384.0f;
654
655     /* generate the excitation signal for the entire frame */
656     silk_decode_excitation(s, rc, residual + SILK_MAX_LAG, qoffset_high,
657                            active, voiced);
658
659     /* skip synthesising the side channel if we want mono-only */
660     if (s->output_channels == channel)
661         return;
662
663     /* generate the output signal */
664     for (i = 0; i < s->subframes; i++) {
665         const float * lpc_coeff = (i < 2 && has_lpc_leadin) ? lpc_leadin : lpc_body;
666         float *dst    = frame->output      + SILK_HISTORY + i * s->sflength;
667         float *resptr = residual           + SILK_MAX_LAG + i * s->sflength;
668         float *lpc    = frame->lpc_history + SILK_HISTORY + i * s->sflength;
669         float sum;
670         int j, k;
671
672         if (voiced) {
673             int out_end;
674             float scale;
675
676             if (i < 2 || s->nlsf_interp_factor == 4) {
677                 out_end = -i * s->sflength;
678                 scale   = ltpscale;
679             } else {
680                 out_end = -(i - 2) * s->sflength;
681                 scale   = 1.0f;
682             }
683
684             /* when the LPC coefficients change, a re-whitening filter is used */
685             /* to produce a residual that accounts for the change */
686             for (j = - sf[i].pitchlag - LTP_ORDER/2; j < out_end; j++) {
687                 sum = dst[j];
688                 for (k = 0; k < order; k++)
689                     sum -= lpc_coeff[k] * dst[j - k - 1];
690                 resptr[j] = av_clipf(sum, -1.0f, 1.0f) * scale / sf[i].gain;
691             }
692
693             if (out_end) {
694                 float rescale = sf[i-1].gain / sf[i].gain;
695                 for (j = out_end; j < 0; j++)
696                     resptr[j] *= rescale;
697             }
698
699             /* LTP synthesis */
700             for (j = 0; j < s->sflength; j++) {
701                 sum = resptr[j];
702                 for (k = 0; k < LTP_ORDER; k++)
703                     sum += sf[i].ltptaps[k] * resptr[j - sf[i].pitchlag + LTP_ORDER/2 - k];
704                 resptr[j] = sum;
705             }
706         }
707
708         /* LPC synthesis */
709         for (j = 0; j < s->sflength; j++) {
710             sum = resptr[j] * sf[i].gain;
711             for (k = 1; k <= order; k++)
712                 sum += lpc_coeff[k - 1] * lpc[j - k];
713
714             lpc[j] = sum;
715             dst[j] = av_clipf(sum, -1.0f, 1.0f);
716         }
717     }
718
719     frame->prev_voiced = voiced;
720     memmove(frame->lpc_history, frame->lpc_history + s->flength, SILK_HISTORY * sizeof(float));
721     memmove(frame->output,      frame->output      + s->flength, SILK_HISTORY * sizeof(float));
722
723     frame->coded = 1;
724 }
725
726 static void silk_unmix_ms(SilkContext *s, float *l, float *r)
727 {
728     float *mid    = s->frame[0].output + SILK_HISTORY - s->flength;
729     float *side   = s->frame[1].output + SILK_HISTORY - s->flength;
730     float w0_prev = s->prev_stereo_weights[0];
731     float w1_prev = s->prev_stereo_weights[1];
732     float w0      = s->stereo_weights[0];
733     float w1      = s->stereo_weights[1];
734     int n1        = ff_silk_stereo_interp_len[s->bandwidth];
735     int i;
736
737     for (i = 0; i < n1; i++) {
738         float interp0 = w0_prev + i * (w0 - w0_prev) / n1;
739         float interp1 = w1_prev + i * (w1 - w1_prev) / n1;
740         float p0      = 0.25 * (mid[i - 2] + 2 * mid[i - 1] + mid[i]);
741
742         l[i] = av_clipf((1 + interp1) * mid[i - 1] + side[i - 1] + interp0 * p0, -1.0, 1.0);
743         r[i] = av_clipf((1 - interp1) * mid[i - 1] - side[i - 1] - interp0 * p0, -1.0, 1.0);
744     }
745
746     for (; i < s->flength; i++) {
747         float p0 = 0.25 * (mid[i - 2] + 2 * mid[i - 1] + mid[i]);
748
749         l[i] = av_clipf((1 + w1) * mid[i - 1] + side[i - 1] + w0 * p0, -1.0, 1.0);
750         r[i] = av_clipf((1 - w1) * mid[i - 1] - side[i - 1] - w0 * p0, -1.0, 1.0);
751     }
752
753     memcpy(s->prev_stereo_weights, s->stereo_weights, sizeof(s->stereo_weights));
754 }
755
756 static void silk_flush_frame(SilkFrame *frame)
757 {
758     if (!frame->coded)
759         return;
760
761     memset(frame->output,      0, sizeof(frame->output));
762     memset(frame->lpc_history, 0, sizeof(frame->lpc_history));
763
764     memset(frame->lpc,  0, sizeof(frame->lpc));
765     memset(frame->nlsf, 0, sizeof(frame->nlsf));
766
767     frame->log_gain = 0;
768
769     frame->primarylag  = 0;
770     frame->prev_voiced = 0;
771     frame->coded       = 0;
772 }
773
774 int ff_silk_decode_superframe(SilkContext *s, OpusRangeCoder *rc,
775                               float *output[2],
776                               enum OpusBandwidth bandwidth,
777                               int coded_channels,
778                               int duration_ms)
779 {
780     int active[2][6], redundancy[2];
781     int nb_frames, i, j;
782
783     if (bandwidth > OPUS_BANDWIDTH_WIDEBAND ||
784         coded_channels > 2 || duration_ms > 60) {
785         av_log(s->avctx, AV_LOG_ERROR, "Invalid parameters passed "
786                "to the SILK decoder.\n");
787         return AVERROR(EINVAL);
788     }
789
790     nb_frames = 1 + (duration_ms > 20) + (duration_ms > 40);
791     s->subframes = duration_ms / nb_frames / 5;         // 5ms subframes
792     s->sflength  = 20 * (bandwidth + 2);
793     s->flength   = s->sflength * s->subframes;
794     s->bandwidth = bandwidth;
795     s->wb        = bandwidth == OPUS_BANDWIDTH_WIDEBAND;
796
797     /* make sure to flush the side channel when switching from mono to stereo */
798     if (coded_channels > s->prev_coded_channels)
799         silk_flush_frame(&s->frame[1]);
800     s->prev_coded_channels = coded_channels;
801
802     /* read the LP-layer header bits */
803     for (i = 0; i < coded_channels; i++) {
804         for (j = 0; j < nb_frames; j++)
805             active[i][j] = ff_opus_rc_dec_log(rc, 1);
806
807         redundancy[i] = ff_opus_rc_dec_log(rc, 1);
808         if (redundancy[i]) {
809             avpriv_report_missing_feature(s->avctx, "LBRR frames");
810             return AVERROR_PATCHWELCOME;
811         }
812     }
813
814     for (i = 0; i < nb_frames; i++) {
815         for (j = 0; j < coded_channels && !s->midonly; j++)
816             silk_decode_frame(s, rc, i, j, coded_channels, active[j][i], active[1][i]);
817
818         /* reset the side channel if it is not coded */
819         if (s->midonly && s->frame[1].coded)
820             silk_flush_frame(&s->frame[1]);
821
822         if (coded_channels == 1 || s->output_channels == 1) {
823             for (j = 0; j < s->output_channels; j++) {
824                 memcpy(output[j] + i * s->flength,
825                        s->frame[0].output + SILK_HISTORY - s->flength - 2,
826                        s->flength * sizeof(float));
827             }
828         } else {
829             silk_unmix_ms(s, output[0] + i * s->flength, output[1] + i * s->flength);
830         }
831
832         s->midonly        = 0;
833     }
834
835     return nb_frames * s->flength;
836 }
837
838 void ff_silk_free(SilkContext **ps)
839 {
840     av_freep(ps);
841 }
842
843 void ff_silk_flush(SilkContext *s)
844 {
845     silk_flush_frame(&s->frame[0]);
846     silk_flush_frame(&s->frame[1]);
847
848     memset(s->prev_stereo_weights, 0, sizeof(s->prev_stereo_weights));
849 }
850
851 int ff_silk_init(AVCodecContext *avctx, SilkContext **ps, int output_channels)
852 {
853     SilkContext *s;
854
855     if (output_channels != 1 && output_channels != 2) {
856         av_log(avctx, AV_LOG_ERROR, "Invalid number of output channels: %d\n",
857                output_channels);
858         return AVERROR(EINVAL);
859     }
860
861     s = av_mallocz(sizeof(*s));
862     if (!s)
863         return AVERROR(ENOMEM);
864
865     s->avctx           = avctx;
866     s->output_channels = output_channels;
867
868     ff_silk_flush(s);
869
870     *ps = s;
871
872     return 0;
873 }