2 * G.723.1 compatible decoder
3 * Copyright (c) 2006 Benjamin Larsson
4 * Copyright (c) 2010 Mohamed Naufal Basheer
6 * This file is part of Libav.
8 * Libav 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.
13 * Libav 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.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with Libav; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 * G.723.1 compatible decoder
28 #define BITSTREAM_READER_LE
29 #include "libavutil/audioconvert.h"
30 #include "libavutil/lzo.h"
31 #include "libavutil/opt.h"
34 #include "acelp_vectors.h"
35 #include "celp_filters.h"
36 #include "celp_math.h"
38 #include "g723_1_data.h"
44 ACTIVE_FRAME, ///< Active speech
45 SID_FRAME, ///< Silence Insertion Descriptor frame
55 * G723.1 unpacked data subframe
58 int ad_cb_lag; ///< adaptive codebook lag
68 * Pitch postfilter parameters
71 int index; ///< postfilter backward/forward lag
72 int16_t opt_gain; ///< optimal gain
73 int16_t sc_gain; ///< scaling gain
76 typedef struct g723_1_context {
80 G723_1_Subframe subframe[4];
81 enum FrameType cur_frame_type;
82 enum FrameType past_frame_type;
84 uint8_t lsp_index[LSP_BANDS];
88 int16_t prev_lsp[LPC_ORDER];
89 int16_t prev_excitation[PITCH_MAX];
90 int16_t excitation[PITCH_MAX + FRAME_LEN + 4];
91 int16_t synth_mem[LPC_ORDER];
92 int16_t fir_mem[LPC_ORDER];
93 int iir_mem[LPC_ORDER];
104 int16_t audio[FRAME_LEN + LPC_ORDER];
107 static av_cold int g723_1_decode_init(AVCodecContext *avctx)
109 G723_1_Context *p = avctx->priv_data;
111 avctx->channel_layout = AV_CH_LAYOUT_MONO;
112 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
114 avctx->sample_rate = 8000;
115 p->pf_gain = 1 << 12;
117 avcodec_get_frame_defaults(&p->frame);
118 avctx->coded_frame = &p->frame;
120 memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
126 * Unpack the frame into parameters.
128 * @param p the context
129 * @param buf pointer to the input buffer
130 * @param buf_size size of the input buffer
132 static int unpack_bitstream(G723_1_Context *p, const uint8_t *buf,
137 int temp, info_bits, i;
139 init_get_bits(&gb, buf, buf_size * 8);
141 /* Extract frame type and rate info */
142 info_bits = get_bits(&gb, 2);
144 if (info_bits == 3) {
145 p->cur_frame_type = UNTRANSMITTED_FRAME;
149 /* Extract 24 bit lsp indices, 8 bit for each band */
150 p->lsp_index[2] = get_bits(&gb, 8);
151 p->lsp_index[1] = get_bits(&gb, 8);
152 p->lsp_index[0] = get_bits(&gb, 8);
154 if (info_bits == 2) {
155 p->cur_frame_type = SID_FRAME;
156 p->subframe[0].amp_index = get_bits(&gb, 6);
160 /* Extract the info common to both rates */
161 p->cur_rate = info_bits ? RATE_5300 : RATE_6300;
162 p->cur_frame_type = ACTIVE_FRAME;
164 p->pitch_lag[0] = get_bits(&gb, 7);
165 if (p->pitch_lag[0] > 123) /* test if forbidden code */
167 p->pitch_lag[0] += PITCH_MIN;
168 p->subframe[1].ad_cb_lag = get_bits(&gb, 2);
170 p->pitch_lag[1] = get_bits(&gb, 7);
171 if (p->pitch_lag[1] > 123)
173 p->pitch_lag[1] += PITCH_MIN;
174 p->subframe[3].ad_cb_lag = get_bits(&gb, 2);
175 p->subframe[0].ad_cb_lag = 1;
176 p->subframe[2].ad_cb_lag = 1;
178 for (i = 0; i < SUBFRAMES; i++) {
179 /* Extract combined gain */
180 temp = get_bits(&gb, 12);
182 p->subframe[i].dirac_train = 0;
183 if (p->cur_rate == RATE_6300 && p->pitch_lag[i >> 1] < SUBFRAME_LEN - 2) {
184 p->subframe[i].dirac_train = temp >> 11;
188 p->subframe[i].ad_cb_gain = FASTDIV(temp, GAIN_LEVELS);
189 if (p->subframe[i].ad_cb_gain < ad_cb_len) {
190 p->subframe[i].amp_index = temp - p->subframe[i].ad_cb_gain *
197 p->subframe[0].grid_index = get_bits(&gb, 1);
198 p->subframe[1].grid_index = get_bits(&gb, 1);
199 p->subframe[2].grid_index = get_bits(&gb, 1);
200 p->subframe[3].grid_index = get_bits(&gb, 1);
202 if (p->cur_rate == RATE_6300) {
203 skip_bits(&gb, 1); /* skip reserved bit */
205 /* Compute pulse_pos index using the 13-bit combined position index */
206 temp = get_bits(&gb, 13);
207 p->subframe[0].pulse_pos = temp / 810;
209 temp -= p->subframe[0].pulse_pos * 810;
210 p->subframe[1].pulse_pos = FASTDIV(temp, 90);
212 temp -= p->subframe[1].pulse_pos * 90;
213 p->subframe[2].pulse_pos = FASTDIV(temp, 9);
214 p->subframe[3].pulse_pos = temp - p->subframe[2].pulse_pos * 9;
216 p->subframe[0].pulse_pos = (p->subframe[0].pulse_pos << 16) +
218 p->subframe[1].pulse_pos = (p->subframe[1].pulse_pos << 14) +
220 p->subframe[2].pulse_pos = (p->subframe[2].pulse_pos << 16) +
222 p->subframe[3].pulse_pos = (p->subframe[3].pulse_pos << 14) +
225 p->subframe[0].pulse_sign = get_bits(&gb, 6);
226 p->subframe[1].pulse_sign = get_bits(&gb, 5);
227 p->subframe[2].pulse_sign = get_bits(&gb, 6);
228 p->subframe[3].pulse_sign = get_bits(&gb, 5);
229 } else { /* 5300 bps */
230 p->subframe[0].pulse_pos = get_bits(&gb, 12);
231 p->subframe[1].pulse_pos = get_bits(&gb, 12);
232 p->subframe[2].pulse_pos = get_bits(&gb, 12);
233 p->subframe[3].pulse_pos = get_bits(&gb, 12);
235 p->subframe[0].pulse_sign = get_bits(&gb, 4);
236 p->subframe[1].pulse_sign = get_bits(&gb, 4);
237 p->subframe[2].pulse_sign = get_bits(&gb, 4);
238 p->subframe[3].pulse_sign = get_bits(&gb, 4);
245 * Bitexact implementation of sqrt(val/2).
247 static int16_t square_root(int val)
250 int16_t exp = 0x4000;
253 for (i = 0; i < 14; i ++) {
254 int res_exp = res + exp;
255 if (val >= res_exp * res_exp << 1)
263 * Calculate the number of left-shifts required for normalizing the input.
265 * @param num input number
266 * @param width width of the input, 16 bits(0) / 32 bits(1)
268 static int normalize_bits(int num, int width)
277 return width - av_log2(num) - 1;
281 * Scale vector contents based on the largest of their absolutes.
283 static int scale_vector(int16_t *vector, int length)
290 for (i = 0; i < length; i++)
291 max = FFMAX(max, FFABS(vector[i]));
293 max = FFMIN(max, 0x7FFF);
294 bits = normalize_bits(max, 15);
295 scale = (bits == 15) ? 0x7FFF : (1 << bits);
297 for (i = 0; i < length; i++)
298 vector[i] = av_clipl_int32(vector[i] * scale << 1) >> 4;
304 * Perform inverse quantization of LSP frequencies.
306 * @param cur_lsp the current LSP vector
307 * @param prev_lsp the previous LSP vector
308 * @param lsp_index VQ indices
309 * @param bad_frame bad frame flag
311 static void inverse_quant(int16_t *cur_lsp, int16_t *prev_lsp,
312 uint8_t *lsp_index, int bad_frame)
315 int i, j, temp, stable;
317 /* Check for frame erasure */
324 lsp_index[0] = lsp_index[1] = lsp_index[2] = 0;
327 /* Get the VQ table entry corresponding to the transmitted index */
328 cur_lsp[0] = lsp_band0[lsp_index[0]][0];
329 cur_lsp[1] = lsp_band0[lsp_index[0]][1];
330 cur_lsp[2] = lsp_band0[lsp_index[0]][2];
331 cur_lsp[3] = lsp_band1[lsp_index[1]][0];
332 cur_lsp[4] = lsp_band1[lsp_index[1]][1];
333 cur_lsp[5] = lsp_band1[lsp_index[1]][2];
334 cur_lsp[6] = lsp_band2[lsp_index[2]][0];
335 cur_lsp[7] = lsp_band2[lsp_index[2]][1];
336 cur_lsp[8] = lsp_band2[lsp_index[2]][2];
337 cur_lsp[9] = lsp_band2[lsp_index[2]][3];
339 /* Add predicted vector & DC component to the previously quantized vector */
340 for (i = 0; i < LPC_ORDER; i++) {
341 temp = ((prev_lsp[i] - dc_lsp[i]) * pred + (1 << 14)) >> 15;
342 cur_lsp[i] += dc_lsp[i] + temp;
345 for (i = 0; i < LPC_ORDER; i++) {
346 cur_lsp[0] = FFMAX(cur_lsp[0], 0x180);
347 cur_lsp[LPC_ORDER - 1] = FFMIN(cur_lsp[LPC_ORDER - 1], 0x7e00);
349 /* Stability check */
350 for (j = 1; j < LPC_ORDER; j++) {
351 temp = min_dist + cur_lsp[j - 1] - cur_lsp[j];
354 cur_lsp[j - 1] -= temp;
359 for (j = 1; j < LPC_ORDER; j++) {
360 temp = cur_lsp[j - 1] + min_dist - cur_lsp[j] - 4;
370 memcpy(cur_lsp, prev_lsp, LPC_ORDER * sizeof(*cur_lsp));
374 * Bitexact implementation of 2ab scaled by 1/2^16.
376 * @param a 32 bit multiplicand
377 * @param b 16 bit multiplier
379 #define MULL2(a, b) \
380 ((((a) >> 16) * (b) << 1) + (((a) & 0xffff) * (b) >> 15))
383 * Convert LSP frequencies to LPC coefficients.
385 * @param lpc buffer for LPC coefficients
387 static void lsp2lpc(int16_t *lpc)
389 int f1[LPC_ORDER / 2 + 1];
390 int f2[LPC_ORDER / 2 + 1];
393 /* Calculate negative cosine */
394 for (j = 0; j < LPC_ORDER; j++) {
395 int index = lpc[j] >> 7;
396 int offset = lpc[j] & 0x7f;
397 int64_t temp1 = cos_tab[index] << 16;
398 int temp2 = (cos_tab[index + 1] - cos_tab[index]) *
399 ((offset << 8) + 0x80) << 1;
401 lpc[j] = -(av_clipl_int32(((temp1 + temp2) << 1) + (1 << 15)) >> 16);
405 * Compute sum and difference polynomial coefficients
406 * (bitexact alternative to lsp2poly() in lsp.c)
408 /* Initialize with values in Q28 */
410 f1[1] = (lpc[0] << 14) + (lpc[2] << 14);
411 f1[2] = lpc[0] * lpc[2] + (2 << 28);
414 f2[1] = (lpc[1] << 14) + (lpc[3] << 14);
415 f2[2] = lpc[1] * lpc[3] + (2 << 28);
418 * Calculate and scale the coefficients by 1/2 in
419 * each iteration for a final scaling factor of Q25
421 for (i = 2; i < LPC_ORDER / 2; i++) {
422 f1[i + 1] = f1[i - 1] + MULL2(f1[i], lpc[2 * i]);
423 f2[i + 1] = f2[i - 1] + MULL2(f2[i], lpc[2 * i + 1]);
425 for (j = i; j >= 2; j--) {
426 f1[j] = MULL2(f1[j - 1], lpc[2 * i]) +
427 (f1[j] >> 1) + (f1[j - 2] >> 1);
428 f2[j] = MULL2(f2[j - 1], lpc[2 * i + 1]) +
429 (f2[j] >> 1) + (f2[j - 2] >> 1);
434 f1[1] = ((lpc[2 * i] << 16 >> i) + f1[1]) >> 1;
435 f2[1] = ((lpc[2 * i + 1] << 16 >> i) + f2[1]) >> 1;
438 /* Convert polynomial coefficients to LPC coefficients */
439 for (i = 0; i < LPC_ORDER / 2; i++) {
440 int64_t ff1 = f1[i + 1] + f1[i];
441 int64_t ff2 = f2[i + 1] - f2[i];
443 lpc[i] = av_clipl_int32(((ff1 + ff2) << 3) + (1 << 15)) >> 16;
444 lpc[LPC_ORDER - i - 1] = av_clipl_int32(((ff1 - ff2) << 3) +
450 * Quantize LSP frequencies by interpolation and convert them to
451 * the corresponding LPC coefficients.
453 * @param lpc buffer for LPC coefficients
454 * @param cur_lsp the current LSP vector
455 * @param prev_lsp the previous LSP vector
457 static void lsp_interpolate(int16_t *lpc, int16_t *cur_lsp, int16_t *prev_lsp)
460 int16_t *lpc_ptr = lpc;
462 /* cur_lsp * 0.25 + prev_lsp * 0.75 */
463 ff_acelp_weighted_vector_sum(lpc, cur_lsp, prev_lsp,
464 4096, 12288, 1 << 13, 14, LPC_ORDER);
465 ff_acelp_weighted_vector_sum(lpc + LPC_ORDER, cur_lsp, prev_lsp,
466 8192, 8192, 1 << 13, 14, LPC_ORDER);
467 ff_acelp_weighted_vector_sum(lpc + 2 * LPC_ORDER, cur_lsp, prev_lsp,
468 12288, 4096, 1 << 13, 14, LPC_ORDER);
469 memcpy(lpc + 3 * LPC_ORDER, cur_lsp, LPC_ORDER * sizeof(*lpc));
471 for (i = 0; i < SUBFRAMES; i++) {
473 lpc_ptr += LPC_ORDER;
478 * Generate a train of dirac functions with period as pitch lag.
480 static void gen_dirac_train(int16_t *buf, int pitch_lag)
482 int16_t vector[SUBFRAME_LEN];
485 memcpy(vector, buf, SUBFRAME_LEN * sizeof(*vector));
486 for (i = pitch_lag; i < SUBFRAME_LEN; i += pitch_lag) {
487 for (j = 0; j < SUBFRAME_LEN - i; j++)
488 buf[i + j] += vector[j];
493 * Generate fixed codebook excitation vector.
495 * @param vector decoded excitation vector
496 * @param subfrm current subframe
497 * @param cur_rate current bitrate
498 * @param pitch_lag closed loop pitch lag
499 * @param index current subframe index
501 static void gen_fcb_excitation(int16_t *vector, G723_1_Subframe subfrm,
502 enum Rate cur_rate, int pitch_lag, int index)
506 memset(vector, 0, SUBFRAME_LEN * sizeof(*vector));
508 if (cur_rate == RATE_6300) {
509 if (subfrm.pulse_pos >= max_pos[index])
512 /* Decode amplitudes and positions */
513 j = PULSE_MAX - pulses[index];
514 temp = subfrm.pulse_pos;
515 for (i = 0; i < SUBFRAME_LEN / GRID_SIZE; i++) {
516 temp -= combinatorial_table[j][i];
519 temp += combinatorial_table[j++][i];
520 if (subfrm.pulse_sign & (1 << (PULSE_MAX - j))) {
521 vector[subfrm.grid_index + GRID_SIZE * i] =
522 -fixed_cb_gain[subfrm.amp_index];
524 vector[subfrm.grid_index + GRID_SIZE * i] =
525 fixed_cb_gain[subfrm.amp_index];
530 if (subfrm.dirac_train == 1)
531 gen_dirac_train(vector, pitch_lag);
532 } else { /* 5300 bps */
533 int cb_gain = fixed_cb_gain[subfrm.amp_index];
534 int cb_shift = subfrm.grid_index;
535 int cb_sign = subfrm.pulse_sign;
536 int cb_pos = subfrm.pulse_pos;
537 int offset, beta, lag;
539 for (i = 0; i < 8; i += 2) {
540 offset = ((cb_pos & 7) << 3) + cb_shift + i;
541 vector[offset] = (cb_sign & 1) ? cb_gain : -cb_gain;
546 /* Enhance harmonic components */
547 lag = pitch_contrib[subfrm.ad_cb_gain << 1] + pitch_lag +
548 subfrm.ad_cb_lag - 1;
549 beta = pitch_contrib[(subfrm.ad_cb_gain << 1) + 1];
551 if (lag < SUBFRAME_LEN - 2) {
552 for (i = lag; i < SUBFRAME_LEN; i++)
553 vector[i] += beta * vector[i - lag] >> 15;
559 * Get delayed contribution from the previous excitation vector.
561 static void get_residual(int16_t *residual, int16_t *prev_excitation, int lag)
563 int offset = PITCH_MAX - PITCH_ORDER / 2 - lag;
566 residual[0] = prev_excitation[offset];
567 residual[1] = prev_excitation[offset + 1];
570 for (i = 2; i < SUBFRAME_LEN + PITCH_ORDER - 1; i++)
571 residual[i] = prev_excitation[offset + (i - 2) % lag];
574 static int dot_product(const int16_t *a, const int16_t *b, int length,
579 for (i = 0; i < length; i++) {
580 int64_t prod = av_clipl_int32(MUL64(a[i], b[i]) << shift);
581 sum = av_clipl_int32(sum + prod);
587 * Generate adaptive codebook excitation.
589 static void gen_acb_excitation(int16_t *vector, int16_t *prev_excitation,
590 int pitch_lag, G723_1_Subframe subfrm,
593 int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
594 const int16_t *cb_ptr;
595 int lag = pitch_lag + subfrm.ad_cb_lag - 1;
600 get_residual(residual, prev_excitation, lag);
602 /* Select quantization table */
603 if (cur_rate == RATE_6300 && pitch_lag < SUBFRAME_LEN - 2)
604 cb_ptr = adaptive_cb_gain85;
606 cb_ptr = adaptive_cb_gain170;
608 /* Calculate adaptive vector */
609 cb_ptr += subfrm.ad_cb_gain * 20;
610 for (i = 0; i < SUBFRAME_LEN; i++) {
611 sum = dot_product(residual + i, cb_ptr, PITCH_ORDER, 1);
612 vector[i] = av_clipl_int32((sum << 1) + (1 << 15)) >> 16;
617 * Estimate maximum auto-correlation around pitch lag.
619 * @param p the context
620 * @param offset offset of the excitation vector
621 * @param ccr_max pointer to the maximum auto-correlation
622 * @param pitch_lag decoded pitch lag
623 * @param length length of autocorrelation
624 * @param dir forward lag(1) / backward lag(-1)
626 static int autocorr_max(G723_1_Context *p, int offset, int *ccr_max,
627 int pitch_lag, int length, int dir)
629 int limit, ccr, lag = 0;
630 int16_t *buf = p->excitation + offset;
633 pitch_lag = FFMIN(PITCH_MAX - 3, pitch_lag);
635 limit = FFMIN(FRAME_LEN + PITCH_MAX - offset - length, pitch_lag + 3);
637 limit = pitch_lag + 3;
639 for (i = pitch_lag - 3; i <= limit; i++) {
640 ccr = dot_product(buf, buf + dir * i, length, 1);
642 if (ccr > *ccr_max) {
651 * Calculate pitch postfilter optimal and scaling gains.
653 * @param lag pitch postfilter forward/backward lag
654 * @param ppf pitch postfilter parameters
655 * @param cur_rate current bitrate
656 * @param tgt_eng target energy
657 * @param ccr cross-correlation
658 * @param res_eng residual energy
660 static void comp_ppf_gains(int lag, PPFParam *ppf, enum Rate cur_rate,
661 int tgt_eng, int ccr, int res_eng)
663 int pf_residual; /* square of postfiltered residual */
664 int64_t temp1, temp2;
668 temp1 = tgt_eng * res_eng >> 1;
669 temp2 = ccr * ccr << 1;
672 if (ccr >= res_eng) {
673 ppf->opt_gain = ppf_gain_weight[cur_rate];
675 ppf->opt_gain = (ccr << 15) / res_eng *
676 ppf_gain_weight[cur_rate] >> 15;
678 /* pf_res^2 = tgt_eng + 2*ccr*gain + res_eng*gain^2 */
679 temp1 = (tgt_eng << 15) + (ccr * ppf->opt_gain << 1);
680 temp2 = (ppf->opt_gain * ppf->opt_gain >> 15) * res_eng;
681 pf_residual = av_clipl_int32(temp1 + temp2 + (1 << 15)) >> 16;
683 if (tgt_eng >= pf_residual << 1) {
686 temp1 = (tgt_eng << 14) / pf_residual;
689 /* scaling_gain = sqrt(tgt_eng/pf_res^2) */
690 ppf->sc_gain = square_root(temp1 << 16);
693 ppf->sc_gain = 0x7fff;
696 ppf->opt_gain = av_clip_int16(ppf->opt_gain * ppf->sc_gain >> 15);
700 * Calculate pitch postfilter parameters.
702 * @param p the context
703 * @param offset offset of the excitation vector
704 * @param pitch_lag decoded pitch lag
705 * @param ppf pitch postfilter parameters
706 * @param cur_rate current bitrate
708 static void comp_ppf_coeff(G723_1_Context *p, int offset, int pitch_lag,
709 PPFParam *ppf, enum Rate cur_rate)
714 int64_t temp1, temp2;
718 * 1 - forward cross-correlation
719 * 2 - forward residual energy
720 * 3 - backward cross-correlation
721 * 4 - backward residual energy
723 int energy[5] = {0, 0, 0, 0, 0};
724 int16_t *buf = p->excitation + offset;
725 int fwd_lag = autocorr_max(p, offset, &energy[1], pitch_lag,
727 int back_lag = autocorr_max(p, offset, &energy[3], pitch_lag,
732 ppf->sc_gain = 0x7fff;
734 /* Case 0, Section 3.6 */
735 if (!back_lag && !fwd_lag)
738 /* Compute target energy */
739 energy[0] = dot_product(buf, buf, SUBFRAME_LEN, 1);
741 /* Compute forward residual energy */
743 energy[2] = dot_product(buf + fwd_lag, buf + fwd_lag,
746 /* Compute backward residual energy */
748 energy[4] = dot_product(buf - back_lag, buf - back_lag,
751 /* Normalize and shorten */
753 for (i = 0; i < 5; i++)
754 temp1 = FFMAX(energy[i], temp1);
756 scale = normalize_bits(temp1, 31);
757 for (i = 0; i < 5; i++)
758 energy[i] = (energy[i] << scale) >> 16;
760 if (fwd_lag && !back_lag) { /* Case 1 */
761 comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
763 } else if (!fwd_lag) { /* Case 2 */
764 comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
766 } else { /* Case 3 */
769 * Select the largest of energy[1]^2/energy[2]
770 * and energy[3]^2/energy[4]
772 temp1 = energy[4] * ((energy[1] * energy[1] + (1 << 14)) >> 15);
773 temp2 = energy[2] * ((energy[3] * energy[3] + (1 << 14)) >> 15);
774 if (temp1 >= temp2) {
775 comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
778 comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
785 * Classify frames as voiced/unvoiced.
787 * @param p the context
788 * @param pitch_lag decoded pitch_lag
789 * @param exc_eng excitation energy estimation
790 * @param scale scaling factor of exc_eng
792 * @return residual interpolation index if voiced, 0 otherwise
794 static int comp_interp_index(G723_1_Context *p, int pitch_lag,
795 int *exc_eng, int *scale)
797 int offset = PITCH_MAX + 2 * SUBFRAME_LEN;
798 int16_t *buf = p->excitation + offset;
800 int index, ccr, tgt_eng, best_eng, temp;
802 *scale = scale_vector(p->excitation, FRAME_LEN + PITCH_MAX);
804 /* Compute maximum backward cross-correlation */
806 index = autocorr_max(p, offset, &ccr, pitch_lag, SUBFRAME_LEN * 2, -1);
807 ccr = av_clipl_int32((int64_t)ccr + (1 << 15)) >> 16;
809 /* Compute target energy */
810 tgt_eng = dot_product(buf, buf, SUBFRAME_LEN * 2, 1);
811 *exc_eng = av_clipl_int32((int64_t)tgt_eng + (1 << 15)) >> 16;
816 /* Compute best energy */
817 best_eng = dot_product(buf - index, buf - index,
818 SUBFRAME_LEN * 2, 1);
819 best_eng = av_clipl_int32((int64_t)best_eng + (1 << 15)) >> 16;
821 temp = best_eng * *exc_eng >> 3;
823 if (temp < ccr * ccr)
830 * Peform residual interpolation based on frame classification.
832 * @param buf decoded excitation vector
833 * @param out output vector
834 * @param lag decoded pitch lag
835 * @param gain interpolated gain
836 * @param rseed seed for random number generator
838 static void residual_interp(int16_t *buf, int16_t *out, int lag,
839 int gain, int *rseed)
842 if (lag) { /* Voiced */
843 int16_t *vector_ptr = buf + PITCH_MAX;
845 for (i = 0; i < lag; i++)
846 vector_ptr[i - lag] = vector_ptr[i - lag] * 3 >> 2;
847 av_memcpy_backptr((uint8_t*)vector_ptr, lag * sizeof(*vector_ptr),
848 FRAME_LEN * sizeof(*vector_ptr));
849 memcpy(out, vector_ptr, FRAME_LEN * sizeof(*vector_ptr));
850 } else { /* Unvoiced */
851 for (i = 0; i < FRAME_LEN; i++) {
852 *rseed = *rseed * 521 + 259;
853 out[i] = gain * *rseed >> 15;
855 memset(buf, 0, (FRAME_LEN + PITCH_MAX) * sizeof(*buf));
860 * Perform IIR filtering.
862 * @param fir_coef FIR coefficients
863 * @param iir_coef IIR coefficients
864 * @param src source vector
865 * @param dest destination vector
867 static inline void iir_filter(int16_t *fir_coef, int16_t *iir_coef,
868 int16_t *src, int *dest)
872 for (m = 0; m < SUBFRAME_LEN; m++) {
874 for (n = 1; n <= LPC_ORDER; n++) {
875 filter -= fir_coef[n - 1] * src[m - n] -
876 iir_coef[n - 1] * (dest[m - n] >> 16);
879 dest[m] = av_clipl_int32((src[m] << 16) + (filter << 3) + (1 << 15));
884 * Adjust gain of postfiltered signal.
886 * @param p the context
887 * @param buf postfiltered output vector
888 * @param energy input energy coefficient
890 static void gain_scale(G723_1_Context *p, int16_t * buf, int energy)
892 int num, denom, gain, bits1, bits2;
897 for (i = 0; i < SUBFRAME_LEN; i++) {
898 int64_t temp = buf[i] >> 2;
899 temp = av_clipl_int32(MUL64(temp, temp) << 1);
900 denom = av_clipl_int32(denom + temp);
904 bits1 = normalize_bits(num, 31);
905 bits2 = normalize_bits(denom, 31);
906 num = num << bits1 >> 1;
909 bits2 = 5 + bits1 - bits2;
910 bits2 = FFMAX(0, bits2);
912 gain = (num >> 1) / (denom >> 16);
913 gain = square_root(gain << 16 >> bits2);
918 for (i = 0; i < SUBFRAME_LEN; i++) {
919 p->pf_gain = ((p->pf_gain << 4) - p->pf_gain + gain + (1 << 3)) >> 4;
920 buf[i] = av_clip_int16((buf[i] * (p->pf_gain + (p->pf_gain >> 4)) +
926 * Perform formant filtering.
928 * @param p the context
929 * @param lpc quantized lpc coefficients
930 * @param buf output buffer
932 static void formant_postfilter(G723_1_Context *p, int16_t *lpc, int16_t *buf)
934 int16_t filter_coef[2][LPC_ORDER], *buf_ptr;
935 int filter_signal[LPC_ORDER + FRAME_LEN], *signal_ptr;
938 memcpy(buf, p->fir_mem, LPC_ORDER * sizeof(*buf));
939 memcpy(filter_signal, p->iir_mem, LPC_ORDER * sizeof(*filter_signal));
941 for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
942 for (k = 0; k < LPC_ORDER; k++) {
943 filter_coef[0][k] = (-lpc[k] * postfilter_tbl[0][k] +
945 filter_coef[1][k] = (-lpc[k] * postfilter_tbl[1][k] +
948 iir_filter(filter_coef[0], filter_coef[1], buf + i,
953 memcpy(p->fir_mem, buf + FRAME_LEN, LPC_ORDER * sizeof(*p->fir_mem));
954 memcpy(p->iir_mem, filter_signal + FRAME_LEN,
955 LPC_ORDER * sizeof(*p->iir_mem));
957 buf_ptr = buf + LPC_ORDER;
958 signal_ptr = filter_signal + LPC_ORDER;
959 for (i = 0; i < SUBFRAMES; i++) {
960 int16_t temp_vector[SUBFRAME_LEN];
966 memcpy(temp_vector, buf_ptr, SUBFRAME_LEN * sizeof(*temp_vector));
967 scale = scale_vector(temp_vector, SUBFRAME_LEN);
969 /* Compute auto correlation coefficients */
970 auto_corr[0] = dot_product(temp_vector, temp_vector + 1,
971 SUBFRAME_LEN - 1, 1);
972 auto_corr[1] = dot_product(temp_vector, temp_vector, SUBFRAME_LEN, 1);
974 /* Compute reflection coefficient */
975 temp = auto_corr[1] >> 16;
977 temp = (auto_corr[0] >> 2) / temp;
979 p->reflection_coef = ((p->reflection_coef << 2) - p->reflection_coef +
981 temp = (p->reflection_coef * 0xffffc >> 3) & 0xfffc;
983 /* Compensation filter */
984 for (j = 0; j < SUBFRAME_LEN; j++) {
985 buf_ptr[j] = av_clipl_int32(signal_ptr[j] +
986 ((signal_ptr[j - 1] >> 16) *
990 /* Compute normalized signal energy */
991 temp = 2 * scale + 4;
993 energy = av_clipl_int32((int64_t)auto_corr[1] << -temp);
995 energy = auto_corr[1] >> temp;
997 gain_scale(p, buf_ptr, energy);
999 buf_ptr += SUBFRAME_LEN;
1000 signal_ptr += SUBFRAME_LEN;
1004 static int g723_1_decode_frame(AVCodecContext *avctx, void *data,
1005 int *got_frame_ptr, AVPacket *avpkt)
1007 G723_1_Context *p = avctx->priv_data;
1008 const uint8_t *buf = avpkt->data;
1009 int buf_size = avpkt->size;
1010 int dec_mode = buf[0] & 3;
1012 PPFParam ppf[SUBFRAMES];
1013 int16_t cur_lsp[LPC_ORDER];
1014 int16_t lpc[SUBFRAMES * LPC_ORDER];
1015 int16_t acb_vector[SUBFRAME_LEN];
1016 int16_t *vector_ptr;
1018 int bad_frame = 0, i, j, ret;
1020 if (buf_size < frame_size[dec_mode]) {
1022 av_log(avctx, AV_LOG_WARNING,
1023 "Expected %d bytes, got %d - skipping packet\n",
1024 frame_size[dec_mode], buf_size);
1029 if (unpack_bitstream(p, buf, buf_size) < 0) {
1031 if (p->past_frame_type == ACTIVE_FRAME)
1032 p->cur_frame_type = ACTIVE_FRAME;
1034 p->cur_frame_type = UNTRANSMITTED_FRAME;
1037 p->frame.nb_samples = FRAME_LEN;
1038 if ((ret = avctx->get_buffer(avctx, &p->frame)) < 0) {
1039 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1043 out = (int16_t *)p->frame.data[0];
1045 if (p->cur_frame_type == ACTIVE_FRAME) {
1047 p->erased_frames = 0;
1048 else if (p->erased_frames != 3)
1051 inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, bad_frame);
1052 lsp_interpolate(lpc, cur_lsp, p->prev_lsp);
1054 /* Save the lsp_vector for the next frame */
1055 memcpy(p->prev_lsp, cur_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
1057 /* Generate the excitation for the frame */
1058 memcpy(p->excitation, p->prev_excitation,
1059 PITCH_MAX * sizeof(*p->excitation));
1060 vector_ptr = p->excitation + PITCH_MAX;
1061 if (!p->erased_frames) {
1062 /* Update interpolation gain memory */
1063 p->interp_gain = fixed_cb_gain[(p->subframe[2].amp_index +
1064 p->subframe[3].amp_index) >> 1];
1065 for (i = 0; i < SUBFRAMES; i++) {
1066 gen_fcb_excitation(vector_ptr, p->subframe[i], p->cur_rate,
1067 p->pitch_lag[i >> 1], i);
1068 gen_acb_excitation(acb_vector, &p->excitation[SUBFRAME_LEN * i],
1069 p->pitch_lag[i >> 1], p->subframe[i],
1071 /* Get the total excitation */
1072 for (j = 0; j < SUBFRAME_LEN; j++) {
1073 vector_ptr[j] = av_clip_int16(vector_ptr[j] << 1);
1074 vector_ptr[j] = av_clip_int16(vector_ptr[j] +
1077 vector_ptr += SUBFRAME_LEN;
1080 vector_ptr = p->excitation + PITCH_MAX;
1082 /* Save the excitation */
1083 memcpy(p->audio + LPC_ORDER, vector_ptr, FRAME_LEN * sizeof(*p->audio));
1085 p->interp_index = comp_interp_index(p, p->pitch_lag[1],
1086 &p->sid_gain, &p->cur_gain);
1088 if (p->postfilter) {
1090 for (j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1091 comp_ppf_coeff(p, i, p->pitch_lag[j >> 1],
1092 ppf + j, p->cur_rate);
1095 /* Restore the original excitation */
1096 memcpy(p->excitation, p->prev_excitation,
1097 PITCH_MAX * sizeof(*p->excitation));
1098 memcpy(vector_ptr, p->audio + LPC_ORDER, FRAME_LEN * sizeof(*vector_ptr));
1100 /* Peform pitch postfiltering */
1102 for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1103 ff_acelp_weighted_vector_sum(p->audio + LPC_ORDER + i,
1105 vector_ptr + i + ppf[j].index,
1108 1 << 14, 15, SUBFRAME_LEN);
1111 p->interp_gain = (p->interp_gain * 3 + 2) >> 2;
1112 if (p->erased_frames == 3) {
1114 memset(p->excitation, 0,
1115 (FRAME_LEN + PITCH_MAX) * sizeof(*p->excitation));
1116 memset(p->frame.data[0], 0,
1117 (FRAME_LEN + LPC_ORDER) * sizeof(int16_t));
1119 /* Regenerate frame */
1120 residual_interp(p->excitation, p->audio + LPC_ORDER, p->interp_index,
1121 p->interp_gain, &p->random_seed);
1124 /* Save the excitation for the next frame */
1125 memcpy(p->prev_excitation, p->excitation + FRAME_LEN,
1126 PITCH_MAX * sizeof(*p->excitation));
1128 memset(out, 0, FRAME_LEN * 2);
1129 av_log(avctx, AV_LOG_WARNING,
1130 "G.723.1: Comfort noise generation not supported yet\n");
1133 *(AVFrame *)data = p->frame;
1134 return frame_size[dec_mode];
1137 p->past_frame_type = p->cur_frame_type;
1139 memcpy(p->audio, p->synth_mem, LPC_ORDER * sizeof(*p->audio));
1140 for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1141 ff_celp_lp_synthesis_filter(p->audio + i, &lpc[j * LPC_ORDER],
1142 p->audio + i, SUBFRAME_LEN, LPC_ORDER,
1144 memcpy(p->synth_mem, p->audio + FRAME_LEN, LPC_ORDER * sizeof(*p->audio));
1146 if (p->postfilter) {
1147 formant_postfilter(p, lpc, p->audio);
1148 memcpy(p->frame.data[0], p->audio + LPC_ORDER, FRAME_LEN * 2);
1149 } else { // if output is not postfiltered it should be scaled by 2
1150 for (i = 0; i < FRAME_LEN; i++)
1151 out[i] = av_clip_int16(p->audio[LPC_ORDER + i] << 1);
1155 *(AVFrame *)data = p->frame;
1157 return frame_size[dec_mode];
1160 #define OFFSET(x) offsetof(G723_1_Context, x)
1161 #define AD AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1163 static const AVOption options[] = {
1164 { "postfilter", "postfilter on/off", OFFSET(postfilter), AV_OPT_TYPE_INT,
1170 static const AVClass g723_1dec_class = {
1171 .class_name = "G.723.1 decoder",
1172 .item_name = av_default_item_name,
1174 .version = LIBAVUTIL_VERSION_INT,
1177 AVCodec ff_g723_1_decoder = {
1179 .type = AVMEDIA_TYPE_AUDIO,
1180 .id = AV_CODEC_ID_G723_1,
1181 .priv_data_size = sizeof(G723_1_Context),
1182 .init = g723_1_decode_init,
1183 .decode = g723_1_decode_frame,
1184 .long_name = NULL_IF_CONFIG_SMALL("G.723.1"),
1185 .capabilities = CODEC_CAP_SUBFRAMES,
1186 .priv_class = &g723_1dec_class,