1dff368050caaa817a940f59adb450b8dde0407a
[libav.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 "qcelp.h"
35 #include "qcelpdata.h"
36
37 #include "celp_math.h"
38 #include "celp_filters.h"
39
40 #undef NDEBUG
41 #include <assert.h>
42
43 static void weighted_vector_sumf(float *out, const float *in_a,
44 const float *in_b, float weight_coeff_a,
45 float weight_coeff_b, int length)
46 {
47 int i;
48
49 for(i=0; i<length; i++)
50 out[i] = weight_coeff_a * in_a[i]
51 + weight_coeff_b * in_b[i];
52 }
53
54 /**
55 * Initialize the speech codec according to the specification.
56 *
57 * TIA/EIA/IS-733 2.4.9
58 */
59 static av_cold int qcelp_decode_init(AVCodecContext *avctx) {
60 QCELPContext *q = avctx->priv_data;
61 int i;
62
63 avctx->sample_fmt = SAMPLE_FMT_FLT;
64
65 for (i = 0; i < 10; i++)
66 q->prev_lspf[i] = (i + 1) / 11.;
67
68 return 0;
69 }
70
71 /**
72 * Decodes the 10 quantized LSP frequencies from the LSPV/LSP
73 * transmission codes of any bitrate and checks for badly received packets.
74 *
75 * @param q the context
76 * @param lspf line spectral pair frequencies
77 *
78 * @return 0 on success, -1 if the packet is badly received
79 *
80 * TIA/EIA/IS-733 2.4.3.2.6.2-2, 2.4.8.7.3
81 */
82 static int decode_lspf(QCELPContext *q,
83 float *lspf) {
84 int i;
85 float tmp_lspf;
86
87 if (q->bitrate == RATE_OCTAVE ||
88 q->bitrate == I_F_Q) {
89 float smooth;
90 const float *predictors = (q->prev_bitrate != RATE_OCTAVE &&
91 q->prev_bitrate != I_F_Q ? q->prev_lspf
92 : q->predictor_lspf);
93
94 if (q->bitrate == RATE_OCTAVE) {
95 q->octave_count++;
96
97 for (i = 0; i < 10; i++) {
98 q->predictor_lspf[i] =
99 lspf[i] = (q->lspv[i] ? QCELP_LSP_SPREAD_FACTOR
100 : -QCELP_LSP_SPREAD_FACTOR)
101 + predictors[i] * QCELP_LSP_OCTAVE_PREDICTOR
102 + (i + 1) * ((1 - QCELP_LSP_OCTAVE_PREDICTOR)/11);
103 }
104 smooth = (q->octave_count < 10 ? .875 : 0.1);
105 } else {
106 float erasure_coeff = QCELP_LSP_OCTAVE_PREDICTOR;
107
108 assert(q->bitrate == I_F_Q);
109
110 if (q->erasure_count > 1)
111 erasure_coeff *= (q->erasure_count < 4 ? 0.9 : 0.7);
112
113 for (i = 0; i < 10; i++) {
114 q->predictor_lspf[i] =
115 lspf[i] = (i + 1) * ( 1 - erasure_coeff)/11
116 + erasure_coeff * predictors[i];
117 }
118 smooth = 0.125;
119 }
120
121 // Check the stability of the LSP frequencies.
122 lspf[0] = FFMAX(lspf[0], QCELP_LSP_SPREAD_FACTOR);
123 for (i = 1; i < 10; i++)
124 lspf[i] = FFMAX(lspf[i], (lspf[i-1] + QCELP_LSP_SPREAD_FACTOR));
125
126 lspf[9] = FFMIN(lspf[9], (1.0 - QCELP_LSP_SPREAD_FACTOR));
127 for (i = 9; i > 0; i--)
128 lspf[i-1] = FFMIN(lspf[i-1], (lspf[i] - QCELP_LSP_SPREAD_FACTOR));
129
130 // Low-pass filter the LSP frequencies.
131 weighted_vector_sumf(lspf, lspf, q->prev_lspf, smooth, 1.0 - smooth, 10);
132 } else {
133 q->octave_count = 0;
134
135 tmp_lspf = 0.;
136 for (i = 0; i < 5 ; i++) {
137 lspf[2*i+0] = tmp_lspf += qcelp_lspvq[i][q->lspv[i]][0] * 0.0001;
138 lspf[2*i+1] = tmp_lspf += qcelp_lspvq[i][q->lspv[i]][1] * 0.0001;
139 }
140
141 // Check for badly received packets.
142 if (q->bitrate == RATE_QUARTER) {
143 if (lspf[9] <= .70 || lspf[9] >= .97)
144 return -1;
145 for (i = 3; i < 10; i++)
146 if (fabs(lspf[i] - lspf[i-2]) < .08)
147 return -1;
148 } else {
149 if (lspf[9] <= .66 || lspf[9] >= .985)
150 return -1;
151 for (i = 4; i < 10; i++)
152 if (fabs(lspf[i] - lspf[i-4]) < .0931)
153 return -1;
154 }
155 }
156 return 0;
157 }
158
159 /**
160 * If the received packet is Rate 1/4 a further sanity check is made of the codebook gain.
161 *
162 * @param cbgain the unpacked cbgain array
163 * @return -1 if the sanity check fails, 0 otherwise
164 *
165 * TIA/EIA/IS-733 2.4.8.7.3
166 */
167 static int codebook_sanity_check_for_rate_quarter(const uint8_t *cbgain) {
168 int i, prev_diff=0;
169
170 for (i = 1; i < 5; i++) {
171 int diff = cbgain[i] - cbgain[i-1];
172 if (FFABS(diff) > 10)
173 return -1;
174 else if (FFABS(diff - prev_diff) > 12)
175 return -1;
176 prev_diff = diff;
177 }
178 return 0;
179 }
180
181 /**
182 * Computes the scaled codebook vector Cdn From INDEX and GAIN
183 * for all rates.
184 *
185 * The specification lacks some information here.
186 *
187 * TIA/EIA/IS-733 has an omission on the codebook index determination
188 * formula for RATE_FULL and RATE_HALF frames at section 2.4.8.1.1. It says
189 * you have to subtract the decoded index parameter from the given scaled
190 * codebook vector index 'n' to get the desired circular codebook index, but
191 * it does not mention that you have to clamp 'n' to [0-9] in order to get
192 * RI-compliant results.
193 *
194 * The reason for this mistake seems to be the fact they forgot to mention you
195 * have to do these calculations per codebook subframe and adjust given
196 * equation values accordingly.
197 *
198 * @param q the context
199 * @param gain array holding the 4 pitch subframe gain values
200 * @param cdn_vector array for the generated scaled codebook vector
201 */
202 static void compute_svector(const QCELPContext *q,
203 const float *gain,
204 float *cdn_vector) {
205 int i, j, k;
206 uint16_t cbseed, cindex;
207 float *rnd, tmp_gain, fir_filter_value;
208
209 switch (q->bitrate) {
210 case RATE_FULL:
211 for (i = 0; i < 16; i++) {
212 tmp_gain = gain[i] * QCELP_RATE_FULL_CODEBOOK_RATIO;
213 cindex = -q->cindex[i];
214 for (j = 0; j < 10; j++)
215 *cdn_vector++ = tmp_gain * qcelp_rate_full_codebook[cindex++ & 127];
216 }
217 break;
218 case RATE_HALF:
219 for (i = 0; i < 4; i++) {
220 tmp_gain = gain[i] * QCELP_RATE_HALF_CODEBOOK_RATIO;
221 cindex = -q->cindex[i];
222 for (j = 0; j < 40; j++)
223 *cdn_vector++ = tmp_gain * qcelp_rate_half_codebook[cindex++ & 127];
224 }
225 break;
226 case RATE_QUARTER:
227 cbseed = (0x0003 & q->lspv[4])<<14 |
228 (0x003F & q->lspv[3])<< 8 |
229 (0x0060 & q->lspv[2])<< 1 |
230 (0x0007 & q->lspv[1])<< 3 |
231 (0x0038 & q->lspv[0])>> 3 ;
232 rnd = q->rnd_fir_filter_mem + 20;
233 for (i = 0; i < 8; i++) {
234 tmp_gain = gain[i] * (QCELP_SQRT1887 / 32768.0);
235 for (k = 0; k < 20; k++) {
236 cbseed = 521 * cbseed + 259;
237 *rnd = (int16_t)cbseed;
238
239 // FIR filter
240 fir_filter_value = 0.0;
241 for (j = 0; j < 10; j++)
242 fir_filter_value += qcelp_rnd_fir_coefs[j ] * (rnd[-j ] + rnd[-20+j]);
243 fir_filter_value += qcelp_rnd_fir_coefs[10] * rnd[-10];
244
245 *cdn_vector++ = tmp_gain * fir_filter_value;
246 rnd++;
247 }
248 }
249 memcpy(q->rnd_fir_filter_mem, q->rnd_fir_filter_mem + 160, 20 * sizeof(float));
250 break;
251 case RATE_OCTAVE:
252 cbseed = q->first16bits;
253 for (i = 0; i < 8; i++) {
254 tmp_gain = gain[i] * (QCELP_SQRT1887 / 32768.0);
255 for (j = 0; j < 20; j++) {
256 cbseed = 521 * cbseed + 259;
257 *cdn_vector++ = tmp_gain * (int16_t)cbseed;
258 }
259 }
260 break;
261 case I_F_Q:
262 cbseed = -44; // random codebook index
263 for (i = 0; i < 4; i++) {
264 tmp_gain = gain[i] * QCELP_RATE_FULL_CODEBOOK_RATIO;
265 for (j = 0; j < 40; j++)
266 *cdn_vector++ = tmp_gain * qcelp_rate_full_codebook[cbseed++ & 127];
267 }
268 break;
269 }
270 }
271
272 /**
273 * Apply generic gain control.
274 *
275 * @param v_out output vector
276 * @param v_in gain-controlled vector
277 * @param v_ref vector to control gain of
278 *
279 * FIXME: If v_ref is a zero vector, it energy is zero
280 * and the behavior of the gain control is
281 * undefined in the specs.
282 *
283 * TIA/EIA/IS-733 2.4.8.3-2/3/4/5, 2.4.8.6
284 */
285 static void apply_gain_ctrl(float *v_out,
286 const float *v_ref,
287 const float *v_in) {
288 int i, j, len;
289 float scalefactor;
290
291 for (i = 0, j = 0; i < 4; i++) {
292 scalefactor = ff_dot_productf(v_in + j, v_in + j, 40);
293 if (scalefactor)
294 scalefactor = sqrt(ff_dot_productf(v_ref + j, v_ref + j, 40) / scalefactor);
295 else
296 av_log_missing_feature(NULL, "Zero energy for gain control", 1);
297 for (len = j + 40; j < len; j++)
298 v_out[j] = scalefactor * v_in[j];
299 }
300 }
301
302 /**
303 * Apply filter in pitch-subframe steps.
304 *
305 * @param memory buffer for the previous state of the filter
306 * - must be able to contain 303 elements
307 * - the 143 first elements are from the previous state
308 * - the next 160 are for output
309 * @param v_in input filter vector
310 * @param gain per-subframe gain array, each element is between 0.0 and 2.0
311 * @param lag per-subframe lag array, each element is
312 * - between 16 and 143 if its corresponding pfrac is 0,
313 * - between 16 and 139 otherwise
314 * @param pfrac per-subframe boolean array, 1 if the lag is fractional, 0 otherwise
315 *
316 * @return filter output vector
317 */
318 static const float *do_pitchfilter(float memory[303], const float v_in[160],
319 const float gain[4], const uint8_t *lag,
320 const uint8_t pfrac[4])
321 {
322 int i, j;
323 float *v_lag, *v_out;
324 const float *v_len;
325
326 v_out = memory + 143; // Output vector starts at memory[143].
327
328 for(i=0; i<4; i++)
329 {
330 if(gain[i])
331 {
332 v_lag = memory + 143 + 40 * i - lag[i];
333 for(v_len=v_in+40; v_in<v_len; v_in++)
334 {
335 if(pfrac[i]) // If it is a fractional lag...
336 {
337 for(j=0, *v_out=0.; j<4; j++)
338 *v_out += qcelp_hammsinc_table[j] * (v_lag[j-4] + v_lag[3-j]);
339 }else
340 *v_out = *v_lag;
341
342 *v_out = *v_in + gain[i] * *v_out;
343
344 v_lag++;
345 v_out++;
346 }
347 }else
348 {
349 memcpy(v_out, v_in, 40 * sizeof(float));
350 v_in += 40;
351 v_out += 40;
352 }
353 }
354
355 memmove(memory, memory + 160, 143 * sizeof(float));
356 return memory + 143;
357 }
358
359 /**
360 * Interpolates LSP frequencies and computes LPC coefficients
361 * for a given bitrate & pitch subframe.
362 *
363 * TIA/EIA/IS-733 2.4.3.3.4
364 *
365 * @param q the context
366 * @param curr_lspf LSP frequencies vector of the current frame
367 * @param lpc float vector for the resulting LPC
368 * @param subframe_num frame number in decoded stream
369 */
370 void interpolate_lpc(QCELPContext *q, const float *curr_lspf, float *lpc,
371 const int subframe_num)
372 {
373 float interpolated_lspf[10];
374 float weight;
375
376 if(q->bitrate >= RATE_QUARTER)
377 weight = 0.25 * (subframe_num + 1);
378 else if(q->bitrate == RATE_OCTAVE && !subframe_num)
379 weight = 0.625;
380 else
381 weight = 1.0;
382
383 if(weight != 1.0)
384 {
385 weighted_vector_sumf(interpolated_lspf, curr_lspf, q->prev_lspf,
386 weight, 1.0 - weight, 10);
387 qcelp_lspf2lpc(interpolated_lspf, lpc);
388 }else if(q->bitrate >= RATE_QUARTER || (q->bitrate == I_F_Q && !subframe_num))
389 qcelp_lspf2lpc(curr_lspf, lpc);
390 }
391
392 static int buf_size2bitrate(const int buf_size)
393 {
394 switch(buf_size)
395 {
396 case 35:
397 return RATE_FULL;
398 case 17:
399 return RATE_HALF;
400 case 8:
401 return RATE_QUARTER;
402 case 4:
403 return RATE_OCTAVE;
404 case 1:
405 return SILENCE;
406 }
407
408 return -1;
409 }
410
411 static void warn_insufficient_frame_quality(AVCodecContext *avctx,
412 const char *message)
413 {
414 av_log(avctx, AV_LOG_WARNING, "Frame #%d, IFQ: %s\n", avctx->frame_number,
415 message);
416 }
417
418 AVCodec qcelp_decoder =
419 {
420 .name = "qcelp",
421 .type = CODEC_TYPE_AUDIO,
422 .id = CODEC_ID_QCELP,
423 .init = qcelp_decode_init,
424 .decode = qcelp_decode_frame,
425 .priv_data_size = sizeof(QCELPContext),
426 .long_name = NULL_IF_CONFIG_SMALL("QCELP / PureVoice"),
427 };