OSDN Git Service

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