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 #define BITSTREAM_READER_LE
29 #include "libavutil/audioconvert.h"
30 #include "libavutil/lzo.h"
31 #include "libavutil/opt.h"
35 #include "acelp_vectors.h"
36 #include "celp_filters.h"
37 #include "celp_math.h"
38 #include "g723_1_data.h"
40 #define CNG_RANDOM_SEED 12345
42 typedef struct g723_1_context {
46 G723_1_Subframe subframe[4];
47 enum FrameType cur_frame_type;
48 enum FrameType past_frame_type;
50 uint8_t lsp_index[LSP_BANDS];
54 int16_t prev_lsp[LPC_ORDER];
55 int16_t sid_lsp[LPC_ORDER];
56 int16_t prev_excitation[PITCH_MAX];
57 int16_t excitation[PITCH_MAX + FRAME_LEN + 4];
58 int16_t synth_mem[LPC_ORDER];
59 int16_t fir_mem[LPC_ORDER];
60 int iir_mem[LPC_ORDER];
69 int pf_gain; ///< formant postfilter
70 ///< gain scaling unit memory
73 int16_t audio[FRAME_LEN + LPC_ORDER + PITCH_MAX + 4];
74 int16_t prev_data[HALF_FRAME_LEN];
75 int16_t prev_weight_sig[PITCH_MAX];
78 int16_t hpf_fir_mem; ///< highpass filter fir
79 int hpf_iir_mem; ///< and iir memories
80 int16_t perf_fir_mem[LPC_ORDER]; ///< perceptual filter fir
81 int16_t perf_iir_mem[LPC_ORDER]; ///< and iir memories
83 int16_t harmonic_mem[PITCH_MAX];
86 static av_cold int g723_1_decode_init(AVCodecContext *avctx)
88 G723_1_Context *p = avctx->priv_data;
90 avctx->channel_layout = AV_CH_LAYOUT_MONO;
91 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
95 avcodec_get_frame_defaults(&p->frame);
96 avctx->coded_frame = &p->frame;
98 memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
99 memcpy(p->sid_lsp, dc_lsp, LPC_ORDER * sizeof(*p->sid_lsp));
101 p->cng_random_seed = CNG_RANDOM_SEED;
102 p->past_frame_type = SID_FRAME;
108 * Unpack the frame into parameters.
110 * @param p the context
111 * @param buf pointer to the input buffer
112 * @param buf_size size of the input buffer
114 static int unpack_bitstream(G723_1_Context *p, const uint8_t *buf,
119 int temp, info_bits, i;
121 init_get_bits(&gb, buf, buf_size * 8);
123 /* Extract frame type and rate info */
124 info_bits = get_bits(&gb, 2);
126 if (info_bits == 3) {
127 p->cur_frame_type = UNTRANSMITTED_FRAME;
131 /* Extract 24 bit lsp indices, 8 bit for each band */
132 p->lsp_index[2] = get_bits(&gb, 8);
133 p->lsp_index[1] = get_bits(&gb, 8);
134 p->lsp_index[0] = get_bits(&gb, 8);
136 if (info_bits == 2) {
137 p->cur_frame_type = SID_FRAME;
138 p->subframe[0].amp_index = get_bits(&gb, 6);
142 /* Extract the info common to both rates */
143 p->cur_rate = info_bits ? RATE_5300 : RATE_6300;
144 p->cur_frame_type = ACTIVE_FRAME;
146 p->pitch_lag[0] = get_bits(&gb, 7);
147 if (p->pitch_lag[0] > 123) /* test if forbidden code */
149 p->pitch_lag[0] += PITCH_MIN;
150 p->subframe[1].ad_cb_lag = get_bits(&gb, 2);
152 p->pitch_lag[1] = get_bits(&gb, 7);
153 if (p->pitch_lag[1] > 123)
155 p->pitch_lag[1] += PITCH_MIN;
156 p->subframe[3].ad_cb_lag = get_bits(&gb, 2);
157 p->subframe[0].ad_cb_lag = 1;
158 p->subframe[2].ad_cb_lag = 1;
160 for (i = 0; i < SUBFRAMES; i++) {
161 /* Extract combined gain */
162 temp = get_bits(&gb, 12);
164 p->subframe[i].dirac_train = 0;
165 if (p->cur_rate == RATE_6300 && p->pitch_lag[i >> 1] < SUBFRAME_LEN - 2) {
166 p->subframe[i].dirac_train = temp >> 11;
170 p->subframe[i].ad_cb_gain = FASTDIV(temp, GAIN_LEVELS);
171 if (p->subframe[i].ad_cb_gain < ad_cb_len) {
172 p->subframe[i].amp_index = temp - p->subframe[i].ad_cb_gain *
179 p->subframe[0].grid_index = get_bits1(&gb);
180 p->subframe[1].grid_index = get_bits1(&gb);
181 p->subframe[2].grid_index = get_bits1(&gb);
182 p->subframe[3].grid_index = get_bits1(&gb);
184 if (p->cur_rate == RATE_6300) {
185 skip_bits1(&gb); /* skip reserved bit */
187 /* Compute pulse_pos index using the 13-bit combined position index */
188 temp = get_bits(&gb, 13);
189 p->subframe[0].pulse_pos = temp / 810;
191 temp -= p->subframe[0].pulse_pos * 810;
192 p->subframe[1].pulse_pos = FASTDIV(temp, 90);
194 temp -= p->subframe[1].pulse_pos * 90;
195 p->subframe[2].pulse_pos = FASTDIV(temp, 9);
196 p->subframe[3].pulse_pos = temp - p->subframe[2].pulse_pos * 9;
198 p->subframe[0].pulse_pos = (p->subframe[0].pulse_pos << 16) +
200 p->subframe[1].pulse_pos = (p->subframe[1].pulse_pos << 14) +
202 p->subframe[2].pulse_pos = (p->subframe[2].pulse_pos << 16) +
204 p->subframe[3].pulse_pos = (p->subframe[3].pulse_pos << 14) +
207 p->subframe[0].pulse_sign = get_bits(&gb, 6);
208 p->subframe[1].pulse_sign = get_bits(&gb, 5);
209 p->subframe[2].pulse_sign = get_bits(&gb, 6);
210 p->subframe[3].pulse_sign = get_bits(&gb, 5);
211 } else { /* 5300 bps */
212 p->subframe[0].pulse_pos = get_bits(&gb, 12);
213 p->subframe[1].pulse_pos = get_bits(&gb, 12);
214 p->subframe[2].pulse_pos = get_bits(&gb, 12);
215 p->subframe[3].pulse_pos = get_bits(&gb, 12);
217 p->subframe[0].pulse_sign = get_bits(&gb, 4);
218 p->subframe[1].pulse_sign = get_bits(&gb, 4);
219 p->subframe[2].pulse_sign = get_bits(&gb, 4);
220 p->subframe[3].pulse_sign = get_bits(&gb, 4);
227 * Bitexact implementation of sqrt(val/2).
229 static int16_t square_root(int val)
231 return (ff_sqrt(val << 1) >> 1) & (~1);
235 * Calculate the number of left-shifts required for normalizing the input.
237 * @param num input number
238 * @param width width of the input, 15 or 31 bits
240 static int normalize_bits(int num, int width)
242 return width - av_log2(num) - 1;
245 #define normalize_bits_int16(num) normalize_bits(num, 15)
246 #define normalize_bits_int32(num) normalize_bits(num, 31)
249 * Scale vector contents based on the largest of their absolutes.
251 static int scale_vector(int16_t *dst, const int16_t *vector, int length)
256 for (i = 0; i < length; i++)
257 max |= FFABS(vector[i]);
259 bits= 14 - av_log2_16bit(max);
260 bits= FFMAX(bits, 0);
262 for (i = 0; i < length; i++)
263 dst[i] = vector[i] << bits >> 3;
269 * Perform inverse quantization of LSP frequencies.
271 * @param cur_lsp the current LSP vector
272 * @param prev_lsp the previous LSP vector
273 * @param lsp_index VQ indices
274 * @param bad_frame bad frame flag
276 static void inverse_quant(int16_t *cur_lsp, int16_t *prev_lsp,
277 uint8_t *lsp_index, int bad_frame)
280 int i, j, temp, stable;
282 /* Check for frame erasure */
289 lsp_index[0] = lsp_index[1] = lsp_index[2] = 0;
292 /* Get the VQ table entry corresponding to the transmitted index */
293 cur_lsp[0] = lsp_band0[lsp_index[0]][0];
294 cur_lsp[1] = lsp_band0[lsp_index[0]][1];
295 cur_lsp[2] = lsp_band0[lsp_index[0]][2];
296 cur_lsp[3] = lsp_band1[lsp_index[1]][0];
297 cur_lsp[4] = lsp_band1[lsp_index[1]][1];
298 cur_lsp[5] = lsp_band1[lsp_index[1]][2];
299 cur_lsp[6] = lsp_band2[lsp_index[2]][0];
300 cur_lsp[7] = lsp_band2[lsp_index[2]][1];
301 cur_lsp[8] = lsp_band2[lsp_index[2]][2];
302 cur_lsp[9] = lsp_band2[lsp_index[2]][3];
304 /* Add predicted vector & DC component to the previously quantized vector */
305 for (i = 0; i < LPC_ORDER; i++) {
306 temp = ((prev_lsp[i] - dc_lsp[i]) * pred + (1 << 14)) >> 15;
307 cur_lsp[i] += dc_lsp[i] + temp;
310 for (i = 0; i < LPC_ORDER; i++) {
311 cur_lsp[0] = FFMAX(cur_lsp[0], 0x180);
312 cur_lsp[LPC_ORDER - 1] = FFMIN(cur_lsp[LPC_ORDER - 1], 0x7e00);
314 /* Stability check */
315 for (j = 1; j < LPC_ORDER; j++) {
316 temp = min_dist + cur_lsp[j - 1] - cur_lsp[j];
319 cur_lsp[j - 1] -= temp;
324 for (j = 1; j < LPC_ORDER; j++) {
325 temp = cur_lsp[j - 1] + min_dist - cur_lsp[j] - 4;
335 memcpy(cur_lsp, prev_lsp, LPC_ORDER * sizeof(*cur_lsp));
339 * Bitexact implementation of 2ab scaled by 1/2^16.
341 * @param a 32 bit multiplicand
342 * @param b 16 bit multiplier
344 #define MULL2(a, b) \
348 * Convert LSP frequencies to LPC coefficients.
350 * @param lpc buffer for LPC coefficients
352 static void lsp2lpc(int16_t *lpc)
354 int f1[LPC_ORDER / 2 + 1];
355 int f2[LPC_ORDER / 2 + 1];
358 /* Calculate negative cosine */
359 for (j = 0; j < LPC_ORDER; j++) {
360 int index = lpc[j] >> 7;
361 int offset = lpc[j] & 0x7f;
362 int temp1 = cos_tab[index] << 16;
363 int temp2 = (cos_tab[index + 1] - cos_tab[index]) *
364 ((offset << 8) + 0x80) << 1;
366 lpc[j] = -(av_sat_dadd32(1 << 15, temp1 + temp2) >> 16);
370 * Compute sum and difference polynomial coefficients
371 * (bitexact alternative to lsp2poly() in lsp.c)
373 /* Initialize with values in Q28 */
375 f1[1] = (lpc[0] << 14) + (lpc[2] << 14);
376 f1[2] = lpc[0] * lpc[2] + (2 << 28);
379 f2[1] = (lpc[1] << 14) + (lpc[3] << 14);
380 f2[2] = lpc[1] * lpc[3] + (2 << 28);
383 * Calculate and scale the coefficients by 1/2 in
384 * each iteration for a final scaling factor of Q25
386 for (i = 2; i < LPC_ORDER / 2; i++) {
387 f1[i + 1] = f1[i - 1] + MULL2(f1[i], lpc[2 * i]);
388 f2[i + 1] = f2[i - 1] + MULL2(f2[i], lpc[2 * i + 1]);
390 for (j = i; j >= 2; j--) {
391 f1[j] = MULL2(f1[j - 1], lpc[2 * i]) +
392 (f1[j] >> 1) + (f1[j - 2] >> 1);
393 f2[j] = MULL2(f2[j - 1], lpc[2 * i + 1]) +
394 (f2[j] >> 1) + (f2[j - 2] >> 1);
399 f1[1] = ((lpc[2 * i] << 16 >> i) + f1[1]) >> 1;
400 f2[1] = ((lpc[2 * i + 1] << 16 >> i) + f2[1]) >> 1;
403 /* Convert polynomial coefficients to LPC coefficients */
404 for (i = 0; i < LPC_ORDER / 2; i++) {
405 int64_t ff1 = f1[i + 1] + f1[i];
406 int64_t ff2 = f2[i + 1] - f2[i];
408 lpc[i] = av_clipl_int32(((ff1 + ff2) << 3) + (1 << 15)) >> 16;
409 lpc[LPC_ORDER - i - 1] = av_clipl_int32(((ff1 - ff2) << 3) +
415 * Quantize LSP frequencies by interpolation and convert them to
416 * the corresponding LPC coefficients.
418 * @param lpc buffer for LPC coefficients
419 * @param cur_lsp the current LSP vector
420 * @param prev_lsp the previous LSP vector
422 static void lsp_interpolate(int16_t *lpc, int16_t *cur_lsp, int16_t *prev_lsp)
425 int16_t *lpc_ptr = lpc;
427 /* cur_lsp * 0.25 + prev_lsp * 0.75 */
428 ff_acelp_weighted_vector_sum(lpc, cur_lsp, prev_lsp,
429 4096, 12288, 1 << 13, 14, LPC_ORDER);
430 ff_acelp_weighted_vector_sum(lpc + LPC_ORDER, cur_lsp, prev_lsp,
431 8192, 8192, 1 << 13, 14, LPC_ORDER);
432 ff_acelp_weighted_vector_sum(lpc + 2 * LPC_ORDER, cur_lsp, prev_lsp,
433 12288, 4096, 1 << 13, 14, LPC_ORDER);
434 memcpy(lpc + 3 * LPC_ORDER, cur_lsp, LPC_ORDER * sizeof(*lpc));
436 for (i = 0; i < SUBFRAMES; i++) {
438 lpc_ptr += LPC_ORDER;
443 * Generate a train of dirac functions with period as pitch lag.
445 static void gen_dirac_train(int16_t *buf, int pitch_lag)
447 int16_t vector[SUBFRAME_LEN];
450 memcpy(vector, buf, SUBFRAME_LEN * sizeof(*vector));
451 for (i = pitch_lag; i < SUBFRAME_LEN; i += pitch_lag) {
452 for (j = 0; j < SUBFRAME_LEN - i; j++)
453 buf[i + j] += vector[j];
458 * Generate fixed codebook excitation vector.
460 * @param vector decoded excitation vector
461 * @param subfrm current subframe
462 * @param cur_rate current bitrate
463 * @param pitch_lag closed loop pitch lag
464 * @param index current subframe index
466 static void gen_fcb_excitation(int16_t *vector, G723_1_Subframe *subfrm,
467 enum Rate cur_rate, int pitch_lag, int index)
471 memset(vector, 0, SUBFRAME_LEN * sizeof(*vector));
473 if (cur_rate == RATE_6300) {
474 if (subfrm->pulse_pos >= max_pos[index])
477 /* Decode amplitudes and positions */
478 j = PULSE_MAX - pulses[index];
479 temp = subfrm->pulse_pos;
480 for (i = 0; i < SUBFRAME_LEN / GRID_SIZE; i++) {
481 temp -= combinatorial_table[j][i];
484 temp += combinatorial_table[j++][i];
485 if (subfrm->pulse_sign & (1 << (PULSE_MAX - j))) {
486 vector[subfrm->grid_index + GRID_SIZE * i] =
487 -fixed_cb_gain[subfrm->amp_index];
489 vector[subfrm->grid_index + GRID_SIZE * i] =
490 fixed_cb_gain[subfrm->amp_index];
495 if (subfrm->dirac_train == 1)
496 gen_dirac_train(vector, pitch_lag);
497 } else { /* 5300 bps */
498 int cb_gain = fixed_cb_gain[subfrm->amp_index];
499 int cb_shift = subfrm->grid_index;
500 int cb_sign = subfrm->pulse_sign;
501 int cb_pos = subfrm->pulse_pos;
502 int offset, beta, lag;
504 for (i = 0; i < 8; i += 2) {
505 offset = ((cb_pos & 7) << 3) + cb_shift + i;
506 vector[offset] = (cb_sign & 1) ? cb_gain : -cb_gain;
511 /* Enhance harmonic components */
512 lag = pitch_contrib[subfrm->ad_cb_gain << 1] + pitch_lag +
513 subfrm->ad_cb_lag - 1;
514 beta = pitch_contrib[(subfrm->ad_cb_gain << 1) + 1];
516 if (lag < SUBFRAME_LEN - 2) {
517 for (i = lag; i < SUBFRAME_LEN; i++)
518 vector[i] += beta * vector[i - lag] >> 15;
524 * Get delayed contribution from the previous excitation vector.
526 static void get_residual(int16_t *residual, int16_t *prev_excitation, int lag)
528 int offset = PITCH_MAX - PITCH_ORDER / 2 - lag;
531 residual[0] = prev_excitation[offset];
532 residual[1] = prev_excitation[offset + 1];
535 for (i = 2; i < SUBFRAME_LEN + PITCH_ORDER - 1; i++)
536 residual[i] = prev_excitation[offset + (i - 2) % lag];
539 static int dot_product(const int16_t *a, const int16_t *b, int length)
541 int sum = ff_dot_product(a,b,length);
542 return av_sat_add32(sum, sum);
546 * Generate adaptive codebook excitation.
548 static void gen_acb_excitation(int16_t *vector, int16_t *prev_excitation,
549 int pitch_lag, G723_1_Subframe *subfrm,
552 int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
553 const int16_t *cb_ptr;
554 int lag = pitch_lag + subfrm->ad_cb_lag - 1;
559 get_residual(residual, prev_excitation, lag);
561 /* Select quantization table */
562 if (cur_rate == RATE_6300 && pitch_lag < SUBFRAME_LEN - 2) {
563 cb_ptr = adaptive_cb_gain85;
565 cb_ptr = adaptive_cb_gain170;
567 /* Calculate adaptive vector */
568 cb_ptr += subfrm->ad_cb_gain * 20;
569 for (i = 0; i < SUBFRAME_LEN; i++) {
570 sum = ff_dot_product(residual + i, cb_ptr, PITCH_ORDER);
571 vector[i] = av_sat_dadd32(1 << 15, av_sat_add32(sum, sum)) >> 16;
576 * Estimate maximum auto-correlation around pitch lag.
578 * @param buf buffer with offset applied
579 * @param offset offset of the excitation vector
580 * @param ccr_max pointer to the maximum auto-correlation
581 * @param pitch_lag decoded pitch lag
582 * @param length length of autocorrelation
583 * @param dir forward lag(1) / backward lag(-1)
585 static int autocorr_max(const int16_t *buf, int offset, int *ccr_max,
586 int pitch_lag, int length, int dir)
588 int limit, ccr, lag = 0;
591 pitch_lag = FFMIN(PITCH_MAX - 3, pitch_lag);
593 limit = FFMIN(FRAME_LEN + PITCH_MAX - offset - length, pitch_lag + 3);
595 limit = pitch_lag + 3;
597 for (i = pitch_lag - 3; i <= limit; i++) {
598 ccr = dot_product(buf, buf + dir * i, length);
600 if (ccr > *ccr_max) {
609 * Calculate pitch postfilter optimal and scaling gains.
611 * @param lag pitch postfilter forward/backward lag
612 * @param ppf pitch postfilter parameters
613 * @param cur_rate current bitrate
614 * @param tgt_eng target energy
615 * @param ccr cross-correlation
616 * @param res_eng residual energy
618 static void comp_ppf_gains(int lag, PPFParam *ppf, enum Rate cur_rate,
619 int tgt_eng, int ccr, int res_eng)
621 int pf_residual; /* square of postfiltered residual */
626 temp1 = tgt_eng * res_eng >> 1;
627 temp2 = ccr * ccr << 1;
630 if (ccr >= res_eng) {
631 ppf->opt_gain = ppf_gain_weight[cur_rate];
633 ppf->opt_gain = (ccr << 15) / res_eng *
634 ppf_gain_weight[cur_rate] >> 15;
636 /* pf_res^2 = tgt_eng + 2*ccr*gain + res_eng*gain^2 */
637 temp1 = (tgt_eng << 15) + (ccr * ppf->opt_gain << 1);
638 temp2 = (ppf->opt_gain * ppf->opt_gain >> 15) * res_eng;
639 pf_residual = av_sat_add32(temp1, temp2 + (1 << 15)) >> 16;
641 if (tgt_eng >= pf_residual << 1) {
644 temp1 = (tgt_eng << 14) / pf_residual;
647 /* scaling_gain = sqrt(tgt_eng/pf_res^2) */
648 ppf->sc_gain = square_root(temp1 << 16);
651 ppf->sc_gain = 0x7fff;
654 ppf->opt_gain = av_clip_int16(ppf->opt_gain * ppf->sc_gain >> 15);
658 * Calculate pitch postfilter parameters.
660 * @param p the context
661 * @param offset offset of the excitation vector
662 * @param pitch_lag decoded pitch lag
663 * @param ppf pitch postfilter parameters
664 * @param cur_rate current bitrate
666 static void comp_ppf_coeff(G723_1_Context *p, int offset, int pitch_lag,
667 PPFParam *ppf, enum Rate cur_rate)
676 * 1 - forward cross-correlation
677 * 2 - forward residual energy
678 * 3 - backward cross-correlation
679 * 4 - backward residual energy
681 int energy[5] = {0, 0, 0, 0, 0};
682 int16_t *buf = p->audio + LPC_ORDER + offset;
683 int fwd_lag = autocorr_max(buf, offset, &energy[1], pitch_lag,
685 int back_lag = autocorr_max(buf, offset, &energy[3], pitch_lag,
690 ppf->sc_gain = 0x7fff;
692 /* Case 0, Section 3.6 */
693 if (!back_lag && !fwd_lag)
696 /* Compute target energy */
697 energy[0] = dot_product(buf, buf, SUBFRAME_LEN);
699 /* Compute forward residual energy */
701 energy[2] = dot_product(buf + fwd_lag, buf + fwd_lag, SUBFRAME_LEN);
703 /* Compute backward residual energy */
705 energy[4] = dot_product(buf - back_lag, buf - back_lag, SUBFRAME_LEN);
707 /* Normalize and shorten */
709 for (i = 0; i < 5; i++)
710 temp1 = FFMAX(energy[i], temp1);
712 scale = normalize_bits(temp1, 31);
713 for (i = 0; i < 5; i++)
714 energy[i] = av_clipl_int32(energy[i] << scale) >> 16;
716 if (fwd_lag && !back_lag) { /* Case 1 */
717 comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
719 } else if (!fwd_lag) { /* Case 2 */
720 comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
722 } else { /* Case 3 */
725 * Select the largest of energy[1]^2/energy[2]
726 * and energy[3]^2/energy[4]
728 temp1 = energy[4] * ((energy[1] * energy[1] + (1 << 14)) >> 15);
729 temp2 = energy[2] * ((energy[3] * energy[3] + (1 << 14)) >> 15);
730 if (temp1 >= temp2) {
731 comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
734 comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
741 * Classify frames as voiced/unvoiced.
743 * @param p the context
744 * @param pitch_lag decoded pitch_lag
745 * @param exc_eng excitation energy estimation
746 * @param scale scaling factor of exc_eng
748 * @return residual interpolation index if voiced, 0 otherwise
750 static int comp_interp_index(G723_1_Context *p, int pitch_lag,
751 int *exc_eng, int *scale)
753 int offset = PITCH_MAX + 2 * SUBFRAME_LEN;
754 int16_t *buf = p->audio + LPC_ORDER;
756 int index, ccr, tgt_eng, best_eng, temp;
758 *scale = scale_vector(buf, p->excitation, FRAME_LEN + PITCH_MAX);
761 /* Compute maximum backward cross-correlation */
763 index = autocorr_max(buf, offset, &ccr, pitch_lag, SUBFRAME_LEN * 2, -1);
764 ccr = av_sat_add32(ccr, 1 << 15) >> 16;
766 /* Compute target energy */
767 tgt_eng = dot_product(buf, buf, SUBFRAME_LEN * 2);
768 *exc_eng = av_sat_add32(tgt_eng, 1 << 15) >> 16;
773 /* Compute best energy */
774 best_eng = dot_product(buf - index, buf - index, SUBFRAME_LEN * 2);
775 best_eng = av_sat_add32(best_eng, 1 << 15) >> 16;
777 temp = best_eng * *exc_eng >> 3;
779 if (temp < ccr * ccr) {
786 * Peform residual interpolation based on frame classification.
788 * @param buf decoded excitation vector
789 * @param out output vector
790 * @param lag decoded pitch lag
791 * @param gain interpolated gain
792 * @param rseed seed for random number generator
794 static void residual_interp(int16_t *buf, int16_t *out, int lag,
795 int gain, int *rseed)
798 if (lag) { /* Voiced */
799 int16_t *vector_ptr = buf + PITCH_MAX;
801 for (i = 0; i < lag; i++)
802 out[i] = vector_ptr[i - lag] * 3 >> 2;
803 av_memcpy_backptr((uint8_t*)(out + lag), lag * sizeof(*out),
804 (FRAME_LEN - lag) * sizeof(*out));
805 } else { /* Unvoiced */
806 for (i = 0; i < FRAME_LEN; i++) {
807 *rseed = *rseed * 521 + 259;
808 out[i] = gain * *rseed >> 15;
810 memset(buf, 0, (FRAME_LEN + PITCH_MAX) * sizeof(*buf));
815 * Perform IIR filtering.
817 * @param fir_coef FIR coefficients
818 * @param iir_coef IIR coefficients
819 * @param src source vector
820 * @param dest destination vector
821 * @param width width of the output, 16 bits(0) / 32 bits(1)
823 #define iir_filter(fir_coef, iir_coef, src, dest, width)\
826 int res_shift = 16 & ~-(width);\
827 int in_shift = 16 - res_shift;\
829 for (m = 0; m < SUBFRAME_LEN; m++) {\
831 for (n = 1; n <= LPC_ORDER; n++) {\
832 filter -= (fir_coef)[n - 1] * (src)[m - n] -\
833 (iir_coef)[n - 1] * ((dest)[m - n] >> in_shift);\
836 (dest)[m] = av_clipl_int32(((src)[m] << 16) + (filter << 3) +\
837 (1 << 15)) >> res_shift;\
842 * Adjust gain of postfiltered signal.
844 * @param p the context
845 * @param buf postfiltered output vector
846 * @param energy input energy coefficient
848 static void gain_scale(G723_1_Context *p, int16_t * buf, int energy)
850 int num, denom, gain, bits1, bits2;
855 for (i = 0; i < SUBFRAME_LEN; i++) {
856 int temp = buf[i] >> 2;
858 denom = av_sat_dadd32(denom, temp);
862 bits1 = normalize_bits(num, 31);
863 bits2 = normalize_bits(denom, 31);
864 num = num << bits1 >> 1;
867 bits2 = 5 + bits1 - bits2;
868 bits2 = FFMAX(0, bits2);
870 gain = (num >> 1) / (denom >> 16);
871 gain = square_root(gain << 16 >> bits2);
876 for (i = 0; i < SUBFRAME_LEN; i++) {
877 p->pf_gain = (15 * p->pf_gain + gain + (1 << 3)) >> 4;
878 buf[i] = av_clip_int16((buf[i] * (p->pf_gain + (p->pf_gain >> 4)) +
884 * Perform formant filtering.
886 * @param p the context
887 * @param lpc quantized lpc coefficients
888 * @param buf input buffer
889 * @param dst output buffer
891 static void formant_postfilter(G723_1_Context *p, int16_t *lpc,
892 int16_t *buf, int16_t *dst)
894 int16_t filter_coef[2][LPC_ORDER];
895 int filter_signal[LPC_ORDER + FRAME_LEN], *signal_ptr;
898 memcpy(buf, p->fir_mem, LPC_ORDER * sizeof(*buf));
899 memcpy(filter_signal, p->iir_mem, LPC_ORDER * sizeof(*filter_signal));
901 for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
902 for (k = 0; k < LPC_ORDER; k++) {
903 filter_coef[0][k] = (-lpc[k] * postfilter_tbl[0][k] +
905 filter_coef[1][k] = (-lpc[k] * postfilter_tbl[1][k] +
908 iir_filter(filter_coef[0], filter_coef[1], buf + i,
909 filter_signal + i, 1);
913 memcpy(p->fir_mem, buf + FRAME_LEN, LPC_ORDER * sizeof(int16_t));
914 memcpy(p->iir_mem, filter_signal + FRAME_LEN, LPC_ORDER * sizeof(int));
917 signal_ptr = filter_signal + LPC_ORDER;
918 for (i = 0; i < SUBFRAMES; i++) {
924 scale = scale_vector(dst, buf, SUBFRAME_LEN);
926 /* Compute auto correlation coefficients */
927 auto_corr[0] = dot_product(dst, dst + 1, SUBFRAME_LEN - 1);
928 auto_corr[1] = dot_product(dst, dst, SUBFRAME_LEN);
930 /* Compute reflection coefficient */
931 temp = auto_corr[1] >> 16;
933 temp = (auto_corr[0] >> 2) / temp;
935 p->reflection_coef = (3 * p->reflection_coef + temp + 2) >> 2;
936 temp = -p->reflection_coef >> 1 & ~3;
938 /* Compensation filter */
939 for (j = 0; j < SUBFRAME_LEN; j++) {
940 dst[j] = av_sat_dadd32(signal_ptr[j],
941 (signal_ptr[j - 1] >> 16) * temp) >> 16;
944 /* Compute normalized signal energy */
945 temp = 2 * scale + 4;
947 energy = av_clipl_int32((int64_t)auto_corr[1] << -temp);
949 energy = auto_corr[1] >> temp;
951 gain_scale(p, dst, energy);
954 signal_ptr += SUBFRAME_LEN;
959 static int sid_gain_to_lsp_index(int gain)
963 else if (gain < 0x20)
964 return gain - 8 << 7;
966 return gain - 20 << 8;
969 static inline int cng_rand(int *state, int base)
971 *state = (*state * 521 + 259) & 0xFFFF;
972 return (*state & 0x7FFF) * base >> 15;
975 static int estimate_sid_gain(G723_1_Context *p)
977 int i, shift, seg, seg2, t, val, val_add, x, y;
979 shift = 16 - p->cur_gain * 2;
981 t = p->sid_gain << shift;
983 t = p->sid_gain >> -shift;
984 x = t * cng_filt[0] >> 16;
986 if (x >= cng_bseg[2])
989 if (x >= cng_bseg[1]) {
994 seg = (x >= cng_bseg[0]);
996 seg2 = FFMIN(seg, 3);
1000 for (i = 0; i < shift; i++) {
1001 t = seg * 32 + (val << seg2);
1010 t = seg * 32 + (val << seg2);
1013 t = seg * 32 + (val + 1 << seg2);
1015 val = (seg2 - 1 << 4) + val;
1019 t = seg * 32 + (val - 1 << seg2);
1021 val = (seg2 - 1 << 4) + val;
1029 static void generate_noise(G723_1_Context *p)
1033 int signs[SUBFRAMES / 2 * 11], pos[SUBFRAMES / 2 * 11];
1034 int tmp[SUBFRAME_LEN * 2];
1035 int16_t *vector_ptr;
1037 int b0, c, delta, x, shift;
1039 p->pitch_lag[0] = cng_rand(&p->cng_random_seed, 21) + 123;
1040 p->pitch_lag[1] = cng_rand(&p->cng_random_seed, 19) + 123;
1042 for (i = 0; i < SUBFRAMES; i++) {
1043 p->subframe[i].ad_cb_gain = cng_rand(&p->cng_random_seed, 50) + 1;
1044 p->subframe[i].ad_cb_lag = cng_adaptive_cb_lag[i];
1047 for (i = 0; i < SUBFRAMES / 2; i++) {
1048 t = cng_rand(&p->cng_random_seed, 1 << 13);
1050 off[i * 2 + 1] = ((t >> 1) & 1) + SUBFRAME_LEN;
1052 for (j = 0; j < 11; j++) {
1053 signs[i * 11 + j] = (t & 1) * 2 - 1 << 14;
1059 for (i = 0; i < SUBFRAMES; i++) {
1060 for (j = 0; j < SUBFRAME_LEN / 2; j++)
1062 t = SUBFRAME_LEN / 2;
1063 for (j = 0; j < pulses[i]; j++, idx++) {
1064 int idx2 = cng_rand(&p->cng_random_seed, t);
1066 pos[idx] = tmp[idx2] * 2 + off[i];
1067 tmp[idx2] = tmp[--t];
1071 vector_ptr = p->audio + LPC_ORDER;
1072 memcpy(vector_ptr, p->prev_excitation,
1073 PITCH_MAX * sizeof(*p->excitation));
1074 for (i = 0; i < SUBFRAMES; i += 2) {
1075 gen_acb_excitation(vector_ptr, vector_ptr,
1076 p->pitch_lag[i >> 1], &p->subframe[i],
1078 gen_acb_excitation(vector_ptr + SUBFRAME_LEN,
1079 vector_ptr + SUBFRAME_LEN,
1080 p->pitch_lag[i >> 1], &p->subframe[i + 1],
1084 for (j = 0; j < SUBFRAME_LEN * 2; j++)
1085 t |= FFABS(vector_ptr[j]);
1086 t = FFMIN(t, 0x7FFF);
1090 shift = -10 + av_log2(t);
1096 for (j = 0; j < SUBFRAME_LEN * 2; j++) {
1097 t = vector_ptr[j] << -shift;
1102 for (j = 0; j < SUBFRAME_LEN * 2; j++) {
1103 t = vector_ptr[j] >> shift;
1110 for (j = 0; j < 11; j++)
1111 b0 += tmp[pos[(i / 2) * 11 + j]] * signs[(i / 2) * 11 + j];
1112 b0 = b0 * 2 * 2979LL + (1 << 29) >> 30; // approximated division by 11
1114 c = p->cur_gain * (p->cur_gain * SUBFRAME_LEN >> 5);
1115 if (shift * 2 + 3 >= 0)
1116 c >>= shift * 2 + 3;
1118 c <<= -(shift * 2 + 3);
1119 c = (av_clipl_int32(sum << 1) - c) * 2979LL >> 15;
1121 delta = b0 * b0 * 2 - c;
1125 delta = square_root(delta);
1128 if (FFABS(t) < FFABS(x))
1136 x = av_clip(x, -10000, 10000);
1138 for (j = 0; j < 11; j++) {
1139 idx = (i / 2) * 11 + j;
1140 vector_ptr[pos[idx]] = av_clip_int16(vector_ptr[pos[idx]] +
1141 (x * signs[idx] >> 15));
1144 /* copy decoded data to serve as a history for the next decoded subframes */
1145 memcpy(vector_ptr + PITCH_MAX, vector_ptr,
1146 sizeof(*vector_ptr) * SUBFRAME_LEN * 2);
1147 vector_ptr += SUBFRAME_LEN * 2;
1149 /* Save the excitation for the next frame */
1150 memcpy(p->prev_excitation, p->audio + LPC_ORDER + FRAME_LEN,
1151 PITCH_MAX * sizeof(*p->excitation));
1154 static int g723_1_decode_frame(AVCodecContext *avctx, void *data,
1155 int *got_frame_ptr, AVPacket *avpkt)
1157 G723_1_Context *p = avctx->priv_data;
1158 const uint8_t *buf = avpkt->data;
1159 int buf_size = avpkt->size;
1160 int dec_mode = buf[0] & 3;
1162 PPFParam ppf[SUBFRAMES];
1163 int16_t cur_lsp[LPC_ORDER];
1164 int16_t lpc[SUBFRAMES * LPC_ORDER];
1165 int16_t acb_vector[SUBFRAME_LEN];
1167 int bad_frame = 0, i, j, ret;
1168 int16_t *audio = p->audio;
1170 if (buf_size < frame_size[dec_mode]) {
1172 av_log(avctx, AV_LOG_WARNING,
1173 "Expected %d bytes, got %d - skipping packet\n",
1174 frame_size[dec_mode], buf_size);
1179 if (unpack_bitstream(p, buf, buf_size) < 0) {
1181 if (p->past_frame_type == ACTIVE_FRAME)
1182 p->cur_frame_type = ACTIVE_FRAME;
1184 p->cur_frame_type = UNTRANSMITTED_FRAME;
1187 p->frame.nb_samples = FRAME_LEN;
1188 if ((ret = avctx->get_buffer(avctx, &p->frame)) < 0) {
1189 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1193 out = (int16_t *)p->frame.data[0];
1195 if (p->cur_frame_type == ACTIVE_FRAME) {
1197 p->erased_frames = 0;
1198 else if (p->erased_frames != 3)
1201 inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, bad_frame);
1202 lsp_interpolate(lpc, cur_lsp, p->prev_lsp);
1204 /* Save the lsp_vector for the next frame */
1205 memcpy(p->prev_lsp, cur_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
1207 /* Generate the excitation for the frame */
1208 memcpy(p->excitation, p->prev_excitation,
1209 PITCH_MAX * sizeof(*p->excitation));
1210 if (!p->erased_frames) {
1211 int16_t *vector_ptr = p->excitation + PITCH_MAX;
1213 /* Update interpolation gain memory */
1214 p->interp_gain = fixed_cb_gain[(p->subframe[2].amp_index +
1215 p->subframe[3].amp_index) >> 1];
1216 for (i = 0; i < SUBFRAMES; i++) {
1217 gen_fcb_excitation(vector_ptr, &p->subframe[i], p->cur_rate,
1218 p->pitch_lag[i >> 1], i);
1219 gen_acb_excitation(acb_vector, &p->excitation[SUBFRAME_LEN * i],
1220 p->pitch_lag[i >> 1], &p->subframe[i],
1222 /* Get the total excitation */
1223 for (j = 0; j < SUBFRAME_LEN; j++) {
1224 int v = av_clip_int16(vector_ptr[j] << 1);
1225 vector_ptr[j] = av_clip_int16(v + acb_vector[j]);
1227 vector_ptr += SUBFRAME_LEN;
1230 vector_ptr = p->excitation + PITCH_MAX;
1232 p->interp_index = comp_interp_index(p, p->pitch_lag[1],
1233 &p->sid_gain, &p->cur_gain);
1235 /* Peform pitch postfiltering */
1236 if (p->postfilter) {
1238 for (j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1239 comp_ppf_coeff(p, i, p->pitch_lag[j >> 1],
1240 ppf + j, p->cur_rate);
1242 for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1243 ff_acelp_weighted_vector_sum(p->audio + LPC_ORDER + i,
1245 vector_ptr + i + ppf[j].index,
1248 1 << 14, 15, SUBFRAME_LEN);
1250 audio = vector_ptr - LPC_ORDER;
1253 /* Save the excitation for the next frame */
1254 memcpy(p->prev_excitation, p->excitation + FRAME_LEN,
1255 PITCH_MAX * sizeof(*p->excitation));
1257 p->interp_gain = (p->interp_gain * 3 + 2) >> 2;
1258 if (p->erased_frames == 3) {
1260 memset(p->excitation, 0,
1261 (FRAME_LEN + PITCH_MAX) * sizeof(*p->excitation));
1262 memset(p->prev_excitation, 0,
1263 PITCH_MAX * sizeof(*p->excitation));
1264 memset(p->frame.data[0], 0,
1265 (FRAME_LEN + LPC_ORDER) * sizeof(int16_t));
1267 int16_t *buf = p->audio + LPC_ORDER;
1269 /* Regenerate frame */
1270 residual_interp(p->excitation, buf, p->interp_index,
1271 p->interp_gain, &p->random_seed);
1273 /* Save the excitation for the next frame */
1274 memcpy(p->prev_excitation, buf + (FRAME_LEN - PITCH_MAX),
1275 PITCH_MAX * sizeof(*p->excitation));
1278 p->cng_random_seed = CNG_RANDOM_SEED;
1280 if (p->cur_frame_type == SID_FRAME) {
1281 p->sid_gain = sid_gain_to_lsp_index(p->subframe[0].amp_index);
1282 inverse_quant(p->sid_lsp, p->prev_lsp, p->lsp_index, 0);
1283 } else if (p->past_frame_type == ACTIVE_FRAME) {
1284 p->sid_gain = estimate_sid_gain(p);
1287 if (p->past_frame_type == ACTIVE_FRAME)
1288 p->cur_gain = p->sid_gain;
1290 p->cur_gain = (p->cur_gain * 7 + p->sid_gain) >> 3;
1292 lsp_interpolate(lpc, p->sid_lsp, p->prev_lsp);
1293 /* Save the lsp_vector for the next frame */
1294 memcpy(p->prev_lsp, p->sid_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
1297 p->past_frame_type = p->cur_frame_type;
1299 memcpy(p->audio, p->synth_mem, LPC_ORDER * sizeof(*p->audio));
1300 for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1301 ff_celp_lp_synthesis_filter(p->audio + i, &lpc[j * LPC_ORDER],
1302 audio + i, SUBFRAME_LEN, LPC_ORDER,
1304 memcpy(p->synth_mem, p->audio + FRAME_LEN, LPC_ORDER * sizeof(*p->audio));
1306 if (p->postfilter) {
1307 formant_postfilter(p, lpc, p->audio, out);
1308 } else { // if output is not postfiltered it should be scaled by 2
1309 for (i = 0; i < FRAME_LEN; i++)
1310 out[i] = av_clip_int16(p->audio[LPC_ORDER + i] << 1);
1314 *(AVFrame *)data = p->frame;
1316 return frame_size[dec_mode];
1319 #define OFFSET(x) offsetof(G723_1_Context, x)
1320 #define AD AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1322 static const AVOption options[] = {
1323 { "postfilter", "postfilter on/off", OFFSET(postfilter), AV_OPT_TYPE_INT,
1324 { .i64 = 1 }, 0, 1, AD },
1329 static const AVClass g723_1dec_class = {
1330 .class_name = "G.723.1 decoder",
1331 .item_name = av_default_item_name,
1333 .version = LIBAVUTIL_VERSION_INT,
1336 AVCodec ff_g723_1_decoder = {
1338 .type = AVMEDIA_TYPE_AUDIO,
1339 .id = AV_CODEC_ID_G723_1,
1340 .priv_data_size = sizeof(G723_1_Context),
1341 .init = g723_1_decode_init,
1342 .decode = g723_1_decode_frame,
1343 .long_name = NULL_IF_CONFIG_SMALL("G.723.1"),
1344 .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
1345 .priv_class = &g723_1dec_class,
1348 #if CONFIG_G723_1_ENCODER
1349 #define BITSTREAM_WRITER_LE
1350 #include "put_bits.h"
1352 static av_cold int g723_1_encode_init(AVCodecContext *avctx)
1354 G723_1_Context *p = avctx->priv_data;
1356 if (avctx->sample_rate != 8000) {
1357 av_log(avctx, AV_LOG_ERROR, "Only 8000Hz sample rate supported\n");
1361 if (avctx->channels != 1) {
1362 av_log(avctx, AV_LOG_ERROR, "Only mono supported\n");
1363 return AVERROR(EINVAL);
1366 if (avctx->bit_rate == 6300) {
1367 p->cur_rate = RATE_6300;
1368 } else if (avctx->bit_rate == 5300) {
1369 av_log(avctx, AV_LOG_ERROR, "Bitrate not supported yet, use 6.3k\n");
1370 return AVERROR_PATCHWELCOME;
1372 av_log(avctx, AV_LOG_ERROR,
1373 "Bitrate not supported, use 6.3k\n");
1374 return AVERROR(EINVAL);
1376 avctx->frame_size = 240;
1377 memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(int16_t));
1383 * Remove DC component from the input signal.
1385 * @param buf input signal
1386 * @param fir zero memory
1387 * @param iir pole memory
1389 static void highpass_filter(int16_t *buf, int16_t *fir, int *iir)
1392 for (i = 0; i < FRAME_LEN; i++) {
1393 *iir = (buf[i] << 15) + ((-*fir) << 15) + MULL2(*iir, 0x7f00);
1395 buf[i] = av_clipl_int32((int64_t)*iir + (1 << 15)) >> 16;
1400 * Estimate autocorrelation of the input vector.
1402 * @param buf input buffer
1403 * @param autocorr autocorrelation coefficients vector
1405 static void comp_autocorr(int16_t *buf, int16_t *autocorr)
1408 int16_t vector[LPC_FRAME];
1410 scale_vector(vector, buf, LPC_FRAME);
1412 /* Apply the Hamming window */
1413 for (i = 0; i < LPC_FRAME; i++)
1414 vector[i] = (vector[i] * hamming_window[i] + (1 << 14)) >> 15;
1416 /* Compute the first autocorrelation coefficient */
1417 temp = ff_dot_product(vector, vector, LPC_FRAME);
1419 /* Apply a white noise correlation factor of (1025/1024) */
1423 scale = normalize_bits_int32(temp);
1424 autocorr[0] = av_clipl_int32((int64_t)(temp << scale) +
1427 /* Compute the remaining coefficients */
1429 memset(autocorr + 1, 0, LPC_ORDER * sizeof(int16_t));
1431 for (i = 1; i <= LPC_ORDER; i++) {
1432 temp = ff_dot_product(vector, vector + i, LPC_FRAME - i);
1433 temp = MULL2((temp << scale), binomial_window[i - 1]);
1434 autocorr[i] = av_clipl_int32((int64_t)temp + (1 << 15)) >> 16;
1440 * Use Levinson-Durbin recursion to compute LPC coefficients from
1441 * autocorrelation values.
1443 * @param lpc LPC coefficients vector
1444 * @param autocorr autocorrelation coefficients vector
1445 * @param error prediction error
1447 static void levinson_durbin(int16_t *lpc, int16_t *autocorr, int16_t error)
1449 int16_t vector[LPC_ORDER];
1450 int16_t partial_corr;
1453 memset(lpc, 0, LPC_ORDER * sizeof(int16_t));
1455 for (i = 0; i < LPC_ORDER; i++) {
1456 /* Compute the partial correlation coefficient */
1458 for (j = 0; j < i; j++)
1459 temp -= lpc[j] * autocorr[i - j - 1];
1460 temp = ((autocorr[i] << 13) + temp) << 3;
1462 if (FFABS(temp) >= (error << 16))
1465 partial_corr = temp / (error << 1);
1467 lpc[i] = av_clipl_int32((int64_t)(partial_corr << 14) +
1470 /* Update the prediction error */
1471 temp = MULL2(temp, partial_corr);
1472 error = av_clipl_int32((int64_t)(error << 16) - temp +
1475 memcpy(vector, lpc, i * sizeof(int16_t));
1476 for (j = 0; j < i; j++) {
1477 temp = partial_corr * vector[i - j - 1] << 1;
1478 lpc[j] = av_clipl_int32((int64_t)(lpc[j] << 16) - temp +
1485 * Calculate LPC coefficients for the current frame.
1487 * @param buf current frame
1488 * @param prev_data 2 trailing subframes of the previous frame
1489 * @param lpc LPC coefficients vector
1491 static void comp_lpc_coeff(int16_t *buf, int16_t *lpc)
1493 int16_t autocorr[(LPC_ORDER + 1) * SUBFRAMES];
1494 int16_t *autocorr_ptr = autocorr;
1495 int16_t *lpc_ptr = lpc;
1498 for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
1499 comp_autocorr(buf + i, autocorr_ptr);
1500 levinson_durbin(lpc_ptr, autocorr_ptr + 1, autocorr_ptr[0]);
1502 lpc_ptr += LPC_ORDER;
1503 autocorr_ptr += LPC_ORDER + 1;
1507 static void lpc2lsp(int16_t *lpc, int16_t *prev_lsp, int16_t *lsp)
1509 int f[LPC_ORDER + 2]; ///< coefficients of the sum and difference
1510 ///< polynomials (F1, F2) ordered as
1511 ///< f1[0], f2[0], ...., f1[5], f2[5]
1513 int max, shift, cur_val, prev_val, count, p;
1517 /* Initialize f1[0] and f2[0] to 1 in Q25 */
1518 for (i = 0; i < LPC_ORDER; i++)
1519 lsp[i] = (lpc[i] * bandwidth_expand[i] + (1 << 14)) >> 15;
1521 /* Apply bandwidth expansion on the LPC coefficients */
1522 f[0] = f[1] = 1 << 25;
1524 /* Compute the remaining coefficients */
1525 for (i = 0; i < LPC_ORDER / 2; i++) {
1527 f[2 * i + 2] = -f[2 * i] - ((lsp[i] + lsp[LPC_ORDER - 1 - i]) << 12);
1529 f[2 * i + 3] = f[2 * i + 1] - ((lsp[i] - lsp[LPC_ORDER - 1 - i]) << 12);
1532 /* Divide f1[5] and f2[5] by 2 for use in polynomial evaluation */
1534 f[LPC_ORDER + 1] >>= 1;
1536 /* Normalize and shorten */
1538 for (i = 1; i < LPC_ORDER + 2; i++)
1539 max = FFMAX(max, FFABS(f[i]));
1541 shift = normalize_bits_int32(max);
1543 for (i = 0; i < LPC_ORDER + 2; i++)
1544 f[i] = av_clipl_int32((int64_t)(f[i] << shift) + (1 << 15)) >> 16;
1547 * Evaluate F1 and F2 at uniform intervals of pi/256 along the
1548 * unit circle and check for zero crossings.
1552 for (i = 0; i <= LPC_ORDER / 2; i++)
1553 temp += f[2 * i] * cos_tab[0];
1554 prev_val = av_clipl_int32(temp << 1);
1556 for ( i = 1; i < COS_TBL_SIZE / 2; i++) {
1559 for (j = 0; j <= LPC_ORDER / 2; j++)
1560 temp += f[LPC_ORDER - 2 * j + p] * cos_tab[i * j % COS_TBL_SIZE];
1561 cur_val = av_clipl_int32(temp << 1);
1563 /* Check for sign change, indicating a zero crossing */
1564 if ((cur_val ^ prev_val) < 0) {
1565 int abs_cur = FFABS(cur_val);
1566 int abs_prev = FFABS(prev_val);
1567 int sum = abs_cur + abs_prev;
1569 shift = normalize_bits_int32(sum);
1571 abs_prev = abs_prev << shift >> 8;
1572 lsp[count++] = ((i - 1) << 7) + (abs_prev >> 1) / (sum >> 16);
1574 if (count == LPC_ORDER)
1577 /* Switch between sum and difference polynomials */
1582 for (j = 0; j <= LPC_ORDER / 2; j++){
1583 temp += f[LPC_ORDER - 2 * j + p] *
1584 cos_tab[i * j % COS_TBL_SIZE];
1586 cur_val = av_clipl_int32(temp<<1);
1591 if (count != LPC_ORDER)
1592 memcpy(lsp, prev_lsp, LPC_ORDER * sizeof(int16_t));
1596 * Quantize the current LSP subvector.
1598 * @param num band number
1599 * @param offset offset of the current subvector in an LPC_ORDER vector
1600 * @param size size of the current subvector
1602 #define get_index(num, offset, size) \
1604 int error, max = -1;\
1607 for (i = 0; i < LSP_CB_SIZE; i++) {\
1608 for (j = 0; j < size; j++){\
1609 temp[j] = (weight[j + (offset)] * lsp_band##num[i][j] +\
1612 error = dot_product(lsp + (offset), temp, size) << 1;\
1613 error -= dot_product(lsp_band##num[i], temp, size);\
1616 lsp_index[num] = i;\
1622 * Vector quantize the LSP frequencies.
1624 * @param lsp the current lsp vector
1625 * @param prev_lsp the previous lsp vector
1627 static void lsp_quantize(uint8_t *lsp_index, int16_t *lsp, int16_t *prev_lsp)
1629 int16_t weight[LPC_ORDER];
1633 /* Calculate the VQ weighting vector */
1634 weight[0] = (1 << 20) / (lsp[1] - lsp[0]);
1635 weight[LPC_ORDER - 1] = (1 << 20) /
1636 (lsp[LPC_ORDER - 1] - lsp[LPC_ORDER - 2]);
1638 for (i = 1; i < LPC_ORDER - 1; i++) {
1639 min = FFMIN(lsp[i] - lsp[i - 1], lsp[i + 1] - lsp[i]);
1641 weight[i] = (1 << 20) / min;
1643 weight[i] = INT16_MAX;
1648 for (i = 0; i < LPC_ORDER; i++)
1649 max = FFMAX(weight[i], max);
1651 shift = normalize_bits_int16(max);
1652 for (i = 0; i < LPC_ORDER; i++) {
1653 weight[i] <<= shift;
1656 /* Compute the VQ target vector */
1657 for (i = 0; i < LPC_ORDER; i++) {
1658 lsp[i] -= dc_lsp[i] +
1659 (((prev_lsp[i] - dc_lsp[i]) * 12288 + (1 << 14)) >> 15);
1668 * Apply the formant perceptual weighting filter.
1670 * @param flt_coef filter coefficients
1671 * @param unq_lpc unquantized lpc vector
1673 static void perceptual_filter(G723_1_Context *p, int16_t *flt_coef,
1674 int16_t *unq_lpc, int16_t *buf)
1676 int16_t vector[FRAME_LEN + LPC_ORDER];
1679 memcpy(buf, p->iir_mem, sizeof(int16_t) * LPC_ORDER);
1680 memcpy(vector, p->fir_mem, sizeof(int16_t) * LPC_ORDER);
1681 memcpy(vector + LPC_ORDER, buf + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
1683 for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
1684 for (k = 0; k < LPC_ORDER; k++) {
1685 flt_coef[k + 2 * l] = (unq_lpc[k + l] * percept_flt_tbl[0][k] +
1687 flt_coef[k + 2 * l + LPC_ORDER] = (unq_lpc[k + l] *
1688 percept_flt_tbl[1][k] +
1691 iir_filter(flt_coef + 2 * l, flt_coef + 2 * l + LPC_ORDER, vector + i,
1695 memcpy(p->iir_mem, buf + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
1696 memcpy(p->fir_mem, vector + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
1700 * Estimate the open loop pitch period.
1702 * @param buf perceptually weighted speech
1703 * @param start estimation is carried out from this position
1705 static int estimate_pitch(int16_t *buf, int start)
1708 int max_ccr = 0x4000;
1709 int max_eng = 0x7fff;
1710 int index = PITCH_MIN;
1711 int offset = start - PITCH_MIN + 1;
1713 int ccr, eng, orig_eng, ccr_eng, exp;
1718 orig_eng = ff_dot_product(buf + offset, buf + offset, HALF_FRAME_LEN);
1720 for (i = PITCH_MIN; i <= PITCH_MAX - 3; i++) {
1723 /* Update energy and compute correlation */
1724 orig_eng += buf[offset] * buf[offset] -
1725 buf[offset + HALF_FRAME_LEN] * buf[offset + HALF_FRAME_LEN];
1726 ccr = ff_dot_product(buf + start, buf + offset, HALF_FRAME_LEN);
1730 /* Split into mantissa and exponent to maintain precision */
1731 exp = normalize_bits_int32(ccr);
1732 ccr = av_clipl_int32((int64_t)(ccr << exp) + (1 << 15)) >> 16;
1735 temp = normalize_bits_int32(ccr);
1736 ccr = ccr << temp >> 16;
1739 temp = normalize_bits_int32(orig_eng);
1740 eng = av_clipl_int32((int64_t)(orig_eng << temp) + (1 << 15)) >> 16;
1750 if (exp + 1 < max_exp)
1753 /* Equalize exponents before comparison */
1754 if (exp + 1 == max_exp)
1755 temp = max_ccr >> 1;
1758 ccr_eng = ccr * max_eng;
1759 diff = ccr_eng - eng * temp;
1760 if (diff > 0 && (i - index < PITCH_MIN || diff > ccr_eng >> 2)) {
1772 * Compute harmonic noise filter parameters.
1774 * @param buf perceptually weighted speech
1775 * @param pitch_lag open loop pitch period
1776 * @param hf harmonic filter parameters
1778 static void comp_harmonic_coeff(int16_t *buf, int16_t pitch_lag, HFParam *hf)
1780 int ccr, eng, max_ccr, max_eng;
1785 for (i = 0, j = pitch_lag - 3; j <= pitch_lag + 3; i++, j++) {
1786 /* Compute residual energy */
1787 energy[i << 1] = ff_dot_product(buf - j, buf - j, SUBFRAME_LEN);
1788 /* Compute correlation */
1789 energy[(i << 1) + 1] = ff_dot_product(buf, buf - j, SUBFRAME_LEN);
1792 /* Compute target energy */
1793 energy[14] = ff_dot_product(buf, buf, SUBFRAME_LEN);
1797 for (i = 0; i < 15; i++)
1798 max = FFMAX(max, FFABS(energy[i]));
1800 exp = normalize_bits_int32(max);
1801 for (i = 0; i < 15; i++) {
1802 energy[i] = av_clipl_int32((int64_t)(energy[i] << exp) +
1811 for (i = 0; i <= 6; i++) {
1812 eng = energy[i << 1];
1813 ccr = energy[(i << 1) + 1];
1818 ccr = (ccr * ccr + (1 << 14)) >> 15;
1819 diff = ccr * max_eng - eng * max_ccr;
1827 if (hf->index == -1) {
1828 hf->index = pitch_lag;
1832 eng = energy[14] * max_eng;
1833 eng = (eng >> 2) + (eng >> 3);
1834 ccr = energy[(hf->index << 1) + 1] * energy[(hf->index << 1) + 1];
1836 eng = energy[(hf->index << 1) + 1];
1841 hf->gain = ((eng << 15) / max_eng * 0x2800 + (1 << 14)) >> 15;
1843 hf->index += pitch_lag - 3;
1847 * Apply the harmonic noise shaping filter.
1849 * @param hf filter parameters
1851 static void harmonic_filter(HFParam *hf, const int16_t *src, int16_t *dest)
1855 for (i = 0; i < SUBFRAME_LEN; i++) {
1856 int64_t temp = hf->gain * src[i - hf->index] << 1;
1857 dest[i] = av_clipl_int32((src[i] << 16) - temp + (1 << 15)) >> 16;
1861 static void harmonic_noise_sub(HFParam *hf, const int16_t *src, int16_t *dest)
1864 for (i = 0; i < SUBFRAME_LEN; i++) {
1865 int64_t temp = hf->gain * src[i - hf->index] << 1;
1866 dest[i] = av_clipl_int32(((dest[i] - src[i]) << 16) + temp +
1873 * Combined synthesis and formant perceptual weighting filer.
1875 * @param qnt_lpc quantized lpc coefficients
1876 * @param perf_lpc perceptual filter coefficients
1877 * @param perf_fir perceptual filter fir memory
1878 * @param perf_iir perceptual filter iir memory
1879 * @param scale the filter output will be scaled by 2^scale
1881 static void synth_percept_filter(int16_t *qnt_lpc, int16_t *perf_lpc,
1882 int16_t *perf_fir, int16_t *perf_iir,
1883 const int16_t *src, int16_t *dest, int scale)
1886 int16_t buf_16[SUBFRAME_LEN + LPC_ORDER];
1887 int64_t buf[SUBFRAME_LEN];
1889 int16_t *bptr_16 = buf_16 + LPC_ORDER;
1891 memcpy(buf_16, perf_fir, sizeof(int16_t) * LPC_ORDER);
1892 memcpy(dest - LPC_ORDER, perf_iir, sizeof(int16_t) * LPC_ORDER);
1894 for (i = 0; i < SUBFRAME_LEN; i++) {
1896 for (j = 1; j <= LPC_ORDER; j++)
1897 temp -= qnt_lpc[j - 1] * bptr_16[i - j];
1899 buf[i] = (src[i] << 15) + (temp << 3);
1900 bptr_16[i] = av_clipl_int32(buf[i] + (1 << 15)) >> 16;
1903 for (i = 0; i < SUBFRAME_LEN; i++) {
1904 int64_t fir = 0, iir = 0;
1905 for (j = 1; j <= LPC_ORDER; j++) {
1906 fir -= perf_lpc[j - 1] * bptr_16[i - j];
1907 iir += perf_lpc[j + LPC_ORDER - 1] * dest[i - j];
1909 dest[i] = av_clipl_int32(((buf[i] + (fir << 3)) << scale) + (iir << 3) +
1912 memcpy(perf_fir, buf_16 + SUBFRAME_LEN, sizeof(int16_t) * LPC_ORDER);
1913 memcpy(perf_iir, dest + SUBFRAME_LEN - LPC_ORDER,
1914 sizeof(int16_t) * LPC_ORDER);
1918 * Compute the adaptive codebook contribution.
1920 * @param buf input signal
1921 * @param index the current subframe index
1923 static void acb_search(G723_1_Context *p, int16_t *residual,
1924 int16_t *impulse_resp, const int16_t *buf,
1928 int16_t flt_buf[PITCH_ORDER][SUBFRAME_LEN];
1930 const int16_t *cb_tbl = adaptive_cb_gain85;
1932 int ccr_buf[PITCH_ORDER * SUBFRAMES << 2];
1934 int pitch_lag = p->pitch_lag[index >> 1];
1937 int odd_frame = index & 1;
1938 int iter = 3 + odd_frame;
1942 int i, j, k, l, max;
1946 if (pitch_lag == PITCH_MIN)
1949 pitch_lag = FFMIN(pitch_lag, PITCH_MAX - 5);
1952 for (i = 0; i < iter; i++) {
1953 get_residual(residual, p->prev_excitation, pitch_lag + i - 1);
1955 for (j = 0; j < SUBFRAME_LEN; j++) {
1957 for (k = 0; k <= j; k++)
1958 temp += residual[PITCH_ORDER - 1 + k] * impulse_resp[j - k];
1959 flt_buf[PITCH_ORDER - 1][j] = av_clipl_int32((temp << 1) +
1963 for (j = PITCH_ORDER - 2; j >= 0; j--) {
1964 flt_buf[j][0] = ((residual[j] << 13) + (1 << 14)) >> 15;
1965 for (k = 1; k < SUBFRAME_LEN; k++) {
1966 temp = (flt_buf[j + 1][k - 1] << 15) +
1967 residual[j] * impulse_resp[k];
1968 flt_buf[j][k] = av_clipl_int32((temp << 1) + (1 << 15)) >> 16;
1972 /* Compute crosscorrelation with the signal */
1973 for (j = 0; j < PITCH_ORDER; j++) {
1974 temp = ff_dot_product(buf, flt_buf[j], SUBFRAME_LEN);
1975 ccr_buf[count++] = av_clipl_int32(temp << 1);
1978 /* Compute energies */
1979 for (j = 0; j < PITCH_ORDER; j++) {
1980 ccr_buf[count++] = dot_product(flt_buf[j], flt_buf[j],
1984 for (j = 1; j < PITCH_ORDER; j++) {
1985 for (k = 0; k < j; k++) {
1986 temp = ff_dot_product(flt_buf[j], flt_buf[k], SUBFRAME_LEN);
1987 ccr_buf[count++] = av_clipl_int32(temp<<2);
1992 /* Normalize and shorten */
1994 for (i = 0; i < 20 * iter; i++)
1995 max = FFMAX(max, FFABS(ccr_buf[i]));
1997 temp = normalize_bits_int32(max);
1999 for (i = 0; i < 20 * iter; i++){
2000 ccr_buf[i] = av_clipl_int32((int64_t)(ccr_buf[i] << temp) +
2005 for (i = 0; i < iter; i++) {
2006 /* Select quantization table */
2007 if (!odd_frame && pitch_lag + i - 1 >= SUBFRAME_LEN - 2 ||
2008 odd_frame && pitch_lag >= SUBFRAME_LEN - 2) {
2009 cb_tbl = adaptive_cb_gain170;
2013 for (j = 0, k = 0; j < tbl_size; j++, k += 20) {
2015 for (l = 0; l < 20; l++)
2016 temp += ccr_buf[20 * i + l] * cb_tbl[k + l];
2017 temp = av_clipl_int32(temp);
2028 pitch_lag += acb_lag - 1;
2032 p->pitch_lag[index >> 1] = pitch_lag;
2033 p->subframe[index].ad_cb_lag = acb_lag;
2034 p->subframe[index].ad_cb_gain = acb_gain;
2038 * Subtract the adaptive codebook contribution from the input
2039 * to obtain the residual.
2041 * @param buf target vector
2043 static void sub_acb_contrib(const int16_t *residual, const int16_t *impulse_resp,
2047 /* Subtract adaptive CB contribution to obtain the residual */
2048 for (i = 0; i < SUBFRAME_LEN; i++) {
2049 int64_t temp = buf[i] << 14;
2050 for (j = 0; j <= i; j++)
2051 temp -= residual[j] * impulse_resp[i - j];
2053 buf[i] = av_clipl_int32((temp << 2) + (1 << 15)) >> 16;
2058 * Quantize the residual signal using the fixed codebook (MP-MLQ).
2060 * @param optim optimized fixed codebook parameters
2061 * @param buf excitation vector
2063 static void get_fcb_param(FCBParam *optim, int16_t *impulse_resp,
2064 int16_t *buf, int pulse_cnt, int pitch_lag)
2067 int16_t impulse_r[SUBFRAME_LEN];
2068 int16_t temp_corr[SUBFRAME_LEN];
2069 int16_t impulse_corr[SUBFRAME_LEN];
2071 int ccr1[SUBFRAME_LEN];
2072 int ccr2[SUBFRAME_LEN];
2073 int amp, err, max, max_amp_index, min, scale, i, j, k, l;
2077 /* Update impulse response */
2078 memcpy(impulse_r, impulse_resp, sizeof(int16_t) * SUBFRAME_LEN);
2079 param.dirac_train = 0;
2080 if (pitch_lag < SUBFRAME_LEN - 2) {
2081 param.dirac_train = 1;
2082 gen_dirac_train(impulse_r, pitch_lag);
2085 for (i = 0; i < SUBFRAME_LEN; i++)
2086 temp_corr[i] = impulse_r[i] >> 1;
2088 /* Compute impulse response autocorrelation */
2089 temp = dot_product(temp_corr, temp_corr, SUBFRAME_LEN);
2091 scale = normalize_bits_int32(temp);
2092 impulse_corr[0] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
2094 for (i = 1; i < SUBFRAME_LEN; i++) {
2095 temp = dot_product(temp_corr + i, temp_corr, SUBFRAME_LEN - i);
2096 impulse_corr[i] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
2099 /* Compute crosscorrelation of impulse response with residual signal */
2101 for (i = 0; i < SUBFRAME_LEN; i++){
2102 temp = dot_product(buf + i, impulse_r, SUBFRAME_LEN - i);
2104 ccr1[i] = temp >> -scale;
2106 ccr1[i] = av_clipl_int32(temp << scale);
2110 for (i = 0; i < GRID_SIZE; i++) {
2111 /* Maximize the crosscorrelation */
2113 for (j = i; j < SUBFRAME_LEN; j += GRID_SIZE) {
2114 temp = FFABS(ccr1[j]);
2117 param.pulse_pos[0] = j;
2121 /* Quantize the gain (max crosscorrelation/impulse_corr[0]) */
2124 max_amp_index = GAIN_LEVELS - 2;
2125 for (j = max_amp_index; j >= 2; j--) {
2126 temp = av_clipl_int32((int64_t)fixed_cb_gain[j] *
2127 impulse_corr[0] << 1);
2128 temp = FFABS(temp - amp);
2136 /* Select additional gain values */
2137 for (j = 1; j < 5; j++) {
2138 for (k = i; k < SUBFRAME_LEN; k += GRID_SIZE) {
2142 param.amp_index = max_amp_index + j - 2;
2143 amp = fixed_cb_gain[param.amp_index];
2145 param.pulse_sign[0] = (ccr2[param.pulse_pos[0]] < 0) ? -amp : amp;
2146 temp_corr[param.pulse_pos[0]] = 1;
2148 for (k = 1; k < pulse_cnt; k++) {
2150 for (l = i; l < SUBFRAME_LEN; l += GRID_SIZE) {
2153 temp = impulse_corr[FFABS(l - param.pulse_pos[k - 1])];
2154 temp = av_clipl_int32((int64_t)temp *
2155 param.pulse_sign[k - 1] << 1);
2157 temp = FFABS(ccr2[l]);
2160 param.pulse_pos[k] = l;
2164 param.pulse_sign[k] = (ccr2[param.pulse_pos[k]] < 0) ?
2166 temp_corr[param.pulse_pos[k]] = 1;
2169 /* Create the error vector */
2170 memset(temp_corr, 0, sizeof(int16_t) * SUBFRAME_LEN);
2172 for (k = 0; k < pulse_cnt; k++)
2173 temp_corr[param.pulse_pos[k]] = param.pulse_sign[k];
2175 for (k = SUBFRAME_LEN - 1; k >= 0; k--) {
2177 for (l = 0; l <= k; l++) {
2178 int prod = av_clipl_int32((int64_t)temp_corr[l] *
2179 impulse_r[k - l] << 1);
2180 temp = av_clipl_int32(temp + prod);
2182 temp_corr[k] = temp << 2 >> 16;
2185 /* Compute square of error */
2187 for (k = 0; k < SUBFRAME_LEN; k++) {
2189 prod = av_clipl_int32((int64_t)buf[k] * temp_corr[k] << 1);
2190 err = av_clipl_int32(err - prod);
2191 prod = av_clipl_int32((int64_t)temp_corr[k] * temp_corr[k]);
2192 err = av_clipl_int32(err + prod);
2196 if (err < optim->min_err) {
2197 optim->min_err = err;
2198 optim->grid_index = i;
2199 optim->amp_index = param.amp_index;
2200 optim->dirac_train = param.dirac_train;
2202 for (k = 0; k < pulse_cnt; k++) {
2203 optim->pulse_sign[k] = param.pulse_sign[k];
2204 optim->pulse_pos[k] = param.pulse_pos[k];
2212 * Encode the pulse position and gain of the current subframe.
2214 * @param optim optimized fixed CB parameters
2215 * @param buf excitation vector
2217 static void pack_fcb_param(G723_1_Subframe *subfrm, FCBParam *optim,
2218 int16_t *buf, int pulse_cnt)
2222 j = PULSE_MAX - pulse_cnt;
2224 subfrm->pulse_sign = 0;
2225 subfrm->pulse_pos = 0;
2227 for (i = 0; i < SUBFRAME_LEN >> 1; i++) {
2228 int val = buf[optim->grid_index + (i << 1)];
2230 subfrm->pulse_pos += combinatorial_table[j][i];
2232 subfrm->pulse_sign <<= 1;
2233 if (val < 0) subfrm->pulse_sign++;
2236 if (j == PULSE_MAX) break;
2239 subfrm->amp_index = optim->amp_index;
2240 subfrm->grid_index = optim->grid_index;
2241 subfrm->dirac_train = optim->dirac_train;
2245 * Compute the fixed codebook excitation.
2247 * @param buf target vector
2248 * @param impulse_resp impulse response of the combined filter
2250 static void fcb_search(G723_1_Context *p, int16_t *impulse_resp,
2251 int16_t *buf, int index)
2254 int pulse_cnt = pulses[index];
2257 optim.min_err = 1 << 30;
2258 get_fcb_param(&optim, impulse_resp, buf, pulse_cnt, SUBFRAME_LEN);
2260 if (p->pitch_lag[index >> 1] < SUBFRAME_LEN - 2) {
2261 get_fcb_param(&optim, impulse_resp, buf, pulse_cnt,
2262 p->pitch_lag[index >> 1]);
2265 /* Reconstruct the excitation */
2266 memset(buf, 0, sizeof(int16_t) * SUBFRAME_LEN);
2267 for (i = 0; i < pulse_cnt; i++)
2268 buf[optim.pulse_pos[i]] = optim.pulse_sign[i];
2270 pack_fcb_param(&p->subframe[index], &optim, buf, pulse_cnt);
2272 if (optim.dirac_train)
2273 gen_dirac_train(buf, p->pitch_lag[index >> 1]);
2277 * Pack the frame parameters into output bitstream.
2279 * @param frame output buffer
2280 * @param size size of the buffer
2282 static int pack_bitstream(G723_1_Context *p, unsigned char *frame, int size)
2285 int info_bits, i, temp;
2287 init_put_bits(&pb, frame, size);
2289 if (p->cur_rate == RATE_6300) {
2291 put_bits(&pb, 2, info_bits);
2294 put_bits(&pb, 8, p->lsp_index[2]);
2295 put_bits(&pb, 8, p->lsp_index[1]);
2296 put_bits(&pb, 8, p->lsp_index[0]);
2298 put_bits(&pb, 7, p->pitch_lag[0] - PITCH_MIN);
2299 put_bits(&pb, 2, p->subframe[1].ad_cb_lag);
2300 put_bits(&pb, 7, p->pitch_lag[1] - PITCH_MIN);
2301 put_bits(&pb, 2, p->subframe[3].ad_cb_lag);
2303 /* Write 12 bit combined gain */
2304 for (i = 0; i < SUBFRAMES; i++) {
2305 temp = p->subframe[i].ad_cb_gain * GAIN_LEVELS +
2306 p->subframe[i].amp_index;
2307 if (p->cur_rate == RATE_6300)
2308 temp += p->subframe[i].dirac_train << 11;
2309 put_bits(&pb, 12, temp);
2312 put_bits(&pb, 1, p->subframe[0].grid_index);
2313 put_bits(&pb, 1, p->subframe[1].grid_index);
2314 put_bits(&pb, 1, p->subframe[2].grid_index);
2315 put_bits(&pb, 1, p->subframe[3].grid_index);
2317 if (p->cur_rate == RATE_6300) {
2318 skip_put_bits(&pb, 1); /* reserved bit */
2320 /* Write 13 bit combined position index */
2321 temp = (p->subframe[0].pulse_pos >> 16) * 810 +
2322 (p->subframe[1].pulse_pos >> 14) * 90 +
2323 (p->subframe[2].pulse_pos >> 16) * 9 +
2324 (p->subframe[3].pulse_pos >> 14);
2325 put_bits(&pb, 13, temp);
2327 put_bits(&pb, 16, p->subframe[0].pulse_pos & 0xffff);
2328 put_bits(&pb, 14, p->subframe[1].pulse_pos & 0x3fff);
2329 put_bits(&pb, 16, p->subframe[2].pulse_pos & 0xffff);
2330 put_bits(&pb, 14, p->subframe[3].pulse_pos & 0x3fff);
2332 put_bits(&pb, 6, p->subframe[0].pulse_sign);
2333 put_bits(&pb, 5, p->subframe[1].pulse_sign);
2334 put_bits(&pb, 6, p->subframe[2].pulse_sign);
2335 put_bits(&pb, 5, p->subframe[3].pulse_sign);
2338 flush_put_bits(&pb);
2339 return frame_size[info_bits];
2342 static int g723_1_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
2343 const AVFrame *frame, int *got_packet_ptr)
2345 G723_1_Context *p = avctx->priv_data;
2346 int16_t unq_lpc[LPC_ORDER * SUBFRAMES];
2347 int16_t qnt_lpc[LPC_ORDER * SUBFRAMES];
2348 int16_t cur_lsp[LPC_ORDER];
2349 int16_t weighted_lpc[LPC_ORDER * SUBFRAMES << 1];
2350 int16_t vector[FRAME_LEN + PITCH_MAX];
2352 int16_t *in = (const int16_t *)frame->data[0];
2357 highpass_filter(in, &p->hpf_fir_mem, &p->hpf_iir_mem);
2359 memcpy(vector, p->prev_data, HALF_FRAME_LEN * sizeof(int16_t));
2360 memcpy(vector + HALF_FRAME_LEN, in, FRAME_LEN * sizeof(int16_t));
2362 comp_lpc_coeff(vector, unq_lpc);
2363 lpc2lsp(&unq_lpc[LPC_ORDER * 3], p->prev_lsp, cur_lsp);
2364 lsp_quantize(p->lsp_index, cur_lsp, p->prev_lsp);
2367 memcpy(vector + LPC_ORDER, p->prev_data + SUBFRAME_LEN,
2368 sizeof(int16_t) * SUBFRAME_LEN);
2369 memcpy(vector + LPC_ORDER + SUBFRAME_LEN, in,
2370 sizeof(int16_t) * (HALF_FRAME_LEN + SUBFRAME_LEN));
2371 memcpy(p->prev_data, in + HALF_FRAME_LEN,
2372 sizeof(int16_t) * HALF_FRAME_LEN);
2373 memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
2375 perceptual_filter(p, weighted_lpc, unq_lpc, vector);
2377 memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
2378 memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
2379 memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
2381 scale_vector(vector, vector, FRAME_LEN + PITCH_MAX);
2383 p->pitch_lag[0] = estimate_pitch(vector, PITCH_MAX);
2384 p->pitch_lag[1] = estimate_pitch(vector, PITCH_MAX + HALF_FRAME_LEN);
2386 for (i = PITCH_MAX, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
2387 comp_harmonic_coeff(vector + i, p->pitch_lag[j >> 1], hf + j);
2389 memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
2390 memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
2391 memcpy(p->prev_weight_sig, vector + FRAME_LEN, sizeof(int16_t) * PITCH_MAX);
2393 for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
2394 harmonic_filter(hf + j, vector + PITCH_MAX + i, in + i);
2396 inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, 0);
2397 lsp_interpolate(qnt_lpc, cur_lsp, p->prev_lsp);
2399 memcpy(p->prev_lsp, cur_lsp, sizeof(int16_t) * LPC_ORDER);
2402 for (i = 0; i < SUBFRAMES; i++) {
2403 int16_t impulse_resp[SUBFRAME_LEN];
2404 int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
2405 int16_t flt_in[SUBFRAME_LEN];
2406 int16_t zero[LPC_ORDER], fir[LPC_ORDER], iir[LPC_ORDER];
2409 * Compute the combined impulse response of the synthesis filter,
2410 * formant perceptual weighting filter and harmonic noise shaping filter
2412 memset(zero, 0, sizeof(int16_t) * LPC_ORDER);
2413 memset(vector, 0, sizeof(int16_t) * PITCH_MAX);
2414 memset(flt_in, 0, sizeof(int16_t) * SUBFRAME_LEN);
2416 flt_in[0] = 1 << 13; /* Unit impulse */
2417 synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
2418 zero, zero, flt_in, vector + PITCH_MAX, 1);
2419 harmonic_filter(hf + i, vector + PITCH_MAX, impulse_resp);
2421 /* Compute the combined zero input response */
2423 memcpy(fir, p->perf_fir_mem, sizeof(int16_t) * LPC_ORDER);
2424 memcpy(iir, p->perf_iir_mem, sizeof(int16_t) * LPC_ORDER);
2426 synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
2427 fir, iir, flt_in, vector + PITCH_MAX, 0);
2428 memcpy(vector, p->harmonic_mem, sizeof(int16_t) * PITCH_MAX);
2429 harmonic_noise_sub(hf + i, vector + PITCH_MAX, in);
2431 acb_search(p, residual, impulse_resp, in, i);
2432 gen_acb_excitation(residual, p->prev_excitation,p->pitch_lag[i >> 1],
2433 &p->subframe[i], p->cur_rate);
2434 sub_acb_contrib(residual, impulse_resp, in);
2436 fcb_search(p, impulse_resp, in, i);
2438 /* Reconstruct the excitation */
2439 gen_acb_excitation(impulse_resp, p->prev_excitation, p->pitch_lag[i >> 1],
2440 &p->subframe[i], RATE_6300);
2442 memmove(p->prev_excitation, p->prev_excitation + SUBFRAME_LEN,
2443 sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
2444 for (j = 0; j < SUBFRAME_LEN; j++)
2445 in[j] = av_clip_int16((in[j] << 1) + impulse_resp[j]);
2446 memcpy(p->prev_excitation + PITCH_MAX - SUBFRAME_LEN, in,
2447 sizeof(int16_t) * SUBFRAME_LEN);
2449 /* Update filter memories */
2450 synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
2451 p->perf_fir_mem, p->perf_iir_mem,
2452 in, vector + PITCH_MAX, 0);
2453 memmove(p->harmonic_mem, p->harmonic_mem + SUBFRAME_LEN,
2454 sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
2455 memcpy(p->harmonic_mem + PITCH_MAX - SUBFRAME_LEN, vector + PITCH_MAX,
2456 sizeof(int16_t) * SUBFRAME_LEN);
2459 offset += LPC_ORDER;
2462 if ((ret = ff_alloc_packet2(avctx, avpkt, 24)))
2465 *got_packet_ptr = 1;
2466 avpkt->size = pack_bitstream(p, avpkt->data, avpkt->size);
2470 AVCodec ff_g723_1_encoder = {
2472 .type = AVMEDIA_TYPE_AUDIO,
2473 .id = AV_CODEC_ID_G723_1,
2474 .priv_data_size = sizeof(G723_1_Context),
2475 .init = g723_1_encode_init,
2476 .encode2 = g723_1_encode_frame,
2477 .long_name = NULL_IF_CONFIG_SMALL("G.723.1"),
2478 .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,
2479 AV_SAMPLE_FMT_NONE},