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 FFmpeg.
8 * FFmpeg 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 * FFmpeg 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 FFmpeg; 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 #include "libavutil/channel_layout.h"
29 #include "libavutil/mem.h"
30 #include "libavutil/opt.h"
32 #define BITSTREAM_READER_LE
33 #include "acelp_vectors.h"
35 #include "celp_filters.h"
36 #include "celp_math.h"
41 #define CNG_RANDOM_SEED 12345
43 static av_cold int g723_1_decode_init(AVCodecContext *avctx)
45 G723_1_Context *s = avctx->priv_data;
46 G723_1_ChannelContext *p = &s->ch[0];
48 avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
49 if (avctx->channels < 1 || avctx->channels > 2) {
50 av_log(avctx, AV_LOG_ERROR, "Only mono and stereo are supported (requested channels: %d).\n", avctx->channels);
51 return AVERROR(EINVAL);
53 avctx->channel_layout = avctx->channels == 1 ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO;
56 memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
57 memcpy(p->sid_lsp, dc_lsp, LPC_ORDER * sizeof(*p->sid_lsp));
59 p->cng_random_seed = CNG_RANDOM_SEED;
60 p->past_frame_type = SID_FRAME;
66 * Unpack the frame into parameters.
68 * @param p the context
69 * @param buf pointer to the input buffer
70 * @param buf_size size of the input buffer
72 static int unpack_bitstream(G723_1_ChannelContext *p, const uint8_t *buf,
77 int temp, info_bits, i;
79 init_get_bits(&gb, buf, buf_size * 8);
81 /* Extract frame type and rate info */
82 info_bits = get_bits(&gb, 2);
85 p->cur_frame_type = UNTRANSMITTED_FRAME;
89 /* Extract 24 bit lsp indices, 8 bit for each band */
90 p->lsp_index[2] = get_bits(&gb, 8);
91 p->lsp_index[1] = get_bits(&gb, 8);
92 p->lsp_index[0] = get_bits(&gb, 8);
95 p->cur_frame_type = SID_FRAME;
96 p->subframe[0].amp_index = get_bits(&gb, 6);
100 /* Extract the info common to both rates */
101 p->cur_rate = info_bits ? RATE_5300 : RATE_6300;
102 p->cur_frame_type = ACTIVE_FRAME;
104 p->pitch_lag[0] = get_bits(&gb, 7);
105 if (p->pitch_lag[0] > 123) /* test if forbidden code */
107 p->pitch_lag[0] += PITCH_MIN;
108 p->subframe[1].ad_cb_lag = get_bits(&gb, 2);
110 p->pitch_lag[1] = get_bits(&gb, 7);
111 if (p->pitch_lag[1] > 123)
113 p->pitch_lag[1] += PITCH_MIN;
114 p->subframe[3].ad_cb_lag = get_bits(&gb, 2);
115 p->subframe[0].ad_cb_lag = 1;
116 p->subframe[2].ad_cb_lag = 1;
118 for (i = 0; i < SUBFRAMES; i++) {
119 /* Extract combined gain */
120 temp = get_bits(&gb, 12);
122 p->subframe[i].dirac_train = 0;
123 if (p->cur_rate == RATE_6300 && p->pitch_lag[i >> 1] < SUBFRAME_LEN - 2) {
124 p->subframe[i].dirac_train = temp >> 11;
128 p->subframe[i].ad_cb_gain = FASTDIV(temp, GAIN_LEVELS);
129 if (p->subframe[i].ad_cb_gain < ad_cb_len) {
130 p->subframe[i].amp_index = temp - p->subframe[i].ad_cb_gain *
137 p->subframe[0].grid_index = get_bits1(&gb);
138 p->subframe[1].grid_index = get_bits1(&gb);
139 p->subframe[2].grid_index = get_bits1(&gb);
140 p->subframe[3].grid_index = get_bits1(&gb);
142 if (p->cur_rate == RATE_6300) {
143 skip_bits1(&gb); /* skip reserved bit */
145 /* Compute pulse_pos index using the 13-bit combined position index */
146 temp = get_bits(&gb, 13);
147 p->subframe[0].pulse_pos = temp / 810;
149 temp -= p->subframe[0].pulse_pos * 810;
150 p->subframe[1].pulse_pos = FASTDIV(temp, 90);
152 temp -= p->subframe[1].pulse_pos * 90;
153 p->subframe[2].pulse_pos = FASTDIV(temp, 9);
154 p->subframe[3].pulse_pos = temp - p->subframe[2].pulse_pos * 9;
156 p->subframe[0].pulse_pos = (p->subframe[0].pulse_pos << 16) +
158 p->subframe[1].pulse_pos = (p->subframe[1].pulse_pos << 14) +
160 p->subframe[2].pulse_pos = (p->subframe[2].pulse_pos << 16) +
162 p->subframe[3].pulse_pos = (p->subframe[3].pulse_pos << 14) +
165 p->subframe[0].pulse_sign = get_bits(&gb, 6);
166 p->subframe[1].pulse_sign = get_bits(&gb, 5);
167 p->subframe[2].pulse_sign = get_bits(&gb, 6);
168 p->subframe[3].pulse_sign = get_bits(&gb, 5);
169 } else { /* 5300 bps */
170 p->subframe[0].pulse_pos = get_bits(&gb, 12);
171 p->subframe[1].pulse_pos = get_bits(&gb, 12);
172 p->subframe[2].pulse_pos = get_bits(&gb, 12);
173 p->subframe[3].pulse_pos = get_bits(&gb, 12);
175 p->subframe[0].pulse_sign = get_bits(&gb, 4);
176 p->subframe[1].pulse_sign = get_bits(&gb, 4);
177 p->subframe[2].pulse_sign = get_bits(&gb, 4);
178 p->subframe[3].pulse_sign = get_bits(&gb, 4);
185 * Bitexact implementation of sqrt(val/2).
187 static int16_t square_root(unsigned val)
189 av_assert2(!(val & 0x80000000));
191 return (ff_sqrt(val << 1) >> 1) & (~1);
195 * Generate fixed codebook excitation vector.
197 * @param vector decoded excitation vector
198 * @param subfrm current subframe
199 * @param cur_rate current bitrate
200 * @param pitch_lag closed loop pitch lag
201 * @param index current subframe index
203 static void gen_fcb_excitation(int16_t *vector, G723_1_Subframe *subfrm,
204 enum Rate cur_rate, int pitch_lag, int index)
208 memset(vector, 0, SUBFRAME_LEN * sizeof(*vector));
210 if (cur_rate == RATE_6300) {
211 if (subfrm->pulse_pos >= max_pos[index])
214 /* Decode amplitudes and positions */
215 j = PULSE_MAX - pulses[index];
216 temp = subfrm->pulse_pos;
217 for (i = 0; i < SUBFRAME_LEN / GRID_SIZE; i++) {
218 temp -= combinatorial_table[j][i];
221 temp += combinatorial_table[j++][i];
222 if (subfrm->pulse_sign & (1 << (PULSE_MAX - j))) {
223 vector[subfrm->grid_index + GRID_SIZE * i] =
224 -fixed_cb_gain[subfrm->amp_index];
226 vector[subfrm->grid_index + GRID_SIZE * i] =
227 fixed_cb_gain[subfrm->amp_index];
232 if (subfrm->dirac_train == 1)
233 ff_g723_1_gen_dirac_train(vector, pitch_lag);
234 } else { /* 5300 bps */
235 int cb_gain = fixed_cb_gain[subfrm->amp_index];
236 int cb_shift = subfrm->grid_index;
237 int cb_sign = subfrm->pulse_sign;
238 int cb_pos = subfrm->pulse_pos;
239 int offset, beta, lag;
241 for (i = 0; i < 8; i += 2) {
242 offset = ((cb_pos & 7) << 3) + cb_shift + i;
243 vector[offset] = (cb_sign & 1) ? cb_gain : -cb_gain;
248 /* Enhance harmonic components */
249 lag = pitch_contrib[subfrm->ad_cb_gain << 1] + pitch_lag +
250 subfrm->ad_cb_lag - 1;
251 beta = pitch_contrib[(subfrm->ad_cb_gain << 1) + 1];
253 if (lag < SUBFRAME_LEN - 2) {
254 for (i = lag; i < SUBFRAME_LEN; i++)
255 vector[i] += beta * vector[i - lag] >> 15;
261 * Estimate maximum auto-correlation around pitch lag.
263 * @param buf buffer with offset applied
264 * @param offset offset of the excitation vector
265 * @param ccr_max pointer to the maximum auto-correlation
266 * @param pitch_lag decoded pitch lag
267 * @param length length of autocorrelation
268 * @param dir forward lag(1) / backward lag(-1)
270 static int autocorr_max(const int16_t *buf, int offset, int *ccr_max,
271 int pitch_lag, int length, int dir)
273 int limit, ccr, lag = 0;
276 pitch_lag = FFMIN(PITCH_MAX - 3, pitch_lag);
278 limit = FFMIN(FRAME_LEN + PITCH_MAX - offset - length, pitch_lag + 3);
280 limit = pitch_lag + 3;
282 for (i = pitch_lag - 3; i <= limit; i++) {
283 ccr = ff_g723_1_dot_product(buf, buf + dir * i, length);
285 if (ccr > *ccr_max) {
294 * Calculate pitch postfilter optimal and scaling gains.
296 * @param lag pitch postfilter forward/backward lag
297 * @param ppf pitch postfilter parameters
298 * @param cur_rate current bitrate
299 * @param tgt_eng target energy
300 * @param ccr cross-correlation
301 * @param res_eng residual energy
303 static void comp_ppf_gains(int lag, PPFParam *ppf, enum Rate cur_rate,
304 int tgt_eng, int ccr, int res_eng)
306 int pf_residual; /* square of postfiltered residual */
311 temp1 = tgt_eng * res_eng >> 1;
312 temp2 = ccr * ccr << 1;
315 if (ccr >= res_eng) {
316 ppf->opt_gain = ppf_gain_weight[cur_rate];
318 ppf->opt_gain = (ccr << 15) / res_eng *
319 ppf_gain_weight[cur_rate] >> 15;
321 /* pf_res^2 = tgt_eng + 2*ccr*gain + res_eng*gain^2 */
322 temp1 = (tgt_eng << 15) + (ccr * ppf->opt_gain << 1);
323 temp2 = (ppf->opt_gain * ppf->opt_gain >> 15) * res_eng;
324 pf_residual = av_sat_add32(temp1, temp2 + (1 << 15)) >> 16;
326 if (tgt_eng >= pf_residual << 1) {
329 temp1 = (tgt_eng << 14) / pf_residual;
332 /* scaling_gain = sqrt(tgt_eng/pf_res^2) */
333 ppf->sc_gain = square_root(temp1 << 16);
336 ppf->sc_gain = 0x7fff;
339 ppf->opt_gain = av_clip_int16(ppf->opt_gain * ppf->sc_gain >> 15);
343 * Calculate pitch postfilter parameters.
345 * @param p the context
346 * @param offset offset of the excitation vector
347 * @param pitch_lag decoded pitch lag
348 * @param ppf pitch postfilter parameters
349 * @param cur_rate current bitrate
351 static void comp_ppf_coeff(G723_1_ChannelContext *p, int offset, int pitch_lag,
352 PPFParam *ppf, enum Rate cur_rate)
361 * 1 - forward cross-correlation
362 * 2 - forward residual energy
363 * 3 - backward cross-correlation
364 * 4 - backward residual energy
366 int energy[5] = {0, 0, 0, 0, 0};
367 int16_t *buf = p->audio + LPC_ORDER + offset;
368 int fwd_lag = autocorr_max(buf, offset, &energy[1], pitch_lag,
370 int back_lag = autocorr_max(buf, offset, &energy[3], pitch_lag,
375 ppf->sc_gain = 0x7fff;
377 /* Case 0, Section 3.6 */
378 if (!back_lag && !fwd_lag)
381 /* Compute target energy */
382 energy[0] = ff_g723_1_dot_product(buf, buf, SUBFRAME_LEN);
384 /* Compute forward residual energy */
386 energy[2] = ff_g723_1_dot_product(buf + fwd_lag, buf + fwd_lag,
389 /* Compute backward residual energy */
391 energy[4] = ff_g723_1_dot_product(buf - back_lag, buf - back_lag,
394 /* Normalize and shorten */
396 for (i = 0; i < 5; i++)
397 temp1 = FFMAX(energy[i], temp1);
399 scale = ff_g723_1_normalize_bits(temp1, 31);
400 for (i = 0; i < 5; i++)
401 energy[i] = (energy[i] << scale) >> 16;
403 if (fwd_lag && !back_lag) { /* Case 1 */
404 comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
406 } else if (!fwd_lag) { /* Case 2 */
407 comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
409 } else { /* Case 3 */
412 * Select the largest of energy[1]^2/energy[2]
413 * and energy[3]^2/energy[4]
415 temp1 = energy[4] * ((energy[1] * energy[1] + (1 << 14)) >> 15);
416 temp2 = energy[2] * ((energy[3] * energy[3] + (1 << 14)) >> 15);
417 if (temp1 >= temp2) {
418 comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
421 comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
428 * Classify frames as voiced/unvoiced.
430 * @param p the context
431 * @param pitch_lag decoded pitch_lag
432 * @param exc_eng excitation energy estimation
433 * @param scale scaling factor of exc_eng
435 * @return residual interpolation index if voiced, 0 otherwise
437 static int comp_interp_index(G723_1_ChannelContext *p, int pitch_lag,
438 int *exc_eng, int *scale)
440 int offset = PITCH_MAX + 2 * SUBFRAME_LEN;
441 int16_t *buf = p->audio + LPC_ORDER;
443 int index, ccr, tgt_eng, best_eng, temp;
445 *scale = ff_g723_1_scale_vector(buf, p->excitation, FRAME_LEN + PITCH_MAX);
448 /* Compute maximum backward cross-correlation */
450 index = autocorr_max(buf, offset, &ccr, pitch_lag, SUBFRAME_LEN * 2, -1);
451 ccr = av_sat_add32(ccr, 1 << 15) >> 16;
453 /* Compute target energy */
454 tgt_eng = ff_g723_1_dot_product(buf, buf, SUBFRAME_LEN * 2);
455 *exc_eng = av_sat_add32(tgt_eng, 1 << 15) >> 16;
460 /* Compute best energy */
461 best_eng = ff_g723_1_dot_product(buf - index, buf - index,
463 best_eng = av_sat_add32(best_eng, 1 << 15) >> 16;
465 temp = best_eng * *exc_eng >> 3;
467 if (temp < ccr * ccr) {
474 * Perform residual interpolation based on frame classification.
476 * @param buf decoded excitation vector
477 * @param out output vector
478 * @param lag decoded pitch lag
479 * @param gain interpolated gain
480 * @param rseed seed for random number generator
482 static void residual_interp(int16_t *buf, int16_t *out, int lag,
483 int gain, int *rseed)
486 if (lag) { /* Voiced */
487 int16_t *vector_ptr = buf + PITCH_MAX;
489 for (i = 0; i < lag; i++)
490 out[i] = vector_ptr[i - lag] * 3 >> 2;
491 av_memcpy_backptr((uint8_t*)(out + lag), lag * sizeof(*out),
492 (FRAME_LEN - lag) * sizeof(*out));
493 } else { /* Unvoiced */
494 for (i = 0; i < FRAME_LEN; i++) {
495 *rseed = (int16_t)(*rseed * 521 + 259);
496 out[i] = gain * *rseed >> 15;
498 memset(buf, 0, (FRAME_LEN + PITCH_MAX) * sizeof(*buf));
503 * Perform IIR filtering.
505 * @param fir_coef FIR coefficients
506 * @param iir_coef IIR coefficients
507 * @param src source vector
508 * @param dest destination vector
509 * @param width width of the output, 16 bits(0) / 32 bits(1)
511 #define iir_filter(fir_coef, iir_coef, src, dest, width)\
514 int res_shift = 16 & ~-(width);\
515 int in_shift = 16 - res_shift;\
517 for (m = 0; m < SUBFRAME_LEN; m++) {\
519 for (n = 1; n <= LPC_ORDER; n++) {\
520 filter -= (fir_coef)[n - 1] * (src)[m - n] -\
521 (iir_coef)[n - 1] * ((dest)[m - n] >> in_shift);\
524 (dest)[m] = av_clipl_int32(((src)[m] * 65536) + (filter * 8) +\
525 (1 << 15)) >> res_shift;\
530 * Adjust gain of postfiltered signal.
532 * @param p the context
533 * @param buf postfiltered output vector
534 * @param energy input energy coefficient
536 static void gain_scale(G723_1_ChannelContext *p, int16_t * buf, int energy)
538 int num, denom, gain, bits1, bits2;
543 for (i = 0; i < SUBFRAME_LEN; i++) {
544 int temp = buf[i] >> 2;
546 denom = av_sat_dadd32(denom, temp);
550 bits1 = ff_g723_1_normalize_bits(num, 31);
551 bits2 = ff_g723_1_normalize_bits(denom, 31);
552 num = num << bits1 >> 1;
555 bits2 = 5 + bits1 - bits2;
556 bits2 = av_clip_uintp2(bits2, 5);
558 gain = (num >> 1) / (denom >> 16);
559 gain = square_root(gain << 16 >> bits2);
564 for (i = 0; i < SUBFRAME_LEN; i++) {
565 p->pf_gain = (15 * p->pf_gain + gain + (1 << 3)) >> 4;
566 buf[i] = av_clip_int16((buf[i] * (p->pf_gain + (p->pf_gain >> 4)) +
572 * Perform formant filtering.
574 * @param p the context
575 * @param lpc quantized lpc coefficients
576 * @param buf input buffer
577 * @param dst output buffer
579 static void formant_postfilter(G723_1_ChannelContext *p, int16_t *lpc,
580 int16_t *buf, int16_t *dst)
582 int16_t filter_coef[2][LPC_ORDER];
583 int filter_signal[LPC_ORDER + FRAME_LEN], *signal_ptr;
586 memcpy(buf, p->fir_mem, LPC_ORDER * sizeof(*buf));
587 memcpy(filter_signal, p->iir_mem, LPC_ORDER * sizeof(*filter_signal));
589 for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
590 for (k = 0; k < LPC_ORDER; k++) {
591 filter_coef[0][k] = (-lpc[k] * postfilter_tbl[0][k] +
593 filter_coef[1][k] = (-lpc[k] * postfilter_tbl[1][k] +
596 iir_filter(filter_coef[0], filter_coef[1], buf + i, filter_signal + i, 1);
600 memcpy(p->fir_mem, buf + FRAME_LEN, LPC_ORDER * sizeof(int16_t));
601 memcpy(p->iir_mem, filter_signal + FRAME_LEN, LPC_ORDER * sizeof(int));
604 signal_ptr = filter_signal + LPC_ORDER;
605 for (i = 0; i < SUBFRAMES; i++) {
611 scale = ff_g723_1_scale_vector(dst, buf, SUBFRAME_LEN);
613 /* Compute auto correlation coefficients */
614 auto_corr[0] = ff_g723_1_dot_product(dst, dst + 1, SUBFRAME_LEN - 1);
615 auto_corr[1] = ff_g723_1_dot_product(dst, dst, SUBFRAME_LEN);
617 /* Compute reflection coefficient */
618 temp = auto_corr[1] >> 16;
620 temp = (auto_corr[0] >> 2) / temp;
622 p->reflection_coef = (3 * p->reflection_coef + temp + 2) >> 2;
623 temp = -p->reflection_coef >> 1 & ~3;
625 /* Compensation filter */
626 for (j = 0; j < SUBFRAME_LEN; j++) {
627 dst[j] = av_sat_dadd32(signal_ptr[j],
628 (signal_ptr[j - 1] >> 16) * temp) >> 16;
631 /* Compute normalized signal energy */
632 temp = 2 * scale + 4;
634 energy = av_clipl_int32((int64_t)auto_corr[1] << -temp);
636 energy = auto_corr[1] >> temp;
638 gain_scale(p, dst, energy);
641 signal_ptr += SUBFRAME_LEN;
646 static int sid_gain_to_lsp_index(int gain)
650 else if (gain < 0x20)
651 return gain - 8 << 7;
653 return gain - 20 << 8;
656 static inline int cng_rand(int *state, int base)
658 *state = (*state * 521 + 259) & 0xFFFF;
659 return (*state & 0x7FFF) * base >> 15;
662 static int estimate_sid_gain(G723_1_ChannelContext *p)
664 int i, shift, seg, seg2, t, val, val_add, x, y;
666 shift = 16 - p->cur_gain * 2;
668 if (p->sid_gain == 0) {
670 } else if (shift >= 31 || (int32_t)((uint32_t)p->sid_gain << shift) >> shift != p->sid_gain) {
671 if (p->sid_gain < 0) t = INT32_MIN;
674 t = p->sid_gain << shift;
676 t = p->sid_gain >> -shift;
677 x = av_clipl_int32(t * (int64_t)cng_filt[0] >> 16);
679 if (x >= cng_bseg[2])
682 if (x >= cng_bseg[1]) {
687 seg = (x >= cng_bseg[0]);
689 seg2 = FFMIN(seg, 3);
693 for (i = 0; i < shift; i++) {
694 t = seg * 32 + (val << seg2);
703 t = seg * 32 + (val << seg2);
706 t = seg * 32 + (val + 1 << seg2);
708 val = (seg2 - 1) * 16 + val;
712 t = seg * 32 + (val - 1 << seg2);
714 val = (seg2 - 1) * 16 + val;
722 static void generate_noise(G723_1_ChannelContext *p)
726 int signs[SUBFRAMES / 2 * 11], pos[SUBFRAMES / 2 * 11];
727 int tmp[SUBFRAME_LEN * 2];
730 int b0, c, delta, x, shift;
732 p->pitch_lag[0] = cng_rand(&p->cng_random_seed, 21) + 123;
733 p->pitch_lag[1] = cng_rand(&p->cng_random_seed, 19) + 123;
735 for (i = 0; i < SUBFRAMES; i++) {
736 p->subframe[i].ad_cb_gain = cng_rand(&p->cng_random_seed, 50) + 1;
737 p->subframe[i].ad_cb_lag = cng_adaptive_cb_lag[i];
740 for (i = 0; i < SUBFRAMES / 2; i++) {
741 t = cng_rand(&p->cng_random_seed, 1 << 13);
743 off[i * 2 + 1] = ((t >> 1) & 1) + SUBFRAME_LEN;
745 for (j = 0; j < 11; j++) {
746 signs[i * 11 + j] = ((t & 1) * 2 - 1) * (1 << 14);
752 for (i = 0; i < SUBFRAMES; i++) {
753 for (j = 0; j < SUBFRAME_LEN / 2; j++)
755 t = SUBFRAME_LEN / 2;
756 for (j = 0; j < pulses[i]; j++, idx++) {
757 int idx2 = cng_rand(&p->cng_random_seed, t);
759 pos[idx] = tmp[idx2] * 2 + off[i];
760 tmp[idx2] = tmp[--t];
764 vector_ptr = p->audio + LPC_ORDER;
765 memcpy(vector_ptr, p->prev_excitation,
766 PITCH_MAX * sizeof(*p->excitation));
767 for (i = 0; i < SUBFRAMES; i += 2) {
768 ff_g723_1_gen_acb_excitation(vector_ptr, vector_ptr,
769 p->pitch_lag[i >> 1], &p->subframe[i],
771 ff_g723_1_gen_acb_excitation(vector_ptr + SUBFRAME_LEN,
772 vector_ptr + SUBFRAME_LEN,
773 p->pitch_lag[i >> 1], &p->subframe[i + 1],
777 for (j = 0; j < SUBFRAME_LEN * 2; j++)
778 t |= FFABS(vector_ptr[j]);
779 t = FFMIN(t, 0x7FFF);
783 shift = -10 + av_log2(t);
789 for (j = 0; j < SUBFRAME_LEN * 2; j++) {
790 t = vector_ptr[j] * (1 << -shift);
795 for (j = 0; j < SUBFRAME_LEN * 2; j++) {
796 t = vector_ptr[j] >> shift;
803 for (j = 0; j < 11; j++)
804 b0 += tmp[pos[(i / 2) * 11 + j]] * signs[(i / 2) * 11 + j];
805 b0 = b0 * 2 * 2979LL + (1 << 29) >> 30; // approximated division by 11
807 c = p->cur_gain * (p->cur_gain * SUBFRAME_LEN >> 5);
808 if (shift * 2 + 3 >= 0)
811 c <<= -(shift * 2 + 3);
812 c = (av_clipl_int32(sum << 1) - c) * 2979LL >> 15;
814 delta = b0 * b0 * 2 - c;
818 delta = square_root(delta);
821 if (FFABS(t) < FFABS(x))
829 x = av_clip(x, -10000, 10000);
831 for (j = 0; j < 11; j++) {
832 idx = (i / 2) * 11 + j;
833 vector_ptr[pos[idx]] = av_clip_int16(vector_ptr[pos[idx]] +
834 (x * signs[idx] >> 15));
837 /* copy decoded data to serve as a history for the next decoded subframes */
838 memcpy(vector_ptr + PITCH_MAX, vector_ptr,
839 sizeof(*vector_ptr) * SUBFRAME_LEN * 2);
840 vector_ptr += SUBFRAME_LEN * 2;
842 /* Save the excitation for the next frame */
843 memcpy(p->prev_excitation, p->audio + LPC_ORDER + FRAME_LEN,
844 PITCH_MAX * sizeof(*p->excitation));
847 static int g723_1_decode_frame(AVCodecContext *avctx, void *data,
848 int *got_frame_ptr, AVPacket *avpkt)
850 G723_1_Context *s = avctx->priv_data;
851 AVFrame *frame = data;
852 const uint8_t *buf = avpkt->data;
853 int buf_size = avpkt->size;
854 int dec_mode = buf[0] & 3;
856 PPFParam ppf[SUBFRAMES];
857 int16_t cur_lsp[LPC_ORDER];
858 int16_t lpc[SUBFRAMES * LPC_ORDER];
859 int16_t acb_vector[SUBFRAME_LEN];
861 int bad_frame = 0, i, j, ret;
863 if (buf_size < frame_size[dec_mode] * avctx->channels) {
865 av_log(avctx, AV_LOG_WARNING,
866 "Expected %d bytes, got %d - skipping packet\n",
867 frame_size[dec_mode], buf_size);
872 frame->nb_samples = FRAME_LEN;
873 if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
876 for (int ch = 0; ch < avctx->channels; ch++) {
877 G723_1_ChannelContext *p = &s->ch[ch];
878 int16_t *audio = p->audio;
880 if (unpack_bitstream(p, buf, buf_size) < 0) {
882 if (p->past_frame_type == ACTIVE_FRAME)
883 p->cur_frame_type = ACTIVE_FRAME;
885 p->cur_frame_type = UNTRANSMITTED_FRAME;
888 out = (int16_t *)frame->extended_data[ch];
890 if (p->cur_frame_type == ACTIVE_FRAME) {
892 p->erased_frames = 0;
893 else if (p->erased_frames != 3)
896 ff_g723_1_inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, bad_frame);
897 ff_g723_1_lsp_interpolate(lpc, cur_lsp, p->prev_lsp);
899 /* Save the lsp_vector for the next frame */
900 memcpy(p->prev_lsp, cur_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
902 /* Generate the excitation for the frame */
903 memcpy(p->excitation, p->prev_excitation,
904 PITCH_MAX * sizeof(*p->excitation));
905 if (!p->erased_frames) {
906 int16_t *vector_ptr = p->excitation + PITCH_MAX;
908 /* Update interpolation gain memory */
909 p->interp_gain = fixed_cb_gain[(p->subframe[2].amp_index +
910 p->subframe[3].amp_index) >> 1];
911 for (i = 0; i < SUBFRAMES; i++) {
912 gen_fcb_excitation(vector_ptr, &p->subframe[i], p->cur_rate,
913 p->pitch_lag[i >> 1], i);
914 ff_g723_1_gen_acb_excitation(acb_vector,
915 &p->excitation[SUBFRAME_LEN * i],
916 p->pitch_lag[i >> 1],
917 &p->subframe[i], p->cur_rate);
918 /* Get the total excitation */
919 for (j = 0; j < SUBFRAME_LEN; j++) {
920 int v = av_clip_int16(vector_ptr[j] * 2);
921 vector_ptr[j] = av_clip_int16(v + acb_vector[j]);
923 vector_ptr += SUBFRAME_LEN;
926 vector_ptr = p->excitation + PITCH_MAX;
928 p->interp_index = comp_interp_index(p, p->pitch_lag[1],
929 &p->sid_gain, &p->cur_gain);
931 /* Perform pitch postfiltering */
934 for (j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
935 comp_ppf_coeff(p, i, p->pitch_lag[j >> 1],
936 ppf + j, p->cur_rate);
938 for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
939 ff_acelp_weighted_vector_sum(p->audio + LPC_ORDER + i,
941 vector_ptr + i + ppf[j].index,
944 1 << 14, 15, SUBFRAME_LEN);
946 audio = vector_ptr - LPC_ORDER;
949 /* Save the excitation for the next frame */
950 memcpy(p->prev_excitation, p->excitation + FRAME_LEN,
951 PITCH_MAX * sizeof(*p->excitation));
953 p->interp_gain = (p->interp_gain * 3 + 2) >> 2;
954 if (p->erased_frames == 3) {
956 memset(p->excitation, 0,
957 (FRAME_LEN + PITCH_MAX) * sizeof(*p->excitation));
958 memset(p->prev_excitation, 0,
959 PITCH_MAX * sizeof(*p->excitation));
960 memset(frame->data[0], 0,
961 (FRAME_LEN + LPC_ORDER) * sizeof(int16_t));
963 int16_t *buf = p->audio + LPC_ORDER;
965 /* Regenerate frame */
966 residual_interp(p->excitation, buf, p->interp_index,
967 p->interp_gain, &p->random_seed);
969 /* Save the excitation for the next frame */
970 memcpy(p->prev_excitation, buf + (FRAME_LEN - PITCH_MAX),
971 PITCH_MAX * sizeof(*p->excitation));
974 p->cng_random_seed = CNG_RANDOM_SEED;
976 if (p->cur_frame_type == SID_FRAME) {
977 p->sid_gain = sid_gain_to_lsp_index(p->subframe[0].amp_index);
978 ff_g723_1_inverse_quant(p->sid_lsp, p->prev_lsp, p->lsp_index, 0);
979 } else if (p->past_frame_type == ACTIVE_FRAME) {
980 p->sid_gain = estimate_sid_gain(p);
983 if (p->past_frame_type == ACTIVE_FRAME)
984 p->cur_gain = p->sid_gain;
986 p->cur_gain = (p->cur_gain * 7 + p->sid_gain) >> 3;
988 ff_g723_1_lsp_interpolate(lpc, p->sid_lsp, p->prev_lsp);
989 /* Save the lsp_vector for the next frame */
990 memcpy(p->prev_lsp, p->sid_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
993 p->past_frame_type = p->cur_frame_type;
995 memcpy(p->audio, p->synth_mem, LPC_ORDER * sizeof(*p->audio));
996 for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
997 ff_celp_lp_synthesis_filter(p->audio + i, &lpc[j * LPC_ORDER],
998 audio + i, SUBFRAME_LEN, LPC_ORDER,
1000 memcpy(p->synth_mem, p->audio + FRAME_LEN, LPC_ORDER * sizeof(*p->audio));
1002 if (s->postfilter) {
1003 formant_postfilter(p, lpc, p->audio, out);
1004 } else { // if output is not postfiltered it should be scaled by 2
1005 for (i = 0; i < FRAME_LEN; i++)
1006 out[i] = av_clip_int16(p->audio[LPC_ORDER + i] << 1);
1012 return frame_size[dec_mode] * avctx->channels;
1015 #define OFFSET(x) offsetof(G723_1_Context, x)
1016 #define AD AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1018 static const AVOption options[] = {
1019 { "postfilter", "enable postfilter", OFFSET(postfilter), AV_OPT_TYPE_BOOL,
1020 { .i64 = 1 }, 0, 1, AD },
1025 static const AVClass g723_1dec_class = {
1026 .class_name = "G.723.1 decoder",
1027 .item_name = av_default_item_name,
1029 .version = LIBAVUTIL_VERSION_INT,
1032 AVCodec ff_g723_1_decoder = {
1034 .long_name = NULL_IF_CONFIG_SMALL("G.723.1"),
1035 .type = AVMEDIA_TYPE_AUDIO,
1036 .id = AV_CODEC_ID_G723_1,
1037 .priv_data_size = sizeof(G723_1_Context),
1038 .init = g723_1_decode_init,
1039 .decode = g723_1_decode_frame,
1040 .capabilities = AV_CODEC_CAP_SUBFRAMES | AV_CODEC_CAP_DR1,
1041 .priv_class = &g723_1dec_class,