]> git.sesse.net Git - ffmpeg/blob - libavcodec/qcelpdec.c
04b714aec25b199dcc5ee368643b4f0c41326034
[ffmpeg] / 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  */
27
28 #include <stddef.h>
29
30 #include "avcodec.h"
31 #include "bitstream.h"
32
33 #include "qcelp.h"
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 static void weighted_vector_sumf(float *out, const float *in_a,
43                                  const float *in_b, float weight_coeff_a,
44                                  float weight_coeff_b, int length)
45 {
46     int i;
47
48     for(i=0; i<length; i++)
49         out[i] = weight_coeff_a * in_a[i]
50                + weight_coeff_b * in_b[i];
51 }
52
53 /**
54  * Initialize the speech codec according to the specification.
55  *
56  * TIA/EIA/IS-733 2.4.9
57  */
58 static av_cold int qcelp_decode_init(AVCodecContext *avctx) {
59     QCELPContext *q = avctx->priv_data;
60     int i;
61
62     avctx->sample_fmt = SAMPLE_FMT_FLT;
63
64     for (i = 0; i < 10; i++)
65         q->prev_lspf[i] = (i + 1) / 11.;
66
67     return 0;
68 }
69
70 /**
71  * Computes the scaled codebook vector Cdn From INDEX and GAIN
72  * for all rates.
73  *
74  * The specification lacks some information here.
75  *
76  * TIA/EIA/IS-733 has an omission on the codebook index determination
77  * formula for RATE_FULL and RATE_HALF frames at section 2.4.8.1.1. It says
78  * you have to subtract the decoded index parameter from the given scaled
79  * codebook vector index 'n' to get the desired circular codebook index, but
80  * it does not mention that you have to clamp 'n' to [0-9] in order to get
81  * RI-compliant results.
82  *
83  * The reason for this mistake seems to be the fact they forgot to mention you
84  * have to do these calculations per codebook subframe and adjust given
85  * equation values accordingly.
86  *
87  * @param q the context
88  * @param gain array holding the 4 pitch subframe gain values
89  * @param cdn_vector array for the generated scaled codebook vector
90  */
91 static void compute_svector(const QCELPContext *q,
92                             const float *gain,
93                             float *cdn_vector) {
94     int      i, j, k;
95     uint16_t cbseed, cindex;
96     float    *rnd, tmp_gain, fir_filter_value;
97
98     switch (q->framerate) {
99     case RATE_FULL:
100         for (i = 0; i < 16; i++) {
101             tmp_gain = gain[i] * QCELP_RATE_FULL_CODEBOOK_RATIO;
102             cindex = -q->cindex[i];
103             for (j = 0; j < 10; j++)
104                 *cdn_vector++ = tmp_gain * qcelp_rate_full_codebook[cindex++ & 127];
105         }
106         break;
107     case RATE_HALF:
108         for (i = 0; i < 4; i++) {
109             tmp_gain = gain[i] * QCELP_RATE_HALF_CODEBOOK_RATIO;
110             cindex = -q->cindex[i];
111             for (j = 0; j < 40; j++)
112                 *cdn_vector++ = tmp_gain * qcelp_rate_half_codebook[cindex++ & 127];
113         }
114         break;
115     case RATE_QUARTER:
116         cbseed = (0x0003 & q->lspv[4])<<14 |
117                  (0x003F & q->lspv[3])<< 8 |
118                  (0x0060 & q->lspv[2])<< 1 |
119                  (0x0007 & q->lspv[1])<< 3 |
120                  (0x0038 & q->lspv[0])>> 3 ;
121         rnd = q->rnd_fir_filter_mem + 20;
122         for (i = 0; i < 8; i++) {
123             tmp_gain = gain[i] * (QCELP_SQRT1887 / 32768.0);
124             for (k = 0; k < 20; k++) {
125                 cbseed = 521 * cbseed + 259;
126                 *rnd = (int16_t)cbseed;
127
128                 // FIR filter
129                 fir_filter_value = 0.0;
130                 for (j = 0; j < 10; j++)
131                     fir_filter_value += qcelp_rnd_fir_coefs[j ] * (rnd[-j ] + rnd[-20+j]);
132                 fir_filter_value     += qcelp_rnd_fir_coefs[10] *  rnd[-10];
133
134                 *cdn_vector++ = tmp_gain * fir_filter_value;
135                 rnd++;
136             }
137         }
138         memcpy(q->rnd_fir_filter_mem, q->rnd_fir_filter_mem + 160, 20 * sizeof(float));
139         break;
140     case RATE_OCTAVE:
141         cbseed = q->first16bits;
142         for (i = 0; i < 8; i++) {
143             tmp_gain = gain[i] * (QCELP_SQRT1887 / 32768.0);
144             for (j = 0; j < 20; j++) {
145                 cbseed = 521 * cbseed + 259;
146                 *cdn_vector++ = tmp_gain * (int16_t)cbseed;
147             }
148         }
149         break;
150     case I_F_Q:
151         cbseed = -44; // random codebook index
152         for (i = 0; i < 4; i++) {
153             tmp_gain = gain[i] * QCELP_RATE_FULL_CODEBOOK_RATIO;
154             for (j = 0; j < 40; j++)
155                 *cdn_vector++ = tmp_gain * qcelp_rate_full_codebook[cbseed++ & 127];
156         }
157         break;
158     }
159 }
160
161 /**
162  * Apply generic gain control.
163  *
164  * @param v_out output vector
165  * @param v_in gain-controlled vector
166  * @param v_ref vector to control gain of
167  *
168  * FIXME: If v_ref is a zero vector, it energy is zero
169  *        and the behavior of the gain control is
170  *        undefined in the specs.
171  *
172  * TIA/EIA/IS-733 2.4.8.3-2/3/4/5, 2.4.8.6
173  */
174 static void apply_gain_ctrl(float *v_out,
175                             const float *v_ref,
176                             const float *v_in) {
177     int   i, j, len;
178     float scalefactor;
179
180     for (i = 0, j = 0; i < 4; i++) {
181         scalefactor = ff_dot_productf(v_in + j, v_in + j, 40);
182         if (scalefactor)
183             scalefactor = sqrt(ff_dot_productf(v_ref + j, v_ref + j, 40) / scalefactor);
184         else
185             av_log_missing_feature(NULL, "Zero energy for gain control", 1);
186         for (len = j + 40; j < len; j++)
187             v_out[j] = scalefactor * v_in[j];
188     }
189 }
190
191 /**
192  * Apply filter in pitch-subframe steps.
193  *
194  * @param memory buffer for the previous state of the filter
195  *        - must be able to contain 303 elements
196  *        - the 143 first elements are from the previous state
197  *        - the next 160 are for output
198  * @param v_in input filter vector
199  * @param gain per-subframe gain array, each element is between 0.0 and 2.0
200  * @param lag per-subframe lag array, each element is
201  *        - between 16 and 143 if its corresponding pfrac is 0,
202  *        - between 16 and 139 otherwise
203  * @param pfrac per-subframe boolean array, 1 if the lag is fractional, 0 otherwise
204  *
205  * @return filter output vector
206  */
207 static const float *do_pitchfilter(float memory[303], const float v_in[160],
208                                    const float gain[4], const uint8_t *lag,
209                                    const uint8_t pfrac[4])
210 {
211     int         i, j;
212     float       *v_lag, *v_out;
213     const float *v_len;
214
215     v_out = memory + 143; // Output vector starts at memory[143].
216
217     for(i=0; i<4; i++)
218     {
219         if(gain[i])
220         {
221             v_lag = memory + 143 + 40 * i - lag[i];
222             for(v_len=v_in+40; v_in<v_len; v_in++)
223             {
224                 if(pfrac[i]) // If it is a fractional lag...
225                 {
226                     for(j=0, *v_out=0.; j<4; j++)
227                         *v_out += qcelp_hammsinc_table[j] * (v_lag[j-4] + v_lag[3-j]);
228                 }else
229                     *v_out = *v_lag;
230
231                 *v_out = *v_in + gain[i] * *v_out;
232
233                 v_lag++;
234                 v_out++;
235             }
236         }else
237         {
238             memcpy(v_out, v_in, 40 * sizeof(float));
239             v_in  += 40;
240             v_out += 40;
241         }
242     }
243
244     memmove(memory, memory + 160, 143 * sizeof(float));
245     return memory + 143;
246 }
247
248 /**
249  * Interpolates LSP frequencies and computes LPC coefficients
250  * for a given framerate & pitch subframe.
251  *
252  * TIA/EIA/IS-733 2.4.3.3.4
253  *
254  * @param q the context
255  * @param curr_lspf LSP frequencies vector of the current frame
256  * @param lpc float vector for the resulting LPC
257  * @param subframe_num frame number in decoded stream
258  */
259 void interpolate_lpc(QCELPContext *q, const float *curr_lspf, float *lpc,
260                      const int subframe_num)
261 {
262     float interpolated_lspf[10];
263     float weight;
264
265     if(q->framerate >= RATE_QUARTER)
266         weight = 0.25 * (subframe_num + 1);
267     else if(q->framerate == RATE_OCTAVE && !subframe_num)
268         weight = 0.625;
269     else
270         weight = 1.0;
271
272     if(weight != 1.0)
273     {
274         weighted_vector_sumf(interpolated_lspf, curr_lspf, q->prev_lspf,
275                              weight, 1.0 - weight, 10);
276         qcelp_lspf2lpc(interpolated_lspf, lpc);
277     }else if(q->framerate >= RATE_QUARTER || (q->framerate == I_F_Q && !subframe_num))
278         qcelp_lspf2lpc(curr_lspf, lpc);
279 }
280
281 static int buf_size2framerate(const int buf_size)
282 {
283     switch(buf_size)
284     {
285         case 35:
286             return RATE_FULL;
287         case 17:
288             return RATE_HALF;
289         case  8:
290             return RATE_QUARTER;
291         case  4:
292             return RATE_OCTAVE;
293         case  1:
294             return SILENCE;
295     }
296
297     return -1;
298 }
299
300 static void warn_insufficient_frame_quality(AVCodecContext *avctx,
301                                             const char *message)
302 {
303     av_log(avctx, AV_LOG_WARNING, "Frame #%d, IFQ: %s\n", avctx->frame_number,
304            message);
305 }
306
307 AVCodec qcelp_decoder =
308 {
309     .name   = "qcelp",
310     .type   = CODEC_TYPE_AUDIO,
311     .id     = CODEC_ID_QCELP,
312     .init   = qcelp_decode_init,
313     .decode = qcelp_decode_frame,
314     .priv_data_size = sizeof(QCELPContext),
315     .long_name = NULL_IF_CONFIG_SMALL("QCELP / PureVoice"),
316 };