]> git.sesse.net Git - ffmpeg/blob - libavcodec/opus_celt.c
Merge commit 'b05128f3c953bd66483e697d60a2e7e45ee9cfa0'
[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 norm = exp2f(block->energy[i] + ff_celt_mean_energy[i]);
485
486         for (j = 0; j < ff_celt_freq_range[i] << f->size; j++)
487             dst[j] *= norm;
488     }
489 }
490
491 static void celt_postfilter_apply_transition(CeltBlock *block, float *data)
492 {
493     const int T0 = block->pf_period_old;
494     const int T1 = block->pf_period;
495
496     float g00, g01, g02;
497     float g10, g11, g12;
498
499     float x0, x1, x2, x3, x4;
500
501     int i;
502
503     if (block->pf_gains[0]     == 0.0 &&
504         block->pf_gains_old[0] == 0.0)
505         return;
506
507     g00 = block->pf_gains_old[0];
508     g01 = block->pf_gains_old[1];
509     g02 = block->pf_gains_old[2];
510     g10 = block->pf_gains[0];
511     g11 = block->pf_gains[1];
512     g12 = block->pf_gains[2];
513
514     x1 = data[-T1 + 1];
515     x2 = data[-T1];
516     x3 = data[-T1 - 1];
517     x4 = data[-T1 - 2];
518
519     for (i = 0; i < CELT_OVERLAP; i++) {
520         float w = ff_celt_window2[i];
521         x0 = data[i - T1 + 2];
522
523         data[i] +=  (1.0 - w) * g00 * data[i - T0]                          +
524                     (1.0 - w) * g01 * (data[i - T0 - 1] + data[i - T0 + 1]) +
525                     (1.0 - w) * g02 * (data[i - T0 - 2] + data[i - T0 + 2]) +
526                     w         * g10 * x2                                    +
527                     w         * g11 * (x1 + x3)                             +
528                     w         * g12 * (x0 + x4);
529         x4 = x3;
530         x3 = x2;
531         x2 = x1;
532         x1 = x0;
533     }
534 }
535
536 static void celt_postfilter_apply(CeltBlock *block, float *data, int len)
537 {
538     const int T = block->pf_period;
539     float g0, g1, g2;
540     float x0, x1, x2, x3, x4;
541     int i;
542
543     if (block->pf_gains[0] == 0.0 || len <= 0)
544         return;
545
546     g0 = block->pf_gains[0];
547     g1 = block->pf_gains[1];
548     g2 = block->pf_gains[2];
549
550     x4 = data[-T - 2];
551     x3 = data[-T - 1];
552     x2 = data[-T];
553     x1 = data[-T + 1];
554
555     for (i = 0; i < len; i++) {
556         x0 = data[i - T + 2];
557         data[i] += g0 * x2        +
558                    g1 * (x1 + x3) +
559                    g2 * (x0 + x4);
560         x4 = x3;
561         x3 = x2;
562         x2 = x1;
563         x1 = x0;
564     }
565 }
566
567 static void celt_postfilter(CeltFrame *f, CeltBlock *block)
568 {
569     int len = f->blocksize * f->blocks;
570
571     celt_postfilter_apply_transition(block, block->buf + 1024);
572
573     block->pf_period_old = block->pf_period;
574     memcpy(block->pf_gains_old, block->pf_gains, sizeof(block->pf_gains));
575
576     block->pf_period = block->pf_period_new;
577     memcpy(block->pf_gains, block->pf_gains_new, sizeof(block->pf_gains));
578
579     if (len > CELT_OVERLAP) {
580         celt_postfilter_apply_transition(block, block->buf + 1024 + CELT_OVERLAP);
581         celt_postfilter_apply(block, block->buf + 1024 + 2 * CELT_OVERLAP,
582                               len - 2 * CELT_OVERLAP);
583
584         block->pf_period_old = block->pf_period;
585         memcpy(block->pf_gains_old, block->pf_gains, sizeof(block->pf_gains));
586     }
587
588     memmove(block->buf, block->buf + len, (1024 + CELT_OVERLAP / 2) * sizeof(float));
589 }
590
591 static int parse_postfilter(CeltFrame *f, OpusRangeCoder *rc, int consumed)
592 {
593     int i;
594
595     memset(f->block[0].pf_gains_new, 0, sizeof(f->block[0].pf_gains_new));
596     memset(f->block[1].pf_gains_new, 0, sizeof(f->block[1].pf_gains_new));
597
598     if (f->start_band == 0 && consumed + 16 <= f->framebits) {
599         int has_postfilter = ff_opus_rc_dec_log(rc, 1);
600         if (has_postfilter) {
601             float gain;
602             int tapset, octave, period;
603
604             octave = ff_opus_rc_dec_uint(rc, 6);
605             period = (16 << octave) + ff_opus_rc_get_raw(rc, 4 + octave) - 1;
606             gain   = 0.09375f * (ff_opus_rc_get_raw(rc, 3) + 1);
607             tapset = (opus_rc_tell(rc) + 2 <= f->framebits) ?
608                      ff_opus_rc_dec_cdf(rc, ff_celt_model_tapset) : 0;
609
610             for (i = 0; i < 2; i++) {
611                 CeltBlock *block = &f->block[i];
612
613                 block->pf_period_new = FFMAX(period, CELT_POSTFILTER_MINPERIOD);
614                 block->pf_gains_new[0] = gain * ff_celt_postfilter_taps[tapset][0];
615                 block->pf_gains_new[1] = gain * ff_celt_postfilter_taps[tapset][1];
616                 block->pf_gains_new[2] = gain * ff_celt_postfilter_taps[tapset][2];
617             }
618         }
619
620         consumed = opus_rc_tell(rc);
621     }
622
623     return consumed;
624 }
625
626 static void process_anticollapse(CeltFrame *f, CeltBlock *block, float *X)
627 {
628     int i, j, k;
629
630     for (i = f->start_band; i < f->end_band; i++) {
631         int renormalize = 0;
632         float *xptr;
633         float prev[2];
634         float Ediff, r;
635         float thresh, sqrt_1;
636         int depth;
637
638         /* depth in 1/8 bits */
639         depth = (1 + f->pulses[i]) / (ff_celt_freq_range[i] << f->size);
640         thresh = exp2f(-1.0 - 0.125f * depth);
641         sqrt_1 = 1.0f / sqrtf(ff_celt_freq_range[i] << f->size);
642
643         xptr = X + (ff_celt_freq_bands[i] << f->size);
644
645         prev[0] = block->prev_energy[0][i];
646         prev[1] = block->prev_energy[1][i];
647         if (f->channels == 1) {
648             CeltBlock *block1 = &f->block[1];
649
650             prev[0] = FFMAX(prev[0], block1->prev_energy[0][i]);
651             prev[1] = FFMAX(prev[1], block1->prev_energy[1][i]);
652         }
653         Ediff = block->energy[i] - FFMIN(prev[0], prev[1]);
654         Ediff = FFMAX(0, Ediff);
655
656         /* r needs to be multiplied by 2 or 2*sqrt(2) depending on LM because
657         short blocks don't have the same energy as long */
658         r = exp2f(1 - Ediff);
659         if (f->size == 3)
660             r *= M_SQRT2;
661         r = FFMIN(thresh, r) * sqrt_1;
662         for (k = 0; k < 1 << f->size; k++) {
663             /* Detect collapse */
664             if (!(block->collapse_masks[i] & 1 << k)) {
665                 /* Fill with noise */
666                 for (j = 0; j < ff_celt_freq_range[i]; j++)
667                     xptr[(j << f->size) + k] = (celt_rng(f) & 0x8000) ? r : -r;
668                 renormalize = 1;
669             }
670         }
671
672         /* We just added some energy, so we need to renormalize */
673         if (renormalize)
674             celt_renormalize_vector(xptr, ff_celt_freq_range[i] << f->size, 1.0f);
675     }
676 }
677
678 static void celt_decode_bands(CeltFrame *f, OpusRangeCoder *rc)
679 {
680     float lowband_scratch[8 * 22];
681     float norm[2 * 8 * 100];
682
683     int totalbits = (f->framebits << 3) - f->anticollapse_needed;
684
685     int update_lowband = 1;
686     int lowband_offset = 0;
687
688     int i, j;
689
690     memset(f->block[0].coeffs, 0, sizeof(f->block[0].coeffs));
691     memset(f->block[1].coeffs, 0, sizeof(f->block[0].coeffs));
692
693     for (i = f->start_band; i < f->end_band; i++) {
694         uint32_t cm[2] = { (1 << f->blocks) - 1, (1 << f->blocks) - 1 };
695         int band_offset = ff_celt_freq_bands[i] << f->size;
696         int band_size   = ff_celt_freq_range[i] << f->size;
697         float *X = f->block[0].coeffs + band_offset;
698         float *Y = (f->channels == 2) ? f->block[1].coeffs + band_offset : NULL;
699
700         int consumed = opus_rc_tell_frac(rc);
701         float *norm2 = norm + 8 * 100;
702         int effective_lowband = -1;
703         int b = 0;
704
705         /* Compute how many bits we want to allocate to this band */
706         if (i != f->start_band)
707             f->remaining -= consumed;
708         f->remaining2 = totalbits - consumed - 1;
709         if (i <= f->coded_bands - 1) {
710             int curr_balance = f->remaining / FFMIN(3, f->coded_bands-i);
711             b = av_clip_uintp2(FFMIN(f->remaining2 + 1, f->pulses[i] + curr_balance), 14);
712         }
713
714         if (ff_celt_freq_bands[i] - ff_celt_freq_range[i] >= ff_celt_freq_bands[f->start_band] &&
715             (update_lowband || lowband_offset == 0))
716             lowband_offset = i;
717
718         /* Get a conservative estimate of the collapse_mask's for the bands we're
719            going to be folding from. */
720         if (lowband_offset != 0 && (f->spread != CELT_SPREAD_AGGRESSIVE ||
721                                     f->blocks > 1 || f->tf_change[i] < 0)) {
722             int foldstart, foldend;
723
724             /* This ensures we never repeat spectral content within one band */
725             effective_lowband = FFMAX(ff_celt_freq_bands[f->start_band],
726                                       ff_celt_freq_bands[lowband_offset] - ff_celt_freq_range[i]);
727             foldstart = lowband_offset;
728             while (ff_celt_freq_bands[--foldstart] > effective_lowband);
729             foldend = lowband_offset - 1;
730             while (ff_celt_freq_bands[++foldend] < effective_lowband + ff_celt_freq_range[i]);
731
732             cm[0] = cm[1] = 0;
733             for (j = foldstart; j < foldend; j++) {
734                 cm[0] |= f->block[0].collapse_masks[j];
735                 cm[1] |= f->block[f->channels - 1].collapse_masks[j];
736             }
737         }
738
739         if (f->dual_stereo && i == f->intensity_stereo) {
740             /* Switch off dual stereo to do intensity */
741             f->dual_stereo = 0;
742             for (j = ff_celt_freq_bands[f->start_band] << f->size; j < band_offset; j++)
743                 norm[j] = (norm[j] + norm2[j]) / 2;
744         }
745
746         if (f->dual_stereo) {
747             cm[0] = f->pvq->decode_band(f->pvq, f, rc, i, X, NULL, band_size, b / 2, f->blocks,
748                                         effective_lowband != -1 ? norm + (effective_lowband << f->size) : NULL, f->size,
749                                         norm + band_offset, 0, 1.0f, lowband_scratch, cm[0]);
750
751             cm[1] = f->pvq->decode_band(f->pvq, f, rc, i, Y, NULL, band_size, b/2, f->blocks,
752                                         effective_lowband != -1 ? norm2 + (effective_lowband << f->size) : NULL, f->size,
753                                         norm2 + band_offset, 0, 1.0f, lowband_scratch, cm[1]);
754         } else {
755             cm[0] = f->pvq->decode_band(f->pvq, f, rc, i, X, Y, band_size, b, f->blocks,
756                                         effective_lowband != -1 ? norm + (effective_lowband << f->size) : NULL, f->size,
757                                         norm + band_offset, 0, 1.0f, lowband_scratch, cm[0]|cm[1]);
758             cm[1] = cm[0];
759         }
760
761         f->block[0].collapse_masks[i]               = (uint8_t)cm[0];
762         f->block[f->channels - 1].collapse_masks[i] = (uint8_t)cm[1];
763         f->remaining += f->pulses[i] + consumed;
764
765         /* Update the folding position only as long as we have 1 bit/sample depth */
766         update_lowband = (b > band_size << 3);
767     }
768 }
769
770 int ff_celt_decode_frame(CeltFrame *f, OpusRangeCoder *rc,
771                          float **output, int channels, int frame_size,
772                          int start_band,  int end_band)
773 {
774     int i, j, downmix = 0;
775     int consumed;           // bits of entropy consumed thus far for this frame
776     MDCT15Context *imdct;
777
778     if (channels != 1 && channels != 2) {
779         av_log(f->avctx, AV_LOG_ERROR, "Invalid number of coded channels: %d\n",
780                channels);
781         return AVERROR_INVALIDDATA;
782     }
783     if (start_band < 0 || start_band > end_band || end_band > CELT_MAX_BANDS) {
784         av_log(f->avctx, AV_LOG_ERROR, "Invalid start/end band: %d %d\n",
785                start_band, end_band);
786         return AVERROR_INVALIDDATA;
787     }
788
789     f->silence        = 0;
790     f->transient      = 0;
791     f->anticollapse   = 0;
792     f->flushed        = 0;
793     f->channels       = channels;
794     f->start_band     = start_band;
795     f->end_band       = end_band;
796     f->framebits      = rc->rb.bytes * 8;
797
798     f->size = av_log2(frame_size / CELT_SHORT_BLOCKSIZE);
799     if (f->size > CELT_MAX_LOG_BLOCKS ||
800         frame_size != CELT_SHORT_BLOCKSIZE * (1 << f->size)) {
801         av_log(f->avctx, AV_LOG_ERROR, "Invalid CELT frame size: %d\n",
802                frame_size);
803         return AVERROR_INVALIDDATA;
804     }
805
806     if (!f->output_channels)
807         f->output_channels = channels;
808
809     memset(f->block[0].collapse_masks, 0, sizeof(f->block[0].collapse_masks));
810     memset(f->block[1].collapse_masks, 0, sizeof(f->block[1].collapse_masks));
811
812     consumed = opus_rc_tell(rc);
813
814     /* obtain silence flag */
815     if (consumed >= f->framebits)
816         f->silence = 1;
817     else if (consumed == 1)
818         f->silence = ff_opus_rc_dec_log(rc, 15);
819
820
821     if (f->silence) {
822         consumed = f->framebits;
823         rc->total_bits += f->framebits - opus_rc_tell(rc);
824     }
825
826     /* obtain post-filter options */
827     consumed = parse_postfilter(f, rc, consumed);
828
829     /* obtain transient flag */
830     if (f->size != 0 && consumed+3 <= f->framebits)
831         f->transient = ff_opus_rc_dec_log(rc, 3);
832
833     f->blocks    = f->transient ? 1 << f->size : 1;
834     f->blocksize = frame_size / f->blocks;
835
836     imdct = f->imdct[f->transient ? 0 : f->size];
837
838     if (channels == 1) {
839         for (i = 0; i < CELT_MAX_BANDS; i++)
840             f->block[0].energy[i] = FFMAX(f->block[0].energy[i], f->block[1].energy[i]);
841     }
842
843     celt_decode_coarse_energy(f, rc);
844     celt_decode_tf_changes   (f, rc);
845     celt_decode_allocation   (f, rc);
846     celt_decode_fine_energy  (f, rc);
847     celt_decode_bands        (f, rc);
848
849     if (f->anticollapse_needed)
850         f->anticollapse = ff_opus_rc_get_raw(rc, 1);
851
852     celt_decode_final_energy(f, rc);
853
854     /* apply anti-collapse processing and denormalization to
855      * each coded channel */
856     for (i = 0; i < f->channels; i++) {
857         CeltBlock *block = &f->block[i];
858
859         if (f->anticollapse)
860             process_anticollapse(f, block, f->block[i].coeffs);
861
862         celt_denormalize(f, block, f->block[i].coeffs);
863     }
864
865     /* stereo -> mono downmix */
866     if (f->output_channels < f->channels) {
867         f->dsp->vector_fmac_scalar(f->block[0].coeffs, f->block[1].coeffs, 1.0, FFALIGN(frame_size, 16));
868         downmix = 1;
869     } else if (f->output_channels > f->channels)
870         memcpy(f->block[1].coeffs, f->block[0].coeffs, frame_size * sizeof(float));
871
872     if (f->silence) {
873         for (i = 0; i < 2; i++) {
874             CeltBlock *block = &f->block[i];
875
876             for (j = 0; j < FF_ARRAY_ELEMS(block->energy); j++)
877                 block->energy[j] = CELT_ENERGY_SILENCE;
878         }
879         memset(f->block[0].coeffs, 0, sizeof(f->block[0].coeffs));
880         memset(f->block[1].coeffs, 0, sizeof(f->block[1].coeffs));
881     }
882
883     /* transform and output for each output channel */
884     for (i = 0; i < f->output_channels; i++) {
885         CeltBlock *block = &f->block[i];
886         float m = block->emph_coeff;
887
888         /* iMDCT and overlap-add */
889         for (j = 0; j < f->blocks; j++) {
890             float *dst  = block->buf + 1024 + j * f->blocksize;
891
892             imdct->imdct_half(imdct, dst + CELT_OVERLAP / 2, f->block[i].coeffs + j,
893                               f->blocks);
894             f->dsp->vector_fmul_window(dst, dst, dst + CELT_OVERLAP / 2,
895                                        ff_celt_window, CELT_OVERLAP / 2);
896         }
897
898         if (downmix)
899             f->dsp->vector_fmul_scalar(&block->buf[1024], &block->buf[1024], 0.5f, frame_size);
900
901         /* postfilter */
902         celt_postfilter(f, block);
903
904         /* deemphasis and output scaling */
905         for (j = 0; j < frame_size; j++) {
906             const float tmp = block->buf[1024 - frame_size + j] + m;
907             m = tmp * CELT_EMPH_COEFF;
908             output[i][j] = tmp;
909         }
910
911         block->emph_coeff = m;
912     }
913
914     if (channels == 1)
915         memcpy(f->block[1].energy, f->block[0].energy, sizeof(f->block[0].energy));
916
917     for (i = 0; i < 2; i++ ) {
918         CeltBlock *block = &f->block[i];
919
920         if (!f->transient) {
921             memcpy(block->prev_energy[1], block->prev_energy[0], sizeof(block->prev_energy[0]));
922             memcpy(block->prev_energy[0], block->energy,         sizeof(block->prev_energy[0]));
923         } else {
924             for (j = 0; j < CELT_MAX_BANDS; j++)
925                 block->prev_energy[0][j] = FFMIN(block->prev_energy[0][j], block->energy[j]);
926         }
927
928         for (j = 0; j < f->start_band; j++) {
929             block->prev_energy[0][j] = CELT_ENERGY_SILENCE;
930             block->energy[j]         = 0.0;
931         }
932         for (j = f->end_band; j < CELT_MAX_BANDS; j++) {
933             block->prev_energy[0][j] = CELT_ENERGY_SILENCE;
934             block->energy[j]         = 0.0;
935         }
936     }
937
938     f->seed = rc->range;
939
940     return 0;
941 }
942
943 void ff_celt_flush(CeltFrame *f)
944 {
945     int i, j;
946
947     if (f->flushed)
948         return;
949
950     for (i = 0; i < 2; i++) {
951         CeltBlock *block = &f->block[i];
952
953         for (j = 0; j < CELT_MAX_BANDS; j++)
954             block->prev_energy[0][j] = block->prev_energy[1][j] = CELT_ENERGY_SILENCE;
955
956         memset(block->energy, 0, sizeof(block->energy));
957         memset(block->buf,    0, sizeof(block->buf));
958
959         memset(block->pf_gains,     0, sizeof(block->pf_gains));
960         memset(block->pf_gains_old, 0, sizeof(block->pf_gains_old));
961         memset(block->pf_gains_new, 0, sizeof(block->pf_gains_new));
962
963         block->emph_coeff = 0.0;
964     }
965     f->seed = 0;
966
967     f->flushed = 1;
968 }
969
970 void ff_celt_free(CeltFrame **f)
971 {
972     CeltFrame *frm = *f;
973     int i;
974
975     if (!frm)
976         return;
977
978     for (i = 0; i < FF_ARRAY_ELEMS(frm->imdct); i++)
979         ff_mdct15_uninit(&frm->imdct[i]);
980
981     ff_celt_pvq_uninit(&frm->pvq);
982
983     av_freep(&frm->dsp);
984     av_freep(f);
985 }
986
987 int ff_celt_init(AVCodecContext *avctx, CeltFrame **f, int output_channels)
988 {
989     CeltFrame *frm;
990     int i, ret;
991
992     if (output_channels != 1 && output_channels != 2) {
993         av_log(avctx, AV_LOG_ERROR, "Invalid number of output channels: %d\n",
994                output_channels);
995         return AVERROR(EINVAL);
996     }
997
998     frm = av_mallocz(sizeof(*frm));
999     if (!frm)
1000         return AVERROR(ENOMEM);
1001
1002     frm->avctx           = avctx;
1003     frm->output_channels = output_channels;
1004
1005     for (i = 0; i < FF_ARRAY_ELEMS(frm->imdct); i++)
1006         if ((ret = ff_mdct15_init(&frm->imdct[i], 1, i + 3, -1.0f/32768)) < 0)
1007             goto fail;
1008
1009     if ((ret = ff_celt_pvq_init(&frm->pvq)) < 0)
1010         goto fail;
1011
1012     frm->dsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
1013     if (!frm->dsp) {
1014         ret = AVERROR(ENOMEM);
1015         goto fail;
1016     }
1017
1018     ff_celt_flush(frm);
1019
1020     *f = frm;
1021
1022     return 0;
1023 fail:
1024     ff_celt_free(&frm);
1025     return ret;
1026 }