]> git.sesse.net Git - ffmpeg/blob - libavcodec/opus_celt.c
opus_celt: Fix arithmetic overflow (per RFC8251)
[ffmpeg] / libavcodec / opus_celt.c
1 /*
2  * Copyright (c) 2012 Andrew D'Addesio
3  * Copyright (c) 2013-2014 Mozilla Corporation
4  * Copyright (c) 2016 Rostislav Pehlivanov <atomnuker@gmail.com>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * Opus CELT decoder
26  */
27
28 #include "opus_celt.h"
29 #include "opustab.h"
30 #include "opus_pvq.h"
31
32 /* Use the 2D z-transform to apply prediction in both the time domain (alpha)
33  * and the frequency domain (beta) */
34 static void celt_decode_coarse_energy(CeltFrame *f, OpusRangeCoder *rc)
35 {
36     int i, j;
37     float prev[2] = { 0 };
38     float alpha = ff_celt_alpha_coef[f->size];
39     float beta  = ff_celt_beta_coef[f->size];
40     const uint8_t *model = ff_celt_coarse_energy_dist[f->size][0];
41
42     /* intra frame */
43     if (opus_rc_tell(rc) + 3 <= f->framebits && ff_opus_rc_dec_log(rc, 3)) {
44         alpha = 0.0f;
45         beta  = 1.0f - (4915.0f/32768.0f);
46         model = ff_celt_coarse_energy_dist[f->size][1];
47     }
48
49     for (i = 0; i < CELT_MAX_BANDS; i++) {
50         for (j = 0; j < f->channels; j++) {
51             CeltBlock *block = &f->block[j];
52             float value;
53             int available;
54
55             if (i < f->start_band || i >= f->end_band) {
56                 block->energy[i] = 0.0;
57                 continue;
58             }
59
60             available = f->framebits - opus_rc_tell(rc);
61             if (available >= 15) {
62                 /* decode using a Laplace distribution */
63                 int k = FFMIN(i, 20) << 1;
64                 value = ff_opus_rc_dec_laplace(rc, model[k] << 7, model[k+1] << 6);
65             } else if (available >= 2) {
66                 int x = ff_opus_rc_dec_cdf(rc, ff_celt_model_energy_small);
67                 value = (x>>1) ^ -(x&1);
68             } else if (available >= 1) {
69                 value = -(float)ff_opus_rc_dec_log(rc, 1);
70             } else value = -1;
71
72             block->energy[i] = FFMAX(-9.0f, block->energy[i]) * alpha + prev[j] + value;
73             prev[j] += beta * value;
74         }
75     }
76 }
77
78 static void celt_decode_fine_energy(CeltFrame *f, OpusRangeCoder *rc)
79 {
80     int i;
81     for (i = f->start_band; i < f->end_band; i++) {
82         int j;
83         if (!f->fine_bits[i])
84             continue;
85
86         for (j = 0; j < f->channels; j++) {
87             CeltBlock *block = &f->block[j];
88             int q2;
89             float offset;
90             q2 = ff_opus_rc_get_raw(rc, f->fine_bits[i]);
91             offset = (q2 + 0.5f) * (1 << (14 - f->fine_bits[i])) / 16384.0f - 0.5f;
92             block->energy[i] += offset;
93         }
94     }
95 }
96
97 static void celt_decode_final_energy(CeltFrame *f, OpusRangeCoder *rc)
98 {
99     int priority, i, j;
100     int bits_left = f->framebits - opus_rc_tell(rc);
101
102     for (priority = 0; priority < 2; priority++) {
103         for (i = f->start_band; i < f->end_band && bits_left >= f->channels; i++) {
104             if (f->fine_priority[i] != priority || f->fine_bits[i] >= CELT_MAX_FINE_BITS)
105                 continue;
106
107             for (j = 0; j < f->channels; j++) {
108                 int q2;
109                 float offset;
110                 q2 = ff_opus_rc_get_raw(rc, 1);
111                 offset = (q2 - 0.5f) * (1 << (14 - f->fine_bits[i] - 1)) / 16384.0f;
112                 f->block[j].energy[i] += offset;
113                 bits_left--;
114             }
115         }
116     }
117 }
118
119 static void celt_decode_tf_changes(CeltFrame *f, OpusRangeCoder *rc)
120 {
121     int i, diff = 0, tf_select = 0, tf_changed = 0, tf_select_bit;
122     int consumed, bits = f->transient ? 2 : 4;
123
124     consumed = opus_rc_tell(rc);
125     tf_select_bit = (f->size != 0 && consumed+bits+1 <= f->framebits);
126
127     for (i = f->start_band; i < f->end_band; i++) {
128         if (consumed+bits+tf_select_bit <= f->framebits) {
129             diff ^= ff_opus_rc_dec_log(rc, bits);
130             consumed = opus_rc_tell(rc);
131             tf_changed |= diff;
132         }
133         f->tf_change[i] = diff;
134         bits = f->transient ? 4 : 5;
135     }
136
137     if (tf_select_bit && ff_celt_tf_select[f->size][f->transient][0][tf_changed] !=
138                          ff_celt_tf_select[f->size][f->transient][1][tf_changed])
139         tf_select = ff_opus_rc_dec_log(rc, 1);
140
141     for (i = f->start_band; i < f->end_band; i++) {
142         f->tf_change[i] = ff_celt_tf_select[f->size][f->transient][tf_select][f->tf_change[i]];
143     }
144 }
145
146 static void celt_decode_allocation(CeltFrame *f, OpusRangeCoder *rc)
147 {
148     // approx. maximum bit allocation for each band before boost/trim
149     int cap[CELT_MAX_BANDS];
150     int boost[CELT_MAX_BANDS];
151     int threshold[CELT_MAX_BANDS];
152     int bits1[CELT_MAX_BANDS];
153     int bits2[CELT_MAX_BANDS];
154     int trim_offset[CELT_MAX_BANDS];
155
156     int skip_start_band = f->start_band;
157     int dynalloc       = 6;
158     int alloctrim      = 5;
159     int extrabits      = 0;
160
161     int skip_bit             = 0;
162     int intensity_stereo_bit = 0;
163     int dual_stereo_bit      = 0;
164
165     int remaining, bandbits;
166     int low, high, total, done;
167     int totalbits;
168     int consumed;
169     int i, j;
170
171     consumed = opus_rc_tell(rc);
172
173     /* obtain spread flag */
174     f->spread = CELT_SPREAD_NORMAL;
175     if (consumed + 4 <= f->framebits)
176         f->spread = ff_opus_rc_dec_cdf(rc, ff_celt_model_spread);
177
178     /* generate static allocation caps */
179     for (i = 0; i < CELT_MAX_BANDS; i++) {
180         cap[i] = (ff_celt_static_caps[f->size][f->channels - 1][i] + 64)
181                  * ff_celt_freq_range[i] << (f->channels - 1) << f->size >> 2;
182     }
183
184     /* obtain band boost */
185     totalbits = f->framebits << 3; // convert to 1/8 bits
186     consumed = opus_rc_tell_frac(rc);
187     for (i = f->start_band; i < f->end_band; i++) {
188         int quanta, band_dynalloc;
189
190         boost[i] = 0;
191
192         quanta = ff_celt_freq_range[i] << (f->channels - 1) << f->size;
193         quanta = FFMIN(quanta << 3, FFMAX(6 << 3, quanta));
194         band_dynalloc = dynalloc;
195         while (consumed + (band_dynalloc<<3) < totalbits && boost[i] < cap[i]) {
196             int add = ff_opus_rc_dec_log(rc, band_dynalloc);
197             consumed = opus_rc_tell_frac(rc);
198             if (!add)
199                 break;
200
201             boost[i]     += quanta;
202             totalbits    -= quanta;
203             band_dynalloc = 1;
204         }
205         /* dynalloc is more likely to occur if it's already been used for earlier bands */
206         if (boost[i])
207             dynalloc = FFMAX(2, dynalloc - 1);
208     }
209
210     /* obtain allocation trim */
211     if (consumed + (6 << 3) <= totalbits)
212         alloctrim = ff_opus_rc_dec_cdf(rc, ff_celt_model_alloc_trim);
213
214     /* anti-collapse bit reservation */
215     totalbits = (f->framebits << 3) - opus_rc_tell_frac(rc) - 1;
216     f->anticollapse_needed = 0;
217     if (f->blocks > 1 && f->size >= 2 &&
218         totalbits >= ((f->size + 2) << 3))
219         f->anticollapse_needed = 1 << 3;
220     totalbits -= f->anticollapse_needed;
221
222     /* band skip bit reservation */
223     if (totalbits >= 1 << 3)
224         skip_bit = 1 << 3;
225     totalbits -= skip_bit;
226
227     /* intensity/dual stereo bit reservation */
228     if (f->channels == 2) {
229         intensity_stereo_bit = ff_celt_log2_frac[f->end_band - f->start_band];
230         if (intensity_stereo_bit <= totalbits) {
231             totalbits -= intensity_stereo_bit;
232             if (totalbits >= 1 << 3) {
233                 dual_stereo_bit = 1 << 3;
234                 totalbits -= 1 << 3;
235             }
236         } else
237             intensity_stereo_bit = 0;
238     }
239
240     for (i = f->start_band; i < f->end_band; i++) {
241         int trim     = alloctrim - 5 - f->size;
242         int band     = ff_celt_freq_range[i] * (f->end_band - i - 1);
243         int duration = f->size + 3;
244         int scale    = duration + f->channels - 1;
245
246         /* PVQ minimum allocation threshold, below this value the band is
247          * skipped */
248         threshold[i] = FFMAX(3 * ff_celt_freq_range[i] << duration >> 4,
249                              f->channels << 3);
250
251         trim_offset[i] = trim * (band << scale) >> 6;
252
253         if (ff_celt_freq_range[i] << f->size == 1)
254             trim_offset[i] -= f->channels << 3;
255     }
256
257     /* bisection */
258     low  = 1;
259     high = CELT_VECTORS - 1;
260     while (low <= high) {
261         int center = (low + high) >> 1;
262         done = total = 0;
263
264         for (i = f->end_band - 1; i >= f->start_band; i--) {
265             bandbits = ff_celt_freq_range[i] * ff_celt_static_alloc[center][i]
266                        << (f->channels - 1) << f->size >> 2;
267
268             if (bandbits)
269                 bandbits = FFMAX(0, bandbits + trim_offset[i]);
270             bandbits += boost[i];
271
272             if (bandbits >= threshold[i] || done) {
273                 done = 1;
274                 total += FFMIN(bandbits, cap[i]);
275             } else if (bandbits >= f->channels << 3)
276                 total += f->channels << 3;
277         }
278
279         if (total > totalbits)
280             high = center - 1;
281         else
282             low = center + 1;
283     }
284     high = low--;
285
286     for (i = f->start_band; i < f->end_band; i++) {
287         bits1[i] = ff_celt_freq_range[i] * ff_celt_static_alloc[low][i]
288                    << (f->channels - 1) << f->size >> 2;
289         bits2[i] = high >= CELT_VECTORS ? cap[i] :
290                    ff_celt_freq_range[i] * ff_celt_static_alloc[high][i]
291                    << (f->channels - 1) << f->size >> 2;
292
293         if (bits1[i])
294             bits1[i] = FFMAX(0, bits1[i] + trim_offset[i]);
295         if (bits2[i])
296             bits2[i] = FFMAX(0, bits2[i] + trim_offset[i]);
297         if (low)
298             bits1[i] += boost[i];
299         bits2[i] += boost[i];
300
301         if (boost[i])
302             skip_start_band = i;
303         bits2[i] = FFMAX(0, bits2[i] - bits1[i]);
304     }
305
306     /* bisection */
307     low  = 0;
308     high = 1 << CELT_ALLOC_STEPS;
309     for (i = 0; i < CELT_ALLOC_STEPS; i++) {
310         int center = (low + high) >> 1;
311         done = total = 0;
312
313         for (j = f->end_band - 1; j >= f->start_band; j--) {
314             bandbits = bits1[j] + (center * bits2[j] >> CELT_ALLOC_STEPS);
315
316             if (bandbits >= threshold[j] || done) {
317                 done = 1;
318                 total += FFMIN(bandbits, cap[j]);
319             } else if (bandbits >= f->channels << 3)
320                 total += f->channels << 3;
321         }
322         if (total > totalbits)
323             high = center;
324         else
325             low = center;
326     }
327
328     done = total = 0;
329     for (i = f->end_band - 1; i >= f->start_band; i--) {
330         bandbits = bits1[i] + (low * bits2[i] >> CELT_ALLOC_STEPS);
331
332         if (bandbits >= threshold[i] || done)
333             done = 1;
334         else
335             bandbits = (bandbits >= f->channels << 3) ?
336                        f->channels << 3 : 0;
337
338         bandbits     = FFMIN(bandbits, cap[i]);
339         f->pulses[i] = bandbits;
340         total      += bandbits;
341     }
342
343     /* band skipping */
344     for (f->coded_bands = f->end_band; ; f->coded_bands--) {
345         int allocation;
346         j = f->coded_bands - 1;
347
348         if (j == skip_start_band) {
349             /* all remaining bands are not skipped */
350             totalbits += skip_bit;
351             break;
352         }
353
354         /* determine the number of bits available for coding "do not skip" markers */
355         remaining   = totalbits - total;
356         bandbits    = remaining / (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]);
357         remaining  -= bandbits  * (ff_celt_freq_bands[j+1] - ff_celt_freq_bands[f->start_band]);
358         allocation  = f->pulses[j] + bandbits * ff_celt_freq_range[j]
359                       + FFMAX(0, remaining - (ff_celt_freq_bands[j] - ff_celt_freq_bands[f->start_band]));
360
361         /* a "do not skip" marker is only coded if the allocation is
362            above the chosen threshold */
363         if (allocation >= FFMAX(threshold[j], (f->channels + 1) <<3 )) {
364             if (ff_opus_rc_dec_log(rc, 1))
365                 break;
366
367             total      += 1 << 3;
368             allocation -= 1 << 3;
369         }
370
371         /* the band is skipped, so reclaim its bits */
372         total -= f->pulses[j];
373         if (intensity_stereo_bit) {
374             total -= intensity_stereo_bit;
375             intensity_stereo_bit = ff_celt_log2_frac[j - f->start_band];
376             total += intensity_stereo_bit;
377         }
378
379         total += f->pulses[j] = (allocation >= f->channels << 3) ?
380                               f->channels << 3 : 0;
381     }
382
383     /* obtain stereo flags */
384     f->intensity_stereo = 0;
385     f->dual_stereo      = 0;
386     if (intensity_stereo_bit)
387         f->intensity_stereo = f->start_band +
388                           ff_opus_rc_dec_uint(rc, f->coded_bands + 1 - f->start_band);
389     if (f->intensity_stereo <= f->start_band)
390         totalbits += dual_stereo_bit; /* no intensity stereo means no dual stereo */
391     else if (dual_stereo_bit)
392         f->dual_stereo = ff_opus_rc_dec_log(rc, 1);
393
394     /* supply the remaining bits in this frame to lower bands */
395     remaining = totalbits - total;
396     bandbits  = remaining / (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]);
397     remaining -= bandbits * (ff_celt_freq_bands[f->coded_bands] - ff_celt_freq_bands[f->start_band]);
398     for (i = f->start_band; i < f->coded_bands; i++) {
399         int bits = FFMIN(remaining, ff_celt_freq_range[i]);
400
401         f->pulses[i] += bits + bandbits * ff_celt_freq_range[i];
402         remaining    -= bits;
403     }
404
405     for (i = f->start_band; i < f->coded_bands; i++) {
406         int N = ff_celt_freq_range[i] << f->size;
407         int prev_extra = extrabits;
408         f->pulses[i] += extrabits;
409
410         if (N > 1) {
411             int dof;        // degrees of freedom
412             int temp;       // dof * channels * log(dof)
413             int offset;     // fine energy quantization offset, i.e.
414                             // extra bits assigned over the standard
415                             // totalbits/dof
416             int fine_bits, max_bits;
417
418             extrabits = FFMAX(0, f->pulses[i] - cap[i]);
419             f->pulses[i] -= extrabits;
420
421             /* intensity stereo makes use of an extra degree of freedom */
422             dof = N * f->channels
423                   + (f->channels == 2 && N > 2 && !f->dual_stereo && i < f->intensity_stereo);
424             temp = dof * (ff_celt_log_freq_range[i] + (f->size<<3));
425             offset = (temp >> 1) - dof * CELT_FINE_OFFSET;
426             if (N == 2) /* dof=2 is the only case that doesn't fit the model */
427                 offset += dof<<1;
428
429             /* grant an additional bias for the first and second pulses */
430             if (f->pulses[i] + offset < 2 * (dof << 3))
431                 offset += temp >> 2;
432             else if (f->pulses[i] + offset < 3 * (dof << 3))
433                 offset += temp >> 3;
434
435             fine_bits = (f->pulses[i] + offset + (dof << 2)) / (dof << 3);
436             max_bits  = FFMIN((f->pulses[i]>>3) >> (f->channels - 1),
437                               CELT_MAX_FINE_BITS);
438
439             max_bits  = FFMAX(max_bits, 0);
440
441             f->fine_bits[i] = av_clip(fine_bits, 0, max_bits);
442
443             /* if fine_bits was rounded down or capped,
444                give priority for the final fine energy pass */
445             f->fine_priority[i] = (f->fine_bits[i] * (dof<<3) >= f->pulses[i] + offset);
446
447             /* the remaining bits are assigned to PVQ */
448             f->pulses[i] -= f->fine_bits[i] << (f->channels - 1) << 3;
449         } else {
450             /* all bits go to fine energy except for the sign bit */
451             extrabits = FFMAX(0, f->pulses[i] - (f->channels << 3));
452             f->pulses[i] -= extrabits;
453             f->fine_bits[i] = 0;
454             f->fine_priority[i] = 1;
455         }
456
457         /* hand back a limited number of extra fine energy bits to this band */
458         if (extrabits > 0) {
459             int fineextra = FFMIN(extrabits >> (f->channels + 2),
460                                   CELT_MAX_FINE_BITS - f->fine_bits[i]);
461             f->fine_bits[i] += fineextra;
462
463             fineextra <<= f->channels + 2;
464             f->fine_priority[i] = (fineextra >= extrabits - prev_extra);
465             extrabits -= fineextra;
466         }
467     }
468     f->remaining = extrabits;
469
470     /* skipped bands dedicate all of their bits for fine energy */
471     for (; i < f->end_band; i++) {
472         f->fine_bits[i]     = f->pulses[i] >> (f->channels - 1) >> 3;
473         f->pulses[i]        = 0;
474         f->fine_priority[i] = f->fine_bits[i] < 1;
475     }
476 }
477
478 static void celt_denormalize(CeltFrame *f, CeltBlock *block, float *data)
479 {
480     int i, j;
481
482     for (i = f->start_band; i < f->end_band; i++) {
483         float *dst = data + (ff_celt_freq_bands[i] << f->size);
484         float log_norm = block->energy[i] + ff_celt_mean_energy[i];
485         float norm = exp2f(FFMIN(log_norm, 32.0f));
486
487         for (j = 0; j < ff_celt_freq_range[i] << f->size; j++)
488             dst[j] *= norm;
489     }
490 }
491
492 static void celt_postfilter_apply_transition(CeltBlock *block, float *data)
493 {
494     const int T0 = block->pf_period_old;
495     const int T1 = block->pf_period;
496
497     float g00, g01, g02;
498     float g10, g11, g12;
499
500     float x0, x1, x2, x3, x4;
501
502     int i;
503
504     if (block->pf_gains[0]     == 0.0 &&
505         block->pf_gains_old[0] == 0.0)
506         return;
507
508     g00 = block->pf_gains_old[0];
509     g01 = block->pf_gains_old[1];
510     g02 = block->pf_gains_old[2];
511     g10 = block->pf_gains[0];
512     g11 = block->pf_gains[1];
513     g12 = block->pf_gains[2];
514
515     x1 = data[-T1 + 1];
516     x2 = data[-T1];
517     x3 = data[-T1 - 1];
518     x4 = data[-T1 - 2];
519
520     for (i = 0; i < CELT_OVERLAP; i++) {
521         float w = ff_celt_window2[i];
522         x0 = data[i - T1 + 2];
523
524         data[i] +=  (1.0 - w) * g00 * data[i - T0]                          +
525                     (1.0 - w) * g01 * (data[i - T0 - 1] + data[i - T0 + 1]) +
526                     (1.0 - w) * g02 * (data[i - T0 - 2] + data[i - T0 + 2]) +
527                     w         * g10 * x2                                    +
528                     w         * g11 * (x1 + x3)                             +
529                     w         * g12 * (x0 + x4);
530         x4 = x3;
531         x3 = x2;
532         x2 = x1;
533         x1 = x0;
534     }
535 }
536
537 static void celt_postfilter_apply(CeltBlock *block, float *data, int len)
538 {
539     const int T = block->pf_period;
540     float g0, g1, g2;
541     float x0, x1, x2, x3, x4;
542     int i;
543
544     if (block->pf_gains[0] == 0.0 || len <= 0)
545         return;
546
547     g0 = block->pf_gains[0];
548     g1 = block->pf_gains[1];
549     g2 = block->pf_gains[2];
550
551     x4 = data[-T - 2];
552     x3 = data[-T - 1];
553     x2 = data[-T];
554     x1 = data[-T + 1];
555
556     for (i = 0; i < len; i++) {
557         x0 = data[i - T + 2];
558         data[i] += g0 * x2        +
559                    g1 * (x1 + x3) +
560                    g2 * (x0 + x4);
561         x4 = x3;
562         x3 = x2;
563         x2 = x1;
564         x1 = x0;
565     }
566 }
567
568 static void celt_postfilter(CeltFrame *f, CeltBlock *block)
569 {
570     int len = f->blocksize * f->blocks;
571
572     celt_postfilter_apply_transition(block, block->buf + 1024);
573
574     block->pf_period_old = block->pf_period;
575     memcpy(block->pf_gains_old, block->pf_gains, sizeof(block->pf_gains));
576
577     block->pf_period = block->pf_period_new;
578     memcpy(block->pf_gains, block->pf_gains_new, sizeof(block->pf_gains));
579
580     if (len > CELT_OVERLAP) {
581         celt_postfilter_apply_transition(block, block->buf + 1024 + CELT_OVERLAP);
582         celt_postfilter_apply(block, block->buf + 1024 + 2 * CELT_OVERLAP,
583                               len - 2 * CELT_OVERLAP);
584
585         block->pf_period_old = block->pf_period;
586         memcpy(block->pf_gains_old, block->pf_gains, sizeof(block->pf_gains));
587     }
588
589     memmove(block->buf, block->buf + len, (1024 + CELT_OVERLAP / 2) * sizeof(float));
590 }
591
592 static int parse_postfilter(CeltFrame *f, OpusRangeCoder *rc, int consumed)
593 {
594     int i;
595
596     memset(f->block[0].pf_gains_new, 0, sizeof(f->block[0].pf_gains_new));
597     memset(f->block[1].pf_gains_new, 0, sizeof(f->block[1].pf_gains_new));
598
599     if (f->start_band == 0 && consumed + 16 <= f->framebits) {
600         int has_postfilter = ff_opus_rc_dec_log(rc, 1);
601         if (has_postfilter) {
602             float gain;
603             int tapset, octave, period;
604
605             octave = ff_opus_rc_dec_uint(rc, 6);
606             period = (16 << octave) + ff_opus_rc_get_raw(rc, 4 + octave) - 1;
607             gain   = 0.09375f * (ff_opus_rc_get_raw(rc, 3) + 1);
608             tapset = (opus_rc_tell(rc) + 2 <= f->framebits) ?
609                      ff_opus_rc_dec_cdf(rc, ff_celt_model_tapset) : 0;
610
611             for (i = 0; i < 2; i++) {
612                 CeltBlock *block = &f->block[i];
613
614                 block->pf_period_new = FFMAX(period, CELT_POSTFILTER_MINPERIOD);
615                 block->pf_gains_new[0] = gain * ff_celt_postfilter_taps[tapset][0];
616                 block->pf_gains_new[1] = gain * ff_celt_postfilter_taps[tapset][1];
617                 block->pf_gains_new[2] = gain * ff_celt_postfilter_taps[tapset][2];
618             }
619         }
620
621         consumed = opus_rc_tell(rc);
622     }
623
624     return consumed;
625 }
626
627 static void process_anticollapse(CeltFrame *f, CeltBlock *block, float *X)
628 {
629     int i, j, k;
630
631     for (i = f->start_band; i < f->end_band; i++) {
632         int renormalize = 0;
633         float *xptr;
634         float prev[2];
635         float Ediff, r;
636         float thresh, sqrt_1;
637         int depth;
638
639         /* depth in 1/8 bits */
640         depth = (1 + f->pulses[i]) / (ff_celt_freq_range[i] << f->size);
641         thresh = exp2f(-1.0 - 0.125f * depth);
642         sqrt_1 = 1.0f / sqrtf(ff_celt_freq_range[i] << f->size);
643
644         xptr = X + (ff_celt_freq_bands[i] << f->size);
645
646         prev[0] = block->prev_energy[0][i];
647         prev[1] = block->prev_energy[1][i];
648         if (f->channels == 1) {
649             CeltBlock *block1 = &f->block[1];
650
651             prev[0] = FFMAX(prev[0], block1->prev_energy[0][i]);
652             prev[1] = FFMAX(prev[1], block1->prev_energy[1][i]);
653         }
654         Ediff = block->energy[i] - FFMIN(prev[0], prev[1]);
655         Ediff = FFMAX(0, Ediff);
656
657         /* r needs to be multiplied by 2 or 2*sqrt(2) depending on LM because
658         short blocks don't have the same energy as long */
659         r = exp2f(1 - Ediff);
660         if (f->size == 3)
661             r *= M_SQRT2;
662         r = FFMIN(thresh, r) * sqrt_1;
663         for (k = 0; k < 1 << f->size; k++) {
664             /* Detect collapse */
665             if (!(block->collapse_masks[i] & 1 << k)) {
666                 /* Fill with noise */
667                 for (j = 0; j < ff_celt_freq_range[i]; j++)
668                     xptr[(j << f->size) + k] = (celt_rng(f) & 0x8000) ? r : -r;
669                 renormalize = 1;
670             }
671         }
672
673         /* We just added some energy, so we need to renormalize */
674         if (renormalize)
675             celt_renormalize_vector(xptr, ff_celt_freq_range[i] << f->size, 1.0f);
676     }
677 }
678
679 static void celt_decode_bands(CeltFrame *f, OpusRangeCoder *rc)
680 {
681     float lowband_scratch[8 * 22];
682     float norm[2 * 8 * 100];
683
684     int totalbits = (f->framebits << 3) - f->anticollapse_needed;
685
686     int update_lowband = 1;
687     int lowband_offset = 0;
688
689     int i, j;
690
691     memset(f->block[0].coeffs, 0, sizeof(f->block[0].coeffs));
692     memset(f->block[1].coeffs, 0, sizeof(f->block[0].coeffs));
693
694     for (i = f->start_band; i < f->end_band; i++) {
695         uint32_t cm[2] = { (1 << f->blocks) - 1, (1 << f->blocks) - 1 };
696         int band_offset = ff_celt_freq_bands[i] << f->size;
697         int band_size   = ff_celt_freq_range[i] << f->size;
698         float *X = f->block[0].coeffs + band_offset;
699         float *Y = (f->channels == 2) ? f->block[1].coeffs + band_offset : NULL;
700
701         int consumed = opus_rc_tell_frac(rc);
702         float *norm2 = norm + 8 * 100;
703         int effective_lowband = -1;
704         int b = 0;
705
706         /* Compute how many bits we want to allocate to this band */
707         if (i != f->start_band)
708             f->remaining -= consumed;
709         f->remaining2 = totalbits - consumed - 1;
710         if (i <= f->coded_bands - 1) {
711             int curr_balance = f->remaining / FFMIN(3, f->coded_bands-i);
712             b = av_clip_uintp2(FFMIN(f->remaining2 + 1, f->pulses[i] + curr_balance), 14);
713         }
714
715         if (ff_celt_freq_bands[i] - ff_celt_freq_range[i] >= ff_celt_freq_bands[f->start_band] &&
716             (update_lowband || lowband_offset == 0))
717             lowband_offset = i;
718
719         /* Get a conservative estimate of the collapse_mask's for the bands we're
720            going to be folding from. */
721         if (lowband_offset != 0 && (f->spread != CELT_SPREAD_AGGRESSIVE ||
722                                     f->blocks > 1 || f->tf_change[i] < 0)) {
723             int foldstart, foldend;
724
725             /* This ensures we never repeat spectral content within one band */
726             effective_lowband = FFMAX(ff_celt_freq_bands[f->start_band],
727                                       ff_celt_freq_bands[lowband_offset] - ff_celt_freq_range[i]);
728             foldstart = lowband_offset;
729             while (ff_celt_freq_bands[--foldstart] > effective_lowband);
730             foldend = lowband_offset - 1;
731             while (ff_celt_freq_bands[++foldend] < effective_lowband + ff_celt_freq_range[i]);
732
733             cm[0] = cm[1] = 0;
734             for (j = foldstart; j < foldend; j++) {
735                 cm[0] |= f->block[0].collapse_masks[j];
736                 cm[1] |= f->block[f->channels - 1].collapse_masks[j];
737             }
738         }
739
740         if (f->dual_stereo && i == f->intensity_stereo) {
741             /* Switch off dual stereo to do intensity */
742             f->dual_stereo = 0;
743             for (j = ff_celt_freq_bands[f->start_band] << f->size; j < band_offset; j++)
744                 norm[j] = (norm[j] + norm2[j]) / 2;
745         }
746
747         if (f->dual_stereo) {
748             cm[0] = f->pvq->decode_band(f->pvq, f, rc, i, X, NULL, band_size, b / 2, f->blocks,
749                                         effective_lowband != -1 ? norm + (effective_lowband << f->size) : NULL, f->size,
750                                         norm + band_offset, 0, 1.0f, lowband_scratch, cm[0]);
751
752             cm[1] = f->pvq->decode_band(f->pvq, f, rc, i, Y, NULL, band_size, b/2, f->blocks,
753                                         effective_lowband != -1 ? norm2 + (effective_lowband << f->size) : NULL, f->size,
754                                         norm2 + band_offset, 0, 1.0f, lowband_scratch, cm[1]);
755         } else {
756             cm[0] = f->pvq->decode_band(f->pvq, f, rc, i, X, Y, band_size, b, f->blocks,
757                                         effective_lowband != -1 ? norm + (effective_lowband << f->size) : NULL, f->size,
758                                         norm + band_offset, 0, 1.0f, lowband_scratch, cm[0]|cm[1]);
759             cm[1] = cm[0];
760         }
761
762         f->block[0].collapse_masks[i]               = (uint8_t)cm[0];
763         f->block[f->channels - 1].collapse_masks[i] = (uint8_t)cm[1];
764         f->remaining += f->pulses[i] + consumed;
765
766         /* Update the folding position only as long as we have 1 bit/sample depth */
767         update_lowband = (b > band_size << 3);
768     }
769 }
770
771 int ff_celt_decode_frame(CeltFrame *f, OpusRangeCoder *rc,
772                          float **output, int channels, int frame_size,
773                          int start_band,  int end_band)
774 {
775     int i, j, downmix = 0;
776     int consumed;           // bits of entropy consumed thus far for this frame
777     MDCT15Context *imdct;
778
779     if (channels != 1 && channels != 2) {
780         av_log(f->avctx, AV_LOG_ERROR, "Invalid number of coded channels: %d\n",
781                channels);
782         return AVERROR_INVALIDDATA;
783     }
784     if (start_band < 0 || start_band > end_band || end_band > CELT_MAX_BANDS) {
785         av_log(f->avctx, AV_LOG_ERROR, "Invalid start/end band: %d %d\n",
786                start_band, end_band);
787         return AVERROR_INVALIDDATA;
788     }
789
790     f->silence        = 0;
791     f->transient      = 0;
792     f->anticollapse   = 0;
793     f->flushed        = 0;
794     f->channels       = channels;
795     f->start_band     = start_band;
796     f->end_band       = end_band;
797     f->framebits      = rc->rb.bytes * 8;
798
799     f->size = av_log2(frame_size / CELT_SHORT_BLOCKSIZE);
800     if (f->size > CELT_MAX_LOG_BLOCKS ||
801         frame_size != CELT_SHORT_BLOCKSIZE * (1 << f->size)) {
802         av_log(f->avctx, AV_LOG_ERROR, "Invalid CELT frame size: %d\n",
803                frame_size);
804         return AVERROR_INVALIDDATA;
805     }
806
807     if (!f->output_channels)
808         f->output_channels = channels;
809
810     memset(f->block[0].collapse_masks, 0, sizeof(f->block[0].collapse_masks));
811     memset(f->block[1].collapse_masks, 0, sizeof(f->block[1].collapse_masks));
812
813     consumed = opus_rc_tell(rc);
814
815     /* obtain silence flag */
816     if (consumed >= f->framebits)
817         f->silence = 1;
818     else if (consumed == 1)
819         f->silence = ff_opus_rc_dec_log(rc, 15);
820
821
822     if (f->silence) {
823         consumed = f->framebits;
824         rc->total_bits += f->framebits - opus_rc_tell(rc);
825     }
826
827     /* obtain post-filter options */
828     consumed = parse_postfilter(f, rc, consumed);
829
830     /* obtain transient flag */
831     if (f->size != 0 && consumed+3 <= f->framebits)
832         f->transient = ff_opus_rc_dec_log(rc, 3);
833
834     f->blocks    = f->transient ? 1 << f->size : 1;
835     f->blocksize = frame_size / f->blocks;
836
837     imdct = f->imdct[f->transient ? 0 : f->size];
838
839     if (channels == 1) {
840         for (i = 0; i < CELT_MAX_BANDS; i++)
841             f->block[0].energy[i] = FFMAX(f->block[0].energy[i], f->block[1].energy[i]);
842     }
843
844     celt_decode_coarse_energy(f, rc);
845     celt_decode_tf_changes   (f, rc);
846     celt_decode_allocation   (f, rc);
847     celt_decode_fine_energy  (f, rc);
848     celt_decode_bands        (f, rc);
849
850     if (f->anticollapse_needed)
851         f->anticollapse = ff_opus_rc_get_raw(rc, 1);
852
853     celt_decode_final_energy(f, rc);
854
855     /* apply anti-collapse processing and denormalization to
856      * each coded channel */
857     for (i = 0; i < f->channels; i++) {
858         CeltBlock *block = &f->block[i];
859
860         if (f->anticollapse)
861             process_anticollapse(f, block, f->block[i].coeffs);
862
863         celt_denormalize(f, block, f->block[i].coeffs);
864     }
865
866     /* stereo -> mono downmix */
867     if (f->output_channels < f->channels) {
868         f->dsp->vector_fmac_scalar(f->block[0].coeffs, f->block[1].coeffs, 1.0, FFALIGN(frame_size, 16));
869         downmix = 1;
870     } else if (f->output_channels > f->channels)
871         memcpy(f->block[1].coeffs, f->block[0].coeffs, frame_size * sizeof(float));
872
873     if (f->silence) {
874         for (i = 0; i < 2; i++) {
875             CeltBlock *block = &f->block[i];
876
877             for (j = 0; j < FF_ARRAY_ELEMS(block->energy); j++)
878                 block->energy[j] = CELT_ENERGY_SILENCE;
879         }
880         memset(f->block[0].coeffs, 0, sizeof(f->block[0].coeffs));
881         memset(f->block[1].coeffs, 0, sizeof(f->block[1].coeffs));
882     }
883
884     /* transform and output for each output channel */
885     for (i = 0; i < f->output_channels; i++) {
886         CeltBlock *block = &f->block[i];
887         float m = block->emph_coeff;
888
889         /* iMDCT and overlap-add */
890         for (j = 0; j < f->blocks; j++) {
891             float *dst  = block->buf + 1024 + j * f->blocksize;
892
893             imdct->imdct_half(imdct, dst + CELT_OVERLAP / 2, f->block[i].coeffs + j,
894                               f->blocks);
895             f->dsp->vector_fmul_window(dst, dst, dst + CELT_OVERLAP / 2,
896                                        ff_celt_window, CELT_OVERLAP / 2);
897         }
898
899         if (downmix)
900             f->dsp->vector_fmul_scalar(&block->buf[1024], &block->buf[1024], 0.5f, frame_size);
901
902         /* postfilter */
903         celt_postfilter(f, block);
904
905         /* deemphasis and output scaling */
906         for (j = 0; j < frame_size; j++) {
907             const float tmp = block->buf[1024 - frame_size + j] + m;
908             m = tmp * CELT_EMPH_COEFF;
909             output[i][j] = tmp;
910         }
911
912         block->emph_coeff = m;
913     }
914
915     if (channels == 1)
916         memcpy(f->block[1].energy, f->block[0].energy, sizeof(f->block[0].energy));
917
918     for (i = 0; i < 2; i++ ) {
919         CeltBlock *block = &f->block[i];
920
921         if (!f->transient) {
922             memcpy(block->prev_energy[1], block->prev_energy[0], sizeof(block->prev_energy[0]));
923             memcpy(block->prev_energy[0], block->energy,         sizeof(block->prev_energy[0]));
924         } else {
925             for (j = 0; j < CELT_MAX_BANDS; j++)
926                 block->prev_energy[0][j] = FFMIN(block->prev_energy[0][j], block->energy[j]);
927         }
928
929         for (j = 0; j < f->start_band; j++) {
930             block->prev_energy[0][j] = CELT_ENERGY_SILENCE;
931             block->energy[j]         = 0.0;
932         }
933         for (j = f->end_band; j < CELT_MAX_BANDS; j++) {
934             block->prev_energy[0][j] = CELT_ENERGY_SILENCE;
935             block->energy[j]         = 0.0;
936         }
937     }
938
939     f->seed = rc->range;
940
941     return 0;
942 }
943
944 void ff_celt_flush(CeltFrame *f)
945 {
946     int i, j;
947
948     if (f->flushed)
949         return;
950
951     for (i = 0; i < 2; i++) {
952         CeltBlock *block = &f->block[i];
953
954         for (j = 0; j < CELT_MAX_BANDS; j++)
955             block->prev_energy[0][j] = block->prev_energy[1][j] = CELT_ENERGY_SILENCE;
956
957         memset(block->energy, 0, sizeof(block->energy));
958         memset(block->buf,    0, sizeof(block->buf));
959
960         memset(block->pf_gains,     0, sizeof(block->pf_gains));
961         memset(block->pf_gains_old, 0, sizeof(block->pf_gains_old));
962         memset(block->pf_gains_new, 0, sizeof(block->pf_gains_new));
963
964         block->emph_coeff = 0.0;
965     }
966     f->seed = 0;
967
968     f->flushed = 1;
969 }
970
971 void ff_celt_free(CeltFrame **f)
972 {
973     CeltFrame *frm = *f;
974     int i;
975
976     if (!frm)
977         return;
978
979     for (i = 0; i < FF_ARRAY_ELEMS(frm->imdct); i++)
980         ff_mdct15_uninit(&frm->imdct[i]);
981
982     ff_celt_pvq_uninit(&frm->pvq);
983
984     av_freep(&frm->dsp);
985     av_freep(f);
986 }
987
988 int ff_celt_init(AVCodecContext *avctx, CeltFrame **f, int output_channels)
989 {
990     CeltFrame *frm;
991     int i, ret;
992
993     if (output_channels != 1 && output_channels != 2) {
994         av_log(avctx, AV_LOG_ERROR, "Invalid number of output channels: %d\n",
995                output_channels);
996         return AVERROR(EINVAL);
997     }
998
999     frm = av_mallocz(sizeof(*frm));
1000     if (!frm)
1001         return AVERROR(ENOMEM);
1002
1003     frm->avctx           = avctx;
1004     frm->output_channels = output_channels;
1005
1006     for (i = 0; i < FF_ARRAY_ELEMS(frm->imdct); i++)
1007         if ((ret = ff_mdct15_init(&frm->imdct[i], 1, i + 3, -1.0f/32768)) < 0)
1008             goto fail;
1009
1010     if ((ret = ff_celt_pvq_init(&frm->pvq)) < 0)
1011         goto fail;
1012
1013     frm->dsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
1014     if (!frm->dsp) {
1015         ret = AVERROR(ENOMEM);
1016         goto fail;
1017     }
1018
1019     ff_celt_flush(frm);
1020
1021     *f = frm;
1022
1023     return 0;
1024 fail:
1025     ff_celt_free(&frm);
1026     return ret;
1027 }