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