Commit last ok'ed parts of QCELP decoder and enable it.
[ffmpeg.git] / libavcodec / qcelpdec.c
1 /*
2  * QCELP decoder
3  * Copyright (c) 2007 Reynaldo H. Verdejo Pinochet
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file qcelpdec.c
24  * QCELP decoder
25  * @author Reynaldo H. Verdejo Pinochet
26  * @remark FFmpeg merging spearheaded by Kenan Gillet
27  */
28
29 #include <stddef.h>
30
31 #include "avcodec.h"
32 #include "bitstream.h"
33
34 #include "qcelpdata.h"
35
36 #include "celp_math.h"
37 #include "celp_filters.h"
38
39 #undef NDEBUG
40 #include <assert.h>
41
42 typedef enum
43 {
44     I_F_Q = -1,    /*!< insufficient frame quality */
45     SILENCE,
46     RATE_OCTAVE,
47     RATE_QUARTER,
48     RATE_HALF,
49     RATE_FULL
50 } qcelp_packet_rate;
51
52 typedef struct {
53     GetBitContext     gb;
54     qcelp_packet_rate bitrate;
55     QCELPFrame        frame;                  /*!< unpacked data frame */
56     uint8_t           erasure_count;
57     uint8_t           octave_count;           /*!< count the consecutive RATE_OCTAVE frames */
58     float             prev_lspf[10];
59     float             predictor_lspf[10];     /*!< LSP predictor,
60                                                   only use for RATE_OCTAVE and I_F_Q */
61     float             pitch_synthesis_filter_mem[303];
62     float             pitch_pre_filter_mem[303];
63     float             rnd_fir_filter_mem[180];
64     float             formant_mem[170];
65     float             last_codebook_gain;
66     int               prev_g1[2];
67     int               prev_bitrate;
68     float             pitch_gain[4];
69     uint8_t           pitch_lag[4];
70     uint16_t          first16bits;
71 } QCELPContext;
72
73 /**
74  * Reconstructs LPC coefficients from the line spectral pair frequencies.
75  *
76  * TIA/EIA/IS-733 2.4.3.3.5
77  */
78 void ff_qcelp_lspf2lpc(const float *lspf, float *lpc);
79
80 static void weighted_vector_sumf(float *out, const float *in_a,
81                                  const float *in_b, float weight_coeff_a,
82                                  float weight_coeff_b, int length)
83 {
84     int i;
85
86     for(i=0; i<length; i++)
87         out[i] = weight_coeff_a * in_a[i]
88                + weight_coeff_b * in_b[i];
89 }
90
91 /**
92  * Initialize the speech codec according to the specification.
93  *
94  * TIA/EIA/IS-733 2.4.9
95  */
96 static av_cold int qcelp_decode_init(AVCodecContext *avctx)
97 {
98     QCELPContext *q = avctx->priv_data;
99     int i;
100
101     avctx->sample_fmt = SAMPLE_FMT_FLT;
102
103     for (i = 0; i < 10; i++)
104         q->prev_lspf[i] = (i + 1) / 11.;
105
106     return 0;
107 }
108
109 /**
110  * Decodes the 10 quantized LSP frequencies from the LSPV/LSP
111  * transmission codes of any bitrate and checks for badly received packets.
112  *
113  * @param q the context
114  * @param lspf line spectral pair frequencies
115  *
116  * @return 0 on success, -1 if the packet is badly received
117  *
118  * TIA/EIA/IS-733 2.4.3.2.6.2-2, 2.4.8.7.3
119  */
120 static int decode_lspf(QCELPContext *q, float *lspf)
121 {
122     int i;
123     float tmp_lspf;
124
125     if(q->bitrate == RATE_OCTAVE || q->bitrate == I_F_Q)
126     {
127         float smooth;
128         const float *predictors = (q->prev_bitrate != RATE_OCTAVE &&
129                                    q->prev_bitrate != I_F_Q ? q->prev_lspf
130                                                             : q->predictor_lspf);
131
132         if(q->bitrate == RATE_OCTAVE)
133         {
134             q->octave_count++;
135
136             for(i=0; i<10; i++)
137             {
138                 q->predictor_lspf[i] =
139                              lspf[i] = (q->frame.lspv[i] ?  QCELP_LSP_SPREAD_FACTOR
140                                                          : -QCELP_LSP_SPREAD_FACTOR)
141                                      + predictors[i] * QCELP_LSP_OCTAVE_PREDICTOR
142                                      + (i + 1) * ((1 - QCELP_LSP_OCTAVE_PREDICTOR)/11);
143             }
144             smooth = (q->octave_count < 10 ? .875 : 0.1);
145         }else
146         {
147             float erasure_coeff = QCELP_LSP_OCTAVE_PREDICTOR;
148
149             assert(q->bitrate == I_F_Q);
150
151             if(q->erasure_count > 1)
152                 erasure_coeff *= (q->erasure_count < 4 ? 0.9 : 0.7);
153
154             for(i=0; i<10; i++)
155             {
156                 q->predictor_lspf[i] =
157                              lspf[i] = (i + 1) * ( 1 - erasure_coeff)/11
158                                      + erasure_coeff * predictors[i];
159             }
160             smooth = 0.125;
161         }
162
163         // Check the stability of the LSP frequencies.
164         lspf[0] = FFMAX(lspf[0], QCELP_LSP_SPREAD_FACTOR);
165         for(i=1; i<10; i++)
166             lspf[i] = FFMAX(lspf[i], (lspf[i-1] + QCELP_LSP_SPREAD_FACTOR));
167
168         lspf[9] = FFMIN(lspf[9], (1.0 - QCELP_LSP_SPREAD_FACTOR));
169         for(i=9; i>0; i--)
170             lspf[i-1] = FFMIN(lspf[i-1], (lspf[i] - QCELP_LSP_SPREAD_FACTOR));
171
172         // Low-pass filter the LSP frequencies.
173         weighted_vector_sumf(lspf, lspf, q->prev_lspf, smooth, 1.0-smooth, 10);
174     }else
175     {
176         q->octave_count = 0;
177
178         tmp_lspf = 0.;
179         for(i=0; i<5 ; i++)
180         {
181             lspf[2*i+0] = tmp_lspf += qcelp_lspvq[i][q->frame.lspv[i]][0] * 0.0001;
182             lspf[2*i+1] = tmp_lspf += qcelp_lspvq[i][q->frame.lspv[i]][1] * 0.0001;
183         }
184
185         // Check for badly received packets.
186         if(q->bitrate == RATE_QUARTER)
187         {
188             if(lspf[9] <= .70 || lspf[9] >=  .97)
189                 return -1;
190             for(i=3; i<10; i++)
191                 if(fabs(lspf[i] - lspf[i-2]) < .08)
192                     return -1;
193         }else
194         {
195             if(lspf[9] <= .66 || lspf[9] >= .985)
196                 return -1;
197             for(i=4; i<10; i++)
198                 if (fabs(lspf[i] - lspf[i-4]) < .0931)
199                     return -1;
200         }
201     }
202     return 0;
203 }
204
205 /**
206  * Converts codebook transmission codes to GAIN and INDEX.
207  *
208  * @param q the context
209  * @param gain array holding the decoded gain
210  *
211  * TIA/EIA/IS-733 2.4.6.2
212  */
213 static void decode_gain_and_index(QCELPContext  *q,
214                                   float *gain) {
215     int   i, subframes_count, g1[16];
216     float slope;
217
218     if (q->bitrate >= RATE_QUARTER) {
219         switch (q->bitrate) {
220             case RATE_FULL: subframes_count = 16; break;
221             case RATE_HALF: subframes_count = 4;  break;
222             default:        subframes_count = 5;
223         }
224         for (i = 0; i < subframes_count; i++) {
225             g1[i] = 4 * q->frame.cbgain[i];
226             if (q->bitrate == RATE_FULL && !((i+1) & 3)) {
227                 g1[i] += av_clip((g1[i-1] + g1[i-2] + g1[i-3]) / 3 - 6, 0, 32);
228             }
229
230             gain[i] = qcelp_g12ga[g1[i]];
231
232             if (q->frame.cbsign[i]) {
233                 gain[i] = -gain[i];
234                 q->frame.cindex[i] = (q->frame.cindex[i]-89) & 127;
235             }
236         }
237
238         q->prev_g1[0] = g1[i-2];
239         q->prev_g1[1] = g1[i-1];
240         q->last_codebook_gain = qcelp_g12ga[g1[i-1]];
241
242         if (q->bitrate == RATE_QUARTER) {
243             // Provide smoothing of the unvoiced excitation energy.
244             gain[7] =     gain[4];
245             gain[6] = 0.4*gain[3] + 0.6*gain[4];
246             gain[5] =     gain[3];
247             gain[4] = 0.8*gain[2] + 0.2*gain[3];
248             gain[3] = 0.2*gain[1] + 0.8*gain[2];
249             gain[2] =     gain[1];
250             gain[1] = 0.6*gain[0] + 0.4*gain[1];
251         }
252     } else {
253         if (q->bitrate == RATE_OCTAVE) {
254             g1[0] = 2 * q->frame.cbgain[0]
255                   + av_clip((q->prev_g1[0] + q->prev_g1[1]) / 2 - 5, 0, 54);
256             subframes_count = 8;
257         } else {
258             assert(q->bitrate == I_F_Q);
259
260             g1[0] = q->prev_g1[1];
261             switch (q->erasure_count) {
262             case 1 : break;
263             case 2 : g1[0] -= 1; break;
264             case 3 : g1[0] -= 2; break;
265             default: g1[0] -= 6;
266             }
267             if (g1[0] < 0)
268                 g1[0] = 0;
269             subframes_count = 4;
270         }
271         // This interpolation is done to produce smoother background noise.
272         slope = 0.5*(qcelp_g12ga[g1[0]] - q->last_codebook_gain) / subframes_count;
273         for (i = 1; i <= subframes_count; i++)
274             gain[i-1] = q->last_codebook_gain + slope * i;
275         q->last_codebook_gain = gain[i-2];
276
277         q->prev_g1[0] = q->prev_g1[1];
278         q->prev_g1[1] = g1[0];
279     }
280 }
281
282 /**
283  * If the received packet is Rate 1/4 a further sanity check is made of the
284  * codebook gain.
285  *
286  * @param cbgain the unpacked cbgain array
287  * @return -1 if the sanity check fails, 0 otherwise
288  *
289  * TIA/EIA/IS-733 2.4.8.7.3
290  */
291 static int codebook_sanity_check_for_rate_quarter(const uint8_t *cbgain)
292 {
293     int i, prev_diff=0;
294
295     for(i=1; i<5; i++)
296     {
297         int diff = cbgain[i] - cbgain[i-1];
298         if(FFABS(diff) > 10)
299             return -1;
300         else if(FFABS(diff - prev_diff) > 12)
301             return -1;
302         prev_diff = diff;
303     }
304     return 0;
305 }
306
307 /**
308  * Computes the scaled codebook vector Cdn From INDEX and GAIN
309  * for all rates.
310  *
311  * The specification lacks some information here.
312  *
313  * TIA/EIA/IS-733 has an omission on the codebook index determination
314  * formula for RATE_FULL and RATE_HALF frames at section 2.4.8.1.1. It says
315  * you have to subtract the decoded index parameter from the given scaled
316  * codebook vector index 'n' to get the desired circular codebook index, but
317  * it does not mention that you have to clamp 'n' to [0-9] in order to get
318  * RI-compliant results.
319  *
320  * The reason for this mistake seems to be the fact they forgot to mention you
321  * have to do these calculations per codebook subframe and adjust given
322  * equation values accordingly.
323  *
324  * @param q the context
325  * @param gain array holding the 4 pitch subframe gain values
326  * @param cdn_vector array for the generated scaled codebook vector
327  */
328 static void compute_svector(const QCELPContext *q, const float *gain,
329                             float *cdn_vector)
330 {
331     int      i, j, k;
332     uint16_t cbseed, cindex;
333     float    *rnd, tmp_gain, fir_filter_value;
334
335     switch(q->bitrate)
336     {
337         case RATE_FULL:
338             for(i=0; i<16; i++)
339             {
340                 tmp_gain = gain[i] * QCELP_RATE_FULL_CODEBOOK_RATIO;
341                 cindex = -q->frame.cindex[i];
342                 for(j=0; j<10; j++)
343                     *cdn_vector++ = tmp_gain * qcelp_rate_full_codebook[cindex++ & 127];
344             }
345         break;
346         case RATE_HALF:
347             for(i=0; i<4; i++)
348             {
349                 tmp_gain = gain[i] * QCELP_RATE_HALF_CODEBOOK_RATIO;
350                 cindex = -q->frame.cindex[i];
351                 for (j = 0; j < 40; j++)
352                 *cdn_vector++ = tmp_gain * qcelp_rate_half_codebook[cindex++ & 127];
353             }
354         break;
355         case RATE_QUARTER:
356             cbseed = (0x0003 & q->frame.lspv[4])<<14 |
357                      (0x003F & q->frame.lspv[3])<< 8 |
358                      (0x0060 & q->frame.lspv[2])<< 1 |
359                      (0x0007 & q->frame.lspv[1])<< 3 |
360                      (0x0038 & q->frame.lspv[0])>> 3 ;
361             rnd = q->rnd_fir_filter_mem + 20;
362             for(i=0; i<8; i++)
363             {
364                 tmp_gain = gain[i] * (QCELP_SQRT1887 / 32768.0);
365                 for(k=0; k<20; k++)
366                 {
367                     cbseed = 521 * cbseed + 259;
368                     *rnd = (int16_t)cbseed;
369
370                     // FIR filter
371                     fir_filter_value = 0.0;
372                     for(j=0; j<10; j++)
373                         fir_filter_value += qcelp_rnd_fir_coefs[j ]
374                                           * (rnd[-j ] + rnd[-20+j]);
375
376                     fir_filter_value += qcelp_rnd_fir_coefs[10] * rnd[-10];
377                     *cdn_vector++ = tmp_gain * fir_filter_value;
378                     rnd++;
379                 }
380             }
381             memcpy(q->rnd_fir_filter_mem, q->rnd_fir_filter_mem + 160, 20 * sizeof(float));
382         break;
383         case RATE_OCTAVE:
384             cbseed = q->first16bits;
385             for(i=0; i<8; i++)
386             {
387                 tmp_gain = gain[i] * (QCELP_SQRT1887 / 32768.0);
388                 for(j=0; j<20; j++)
389                 {
390                     cbseed = 521 * cbseed + 259;
391                     *cdn_vector++ = tmp_gain * (int16_t)cbseed;
392                 }
393             }
394         break;
395         case I_F_Q:
396             cbseed = -44; // random codebook index
397             for(i=0; i<4; i++)
398             {
399                 tmp_gain = gain[i] * QCELP_RATE_FULL_CODEBOOK_RATIO;
400                 for(j=0; j<40; j++)
401                     *cdn_vector++ = tmp_gain * qcelp_rate_full_codebook[cbseed++ & 127];
402             }
403         break;
404     }
405 }
406
407 /**
408  * Apply generic gain control.
409  *
410  * @param v_out output vector
411  * @param v_in gain-controlled vector
412  * @param v_ref vector to control gain of
413  *
414  * FIXME: If v_ref is a zero vector, it energy is zero
415  *        and the behavior of the gain control is
416  *        undefined in the specs.
417  *
418  * TIA/EIA/IS-733 2.4.8.3-2/3/4/5, 2.4.8.6
419  */
420 static void apply_gain_ctrl(float *v_out, const float *v_ref,
421                             const float *v_in)
422 {
423     int   i, j, len;
424     float scalefactor;
425
426     for(i=0, j=0; i<4; i++)
427     {
428         scalefactor = ff_dot_productf(v_in + j, v_in + j, 40);
429         if(scalefactor)
430             scalefactor = sqrt(ff_dot_productf(v_ref + j, v_ref + j, 40)
431                         / scalefactor);
432         else
433             av_log_missing_feature(NULL, "Zero energy for gain control", 1);
434         for(len=j+40; j<len; j++)
435             v_out[j] = scalefactor * v_in[j];
436     }
437 }
438
439 /**
440  * Apply filter in pitch-subframe steps.
441  *
442  * @param memory buffer for the previous state of the filter
443  *        - must be able to contain 303 elements
444  *        - the 143 first elements are from the previous state
445  *        - the next 160 are for output
446  * @param v_in input filter vector
447  * @param gain per-subframe gain array, each element is between 0.0 and 2.0
448  * @param lag per-subframe lag array, each element is
449  *        - between 16 and 143 if its corresponding pfrac is 0,
450  *        - between 16 and 139 otherwise
451  * @param pfrac per-subframe boolean array, 1 if the lag is fractional, 0
452  *        otherwise
453  *
454  * @return filter output vector
455  */
456 static const float *do_pitchfilter(float memory[303], const float v_in[160],
457                                    const float gain[4], const uint8_t *lag,
458                                    const uint8_t pfrac[4])
459 {
460     int         i, j;
461     float       *v_lag, *v_out;
462     const float *v_len;
463
464     v_out = memory + 143; // Output vector starts at memory[143].
465
466     for(i=0; i<4; i++)
467     {
468         if(gain[i])
469         {
470             v_lag = memory + 143 + 40 * i - lag[i];
471             for(v_len=v_in+40; v_in<v_len; v_in++)
472             {
473                 if(pfrac[i]) // If it is a fractional lag...
474                 {
475                     for(j=0, *v_out=0.; j<4; j++)
476                         *v_out += qcelp_hammsinc_table[j] * (v_lag[j-4] + v_lag[3-j]);
477                 }else
478                     *v_out = *v_lag;
479
480                 *v_out = *v_in + gain[i] * *v_out;
481
482                 v_lag++;
483                 v_out++;
484             }
485         }else
486         {
487             memcpy(v_out, v_in, 40 * sizeof(float));
488             v_in  += 40;
489             v_out += 40;
490         }
491     }
492
493     memmove(memory, memory + 160, 143 * sizeof(float));
494     return memory + 143;
495 }
496
497 /**
498  * Apply pitch synthesis filter and pitch prefilter to the scaled codebook vector.
499  * TIA/EIA/IS-733 2.4.5.2
500  *
501  * @param q the context
502  * @param cdn_vector the scaled codebook vector
503  */
504 static void apply_pitch_filters(QCELPContext *q,
505                                 float *cdn_vector) {
506     int         i;
507     const float *v_synthesis_filtered, *v_pre_filtered;
508
509     if (q->bitrate >= RATE_HALF ||
510        (q->bitrate == I_F_Q && (q->prev_bitrate >= RATE_HALF))) {
511
512         if (q->bitrate >= RATE_HALF) {
513
514             // Compute gain & lag for the whole frame.
515             for (i = 0; i < 4; i++) {
516                 q->pitch_gain[i] = q->frame.plag[i] ? (q->frame.pgain[i] + 1) * 0.25 : 0.0;
517
518                 q->pitch_lag[i] = q->frame.plag[i] + 16;
519             }
520         } else {
521             float max_pitch_gain = q->erasure_count < 3 ? 0.9 - 0.3 * (q->erasure_count - 1)
522                                                         : 0.0;
523             for (i = 0; i < 4; i++)
524                 q->pitch_gain[i] = FFMIN(q->pitch_gain[i], max_pitch_gain);
525
526             memset(q->frame.pfrac, 0, sizeof(q->frame.pfrac));
527         }
528
529         // pitch synthesis filter
530         v_synthesis_filtered = do_pitchfilter(q->pitch_synthesis_filter_mem, cdn_vector,
531                                               q->pitch_gain, q->pitch_lag, q->frame.pfrac);
532
533         // pitch prefilter update
534         for (i = 0; i < 4; i++)
535             q->pitch_gain[i] = 0.5 * FFMIN(q->pitch_gain[i], 1.0);
536
537         v_pre_filtered = do_pitchfilter(q->pitch_pre_filter_mem, v_synthesis_filtered,
538                                         q->pitch_gain, q->pitch_lag, q->frame.pfrac);
539
540         apply_gain_ctrl(cdn_vector, v_synthesis_filtered, v_pre_filtered);
541     } else {
542         memcpy(q->pitch_synthesis_filter_mem, cdn_vector + 17, 143 * sizeof(float));
543         memcpy(q->pitch_pre_filter_mem,       cdn_vector + 17, 143 * sizeof(float));
544         memset(q->pitch_gain, 0, sizeof(q->pitch_gain));
545         memset(q->pitch_lag,  0, sizeof(q->pitch_lag));
546     }
547 }
548
549 /**
550  * Interpolates LSP frequencies and computes LPC coefficients
551  * for a given bitrate & pitch subframe.
552  *
553  * TIA/EIA/IS-733 2.4.3.3.4
554  *
555  * @param q the context
556  * @param curr_lspf LSP frequencies vector of the current frame
557  * @param lpc float vector for the resulting LPC
558  * @param subframe_num frame number in decoded stream
559  */
560 void interpolate_lpc(QCELPContext *q, const float *curr_lspf, float *lpc,
561                      const int subframe_num)
562 {
563     float interpolated_lspf[10];
564     float weight;
565
566     if(q->bitrate >= RATE_QUARTER)
567         weight = 0.25 * (subframe_num + 1);
568     else if(q->bitrate == RATE_OCTAVE && !subframe_num)
569         weight = 0.625;
570     else
571         weight = 1.0;
572
573     if(weight != 1.0)
574     {
575         weighted_vector_sumf(interpolated_lspf, curr_lspf, q->prev_lspf,
576                              weight, 1.0 - weight, 10);
577         ff_qcelp_lspf2lpc(interpolated_lspf, lpc);
578     }else if(q->bitrate >= RATE_QUARTER || (q->bitrate == I_F_Q && !subframe_num))
579         ff_qcelp_lspf2lpc(curr_lspf, lpc);
580 }
581
582 static int buf_size2bitrate(const int buf_size)
583 {
584     switch(buf_size)
585     {
586         case 35:
587             return RATE_FULL;
588         case 17:
589             return RATE_HALF;
590         case  8:
591             return RATE_QUARTER;
592         case  4:
593             return RATE_OCTAVE;
594         case  1:
595             return SILENCE;
596     }
597
598     return -1;
599 }
600
601 /**
602  * Determine the bitrate from the frame size and/or the first byte of the frame.
603  *
604  * @param avctx the AV codec context
605  * @param buf_size length of the buffer
606  * @param buf the bufffer
607  *
608  * @return the bitrate on success,
609  *         I_F_Q  if the bitrate cannot be satisfactorily determined
610  *
611  * TIA/EIA/IS-733 2.4.8.7.1
612  */
613 static int determine_bitrate(AVCodecContext *avctx,
614                                const int buf_size,
615                                uint8_t **buf) {
616     qcelp_packet_rate bitrate;
617
618     if ((bitrate = buf_size2bitrate(buf_size)) >= 0) {
619         if (bitrate > **buf) {
620             av_log(avctx, AV_LOG_WARNING, "Claimed bitrate and buffer size mismatch.\n");
621             bitrate = **buf;
622         } else if (bitrate < **buf) {
623             av_log(avctx, AV_LOG_ERROR, "Buffer is too small for the claimed bitrate.\n");
624             return I_F_Q;
625         }
626         (*buf)++;
627     } else if ((bitrate = buf_size2bitrate(buf_size + 1)) >= 0) {
628         av_log(avctx, AV_LOG_WARNING,
629                "Bitrate byte is missing, guessing the bitrate from packet size.\n");
630     } else
631         return I_F_Q;
632
633     if (bitrate == SILENCE) {
634         // FIXME: the decoder should not handle SILENCE frames as I_F_Q frames
635         av_log_missing_feature(avctx, "Blank frame", 1);
636         bitrate = I_F_Q;
637     }
638     return bitrate;
639 }
640
641 static void warn_insufficient_frame_quality(AVCodecContext *avctx,
642                                             const char *message)
643 {
644     av_log(avctx, AV_LOG_WARNING, "Frame #%d, IFQ: %s\n", avctx->frame_number,
645            message);
646 }
647
648 static int qcelp_decode_frame(AVCodecContext *avctx,
649                               void *data,
650                               int *data_size,
651                               uint8_t *buf,
652                               const int buf_size) {
653     QCELPContext      *q = avctx->priv_data;
654     float             *outbuffer = data;
655     int               i;
656     float             quantized_lspf[10], lpc[10];
657     float             gain[16];
658     float             *formant_mem;
659
660     if ((q->bitrate = determine_bitrate(avctx, buf_size, &buf)) == I_F_Q) {
661         warn_insufficient_frame_quality(avctx, "bitrate cannot be determined.");
662         goto erasure;
663     }
664
665     if (q->bitrate == RATE_OCTAVE &&
666        (q->first16bits = AV_RB16(buf)) == 0xFFFF) {
667         warn_insufficient_frame_quality(avctx, "Bitrate is 1/8 and first 16 bits are on.");
668         goto erasure;
669     }
670
671     if (q->bitrate > SILENCE) {
672         const QCELPBitmap *bitmaps     = qcelp_unpacking_bitmaps_per_rate[q->bitrate];
673         const QCELPBitmap *bitmaps_end = qcelp_unpacking_bitmaps_per_rate[q->bitrate]
674                                        + qcelp_unpacking_bitmaps_lengths[q->bitrate];
675         uint8_t           *unpacked_data = (uint8_t *)&q->frame;
676
677         init_get_bits(&q->gb, buf, 8*buf_size);
678
679         memset(&q->frame, 0, sizeof(QCELPFrame));
680
681         for (; bitmaps < bitmaps_end; bitmaps++)
682             unpacked_data[bitmaps->index] |= get_bits(&q->gb, bitmaps->bitlen) << bitmaps->bitpos;
683
684         // Check for erasures/blanks on rates 1, 1/4 and 1/8.
685         if (q->frame.reserved) {
686             warn_insufficient_frame_quality(avctx, "Wrong data in reserved frame area.");
687             goto erasure;
688         }
689         if (q->bitrate == RATE_QUARTER && codebook_sanity_check_for_rate_quarter(q->frame.cbgain)) {
690             warn_insufficient_frame_quality(avctx, "Codebook gain sanity check failed.");
691             goto erasure;
692         }
693
694         if (q->bitrate >= RATE_HALF) {
695             for (i = 0; i < 4; i++) {
696                 if (q->frame.pfrac[i] && q->frame.plag[i] >= 124) {
697                     warn_insufficient_frame_quality(avctx, "Cannot initialize pitch filter.");
698                     goto erasure;
699                 }
700             }
701         }
702     }
703
704     decode_gain_and_index(q, gain);
705     compute_svector(q, gain, outbuffer);
706
707     if (decode_lspf(q, quantized_lspf) < 0) {
708         warn_insufficient_frame_quality(avctx, "Badly received packets in frame.");
709         goto erasure;
710     }
711
712
713     apply_pitch_filters(q, outbuffer);
714
715     if (q->bitrate == I_F_Q) {
716 erasure:
717         q->bitrate = I_F_Q;
718         q->erasure_count++;
719         decode_gain_and_index(q, gain);
720         compute_svector(q, gain, outbuffer);
721         decode_lspf(q, quantized_lspf);
722         apply_pitch_filters(q, outbuffer);
723     } else
724         q->erasure_count = 0;
725
726     formant_mem = q->formant_mem + 10;
727     for (i = 0; i < 4; i++) {
728         interpolate_lpc(q, quantized_lspf, lpc, i);
729         ff_celp_lp_synthesis_filterf(formant_mem, lpc, outbuffer + i * 40, 40, 10);
730         formant_mem += 40;
731     }
732     memcpy(q->formant_mem, q->formant_mem + 160, 10 * sizeof(float));
733
734     // FIXME: postfilter and final gain control should be here.
735     // TIA/EIA/IS-733 2.4.8.6
736
737     formant_mem = q->formant_mem + 10;
738     for (i = 0; i < 160; i++)
739         *outbuffer++ = av_clipf(*formant_mem++, QCELP_CLIP_LOWER_BOUND, QCELP_CLIP_UPPER_BOUND);
740
741     memcpy(q->prev_lspf, quantized_lspf, sizeof(q->prev_lspf));
742     q->prev_bitrate = q->bitrate;
743
744     *data_size = 160 * sizeof(*outbuffer);
745
746     return *data_size;
747 }
748
749 AVCodec qcelp_decoder =
750 {
751     .name   = "qcelp",
752     .type   = CODEC_TYPE_AUDIO,
753     .id     = CODEC_ID_QCELP,
754     .init   = qcelp_decode_init,
755     .decode = qcelp_decode_frame,
756     .priv_data_size = sizeof(QCELPContext),
757     .long_name = NULL_IF_CONFIG_SMALL("QCELP / PureVoice"),
758 };