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/channel_layout.h"
30 #include "libavutil/mem.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"
41 #define CNG_RANDOM_SEED 12345
43 typedef struct g723_1_context {
47 G723_1_Subframe subframe[4];
48 enum FrameType cur_frame_type;
49 enum FrameType past_frame_type;
51 uint8_t lsp_index[LSP_BANDS];
55 int16_t prev_lsp[LPC_ORDER];
56 int16_t sid_lsp[LPC_ORDER];
57 int16_t prev_excitation[PITCH_MAX];
58 int16_t excitation[PITCH_MAX + FRAME_LEN + 4];
59 int16_t synth_mem[LPC_ORDER];
60 int16_t fir_mem[LPC_ORDER];
61 int iir_mem[LPC_ORDER];
70 int pf_gain; ///< formant postfilter
71 ///< gain scaling unit memory
74 int16_t audio[FRAME_LEN + LPC_ORDER + PITCH_MAX + 4];
75 int16_t prev_data[HALF_FRAME_LEN];
76 int16_t prev_weight_sig[PITCH_MAX];
79 int16_t hpf_fir_mem; ///< highpass filter fir
80 int hpf_iir_mem; ///< and iir memories
81 int16_t perf_fir_mem[LPC_ORDER]; ///< perceptual filter fir
82 int16_t perf_iir_mem[LPC_ORDER]; ///< and iir memories
84 int16_t harmonic_mem[PITCH_MAX];
87 static av_cold int g723_1_decode_init(AVCodecContext *avctx)
89 G723_1_Context *p = avctx->priv_data;
91 avctx->channel_layout = AV_CH_LAYOUT_MONO;
92 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
96 avcodec_get_frame_defaults(&p->frame);
97 avctx->coded_frame = &p->frame;
99 memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
100 memcpy(p->sid_lsp, dc_lsp, LPC_ORDER * sizeof(*p->sid_lsp));
102 p->cng_random_seed = CNG_RANDOM_SEED;
103 p->past_frame_type = SID_FRAME;
109 * Unpack the frame into parameters.
111 * @param p the context
112 * @param buf pointer to the input buffer
113 * @param buf_size size of the input buffer
115 static int unpack_bitstream(G723_1_Context *p, const uint8_t *buf,
120 int temp, info_bits, i;
122 init_get_bits(&gb, buf, buf_size * 8);
124 /* Extract frame type and rate info */
125 info_bits = get_bits(&gb, 2);
127 if (info_bits == 3) {
128 p->cur_frame_type = UNTRANSMITTED_FRAME;
132 /* Extract 24 bit lsp indices, 8 bit for each band */
133 p->lsp_index[2] = get_bits(&gb, 8);
134 p->lsp_index[1] = get_bits(&gb, 8);
135 p->lsp_index[0] = get_bits(&gb, 8);
137 if (info_bits == 2) {
138 p->cur_frame_type = SID_FRAME;
139 p->subframe[0].amp_index = get_bits(&gb, 6);
143 /* Extract the info common to both rates */
144 p->cur_rate = info_bits ? RATE_5300 : RATE_6300;
145 p->cur_frame_type = ACTIVE_FRAME;
147 p->pitch_lag[0] = get_bits(&gb, 7);
148 if (p->pitch_lag[0] > 123) /* test if forbidden code */
150 p->pitch_lag[0] += PITCH_MIN;
151 p->subframe[1].ad_cb_lag = get_bits(&gb, 2);
153 p->pitch_lag[1] = get_bits(&gb, 7);
154 if (p->pitch_lag[1] > 123)
156 p->pitch_lag[1] += PITCH_MIN;
157 p->subframe[3].ad_cb_lag = get_bits(&gb, 2);
158 p->subframe[0].ad_cb_lag = 1;
159 p->subframe[2].ad_cb_lag = 1;
161 for (i = 0; i < SUBFRAMES; i++) {
162 /* Extract combined gain */
163 temp = get_bits(&gb, 12);
165 p->subframe[i].dirac_train = 0;
166 if (p->cur_rate == RATE_6300 && p->pitch_lag[i >> 1] < SUBFRAME_LEN - 2) {
167 p->subframe[i].dirac_train = temp >> 11;
171 p->subframe[i].ad_cb_gain = FASTDIV(temp, GAIN_LEVELS);
172 if (p->subframe[i].ad_cb_gain < ad_cb_len) {
173 p->subframe[i].amp_index = temp - p->subframe[i].ad_cb_gain *
180 p->subframe[0].grid_index = get_bits1(&gb);
181 p->subframe[1].grid_index = get_bits1(&gb);
182 p->subframe[2].grid_index = get_bits1(&gb);
183 p->subframe[3].grid_index = get_bits1(&gb);
185 if (p->cur_rate == RATE_6300) {
186 skip_bits1(&gb); /* skip reserved bit */
188 /* Compute pulse_pos index using the 13-bit combined position index */
189 temp = get_bits(&gb, 13);
190 p->subframe[0].pulse_pos = temp / 810;
192 temp -= p->subframe[0].pulse_pos * 810;
193 p->subframe[1].pulse_pos = FASTDIV(temp, 90);
195 temp -= p->subframe[1].pulse_pos * 90;
196 p->subframe[2].pulse_pos = FASTDIV(temp, 9);
197 p->subframe[3].pulse_pos = temp - p->subframe[2].pulse_pos * 9;
199 p->subframe[0].pulse_pos = (p->subframe[0].pulse_pos << 16) +
201 p->subframe[1].pulse_pos = (p->subframe[1].pulse_pos << 14) +
203 p->subframe[2].pulse_pos = (p->subframe[2].pulse_pos << 16) +
205 p->subframe[3].pulse_pos = (p->subframe[3].pulse_pos << 14) +
208 p->subframe[0].pulse_sign = get_bits(&gb, 6);
209 p->subframe[1].pulse_sign = get_bits(&gb, 5);
210 p->subframe[2].pulse_sign = get_bits(&gb, 6);
211 p->subframe[3].pulse_sign = get_bits(&gb, 5);
212 } else { /* 5300 bps */
213 p->subframe[0].pulse_pos = get_bits(&gb, 12);
214 p->subframe[1].pulse_pos = get_bits(&gb, 12);
215 p->subframe[2].pulse_pos = get_bits(&gb, 12);
216 p->subframe[3].pulse_pos = get_bits(&gb, 12);
218 p->subframe[0].pulse_sign = get_bits(&gb, 4);
219 p->subframe[1].pulse_sign = get_bits(&gb, 4);
220 p->subframe[2].pulse_sign = get_bits(&gb, 4);
221 p->subframe[3].pulse_sign = get_bits(&gb, 4);
228 * Bitexact implementation of sqrt(val/2).
230 static int16_t square_root(unsigned val)
232 av_assert2(!(val & 0x80000000));
234 return (ff_sqrt(val << 1) >> 1) & (~1);
238 * Calculate the number of left-shifts required for normalizing the input.
240 * @param num input number
241 * @param width width of the input, 15 or 31 bits
243 static int normalize_bits(int num, int width)
245 return width - av_log2(num) - 1;
248 #define normalize_bits_int16(num) normalize_bits(num, 15)
249 #define normalize_bits_int32(num) normalize_bits(num, 31)
252 * Scale vector contents based on the largest of their absolutes.
254 static int scale_vector(int16_t *dst, const int16_t *vector, int length)
259 for (i = 0; i < length; i++)
260 max |= FFABS(vector[i]);
262 bits= 14 - av_log2_16bit(max);
263 bits= FFMAX(bits, 0);
265 for (i = 0; i < length; i++)
266 dst[i] = vector[i] << bits >> 3;
272 * Perform inverse quantization of LSP frequencies.
274 * @param cur_lsp the current LSP vector
275 * @param prev_lsp the previous LSP vector
276 * @param lsp_index VQ indices
277 * @param bad_frame bad frame flag
279 static void inverse_quant(int16_t *cur_lsp, int16_t *prev_lsp,
280 uint8_t *lsp_index, int bad_frame)
283 int i, j, temp, stable;
285 /* Check for frame erasure */
292 lsp_index[0] = lsp_index[1] = lsp_index[2] = 0;
295 /* Get the VQ table entry corresponding to the transmitted index */
296 cur_lsp[0] = lsp_band0[lsp_index[0]][0];
297 cur_lsp[1] = lsp_band0[lsp_index[0]][1];
298 cur_lsp[2] = lsp_band0[lsp_index[0]][2];
299 cur_lsp[3] = lsp_band1[lsp_index[1]][0];
300 cur_lsp[4] = lsp_band1[lsp_index[1]][1];
301 cur_lsp[5] = lsp_band1[lsp_index[1]][2];
302 cur_lsp[6] = lsp_band2[lsp_index[2]][0];
303 cur_lsp[7] = lsp_band2[lsp_index[2]][1];
304 cur_lsp[8] = lsp_band2[lsp_index[2]][2];
305 cur_lsp[9] = lsp_band2[lsp_index[2]][3];
307 /* Add predicted vector & DC component to the previously quantized vector */
308 for (i = 0; i < LPC_ORDER; i++) {
309 temp = ((prev_lsp[i] - dc_lsp[i]) * pred + (1 << 14)) >> 15;
310 cur_lsp[i] += dc_lsp[i] + temp;
313 for (i = 0; i < LPC_ORDER; i++) {
314 cur_lsp[0] = FFMAX(cur_lsp[0], 0x180);
315 cur_lsp[LPC_ORDER - 1] = FFMIN(cur_lsp[LPC_ORDER - 1], 0x7e00);
317 /* Stability check */
318 for (j = 1; j < LPC_ORDER; j++) {
319 temp = min_dist + cur_lsp[j - 1] - cur_lsp[j];
322 cur_lsp[j - 1] -= temp;
327 for (j = 1; j < LPC_ORDER; j++) {
328 temp = cur_lsp[j - 1] + min_dist - cur_lsp[j] - 4;
338 memcpy(cur_lsp, prev_lsp, LPC_ORDER * sizeof(*cur_lsp));
342 * Bitexact implementation of 2ab scaled by 1/2^16.
344 * @param a 32 bit multiplicand
345 * @param b 16 bit multiplier
347 #define MULL2(a, b) \
351 * Convert LSP frequencies to LPC coefficients.
353 * @param lpc buffer for LPC coefficients
355 static void lsp2lpc(int16_t *lpc)
357 int f1[LPC_ORDER / 2 + 1];
358 int f2[LPC_ORDER / 2 + 1];
361 /* Calculate negative cosine */
362 for (j = 0; j < LPC_ORDER; j++) {
363 int index = (lpc[j] >> 7) & 0x1FF;
364 int offset = lpc[j] & 0x7f;
365 int temp1 = cos_tab[index] << 16;
366 int temp2 = (cos_tab[index + 1] - cos_tab[index]) *
367 ((offset << 8) + 0x80) << 1;
369 lpc[j] = -(av_sat_dadd32(1 << 15, temp1 + temp2) >> 16);
373 * Compute sum and difference polynomial coefficients
374 * (bitexact alternative to lsp2poly() in lsp.c)
376 /* Initialize with values in Q28 */
378 f1[1] = (lpc[0] << 14) + (lpc[2] << 14);
379 f1[2] = lpc[0] * lpc[2] + (2 << 28);
382 f2[1] = (lpc[1] << 14) + (lpc[3] << 14);
383 f2[2] = lpc[1] * lpc[3] + (2 << 28);
386 * Calculate and scale the coefficients by 1/2 in
387 * each iteration for a final scaling factor of Q25
389 for (i = 2; i < LPC_ORDER / 2; i++) {
390 f1[i + 1] = f1[i - 1] + MULL2(f1[i], lpc[2 * i]);
391 f2[i + 1] = f2[i - 1] + MULL2(f2[i], lpc[2 * i + 1]);
393 for (j = i; j >= 2; j--) {
394 f1[j] = MULL2(f1[j - 1], lpc[2 * i]) +
395 (f1[j] >> 1) + (f1[j - 2] >> 1);
396 f2[j] = MULL2(f2[j - 1], lpc[2 * i + 1]) +
397 (f2[j] >> 1) + (f2[j - 2] >> 1);
402 f1[1] = ((lpc[2 * i] << 16 >> i) + f1[1]) >> 1;
403 f2[1] = ((lpc[2 * i + 1] << 16 >> i) + f2[1]) >> 1;
406 /* Convert polynomial coefficients to LPC coefficients */
407 for (i = 0; i < LPC_ORDER / 2; i++) {
408 int64_t ff1 = f1[i + 1] + f1[i];
409 int64_t ff2 = f2[i + 1] - f2[i];
411 lpc[i] = av_clipl_int32(((ff1 + ff2) << 3) + (1 << 15)) >> 16;
412 lpc[LPC_ORDER - i - 1] = av_clipl_int32(((ff1 - ff2) << 3) +
418 * Quantize LSP frequencies by interpolation and convert them to
419 * the corresponding LPC coefficients.
421 * @param lpc buffer for LPC coefficients
422 * @param cur_lsp the current LSP vector
423 * @param prev_lsp the previous LSP vector
425 static void lsp_interpolate(int16_t *lpc, int16_t *cur_lsp, int16_t *prev_lsp)
428 int16_t *lpc_ptr = lpc;
430 /* cur_lsp * 0.25 + prev_lsp * 0.75 */
431 ff_acelp_weighted_vector_sum(lpc, cur_lsp, prev_lsp,
432 4096, 12288, 1 << 13, 14, LPC_ORDER);
433 ff_acelp_weighted_vector_sum(lpc + LPC_ORDER, cur_lsp, prev_lsp,
434 8192, 8192, 1 << 13, 14, LPC_ORDER);
435 ff_acelp_weighted_vector_sum(lpc + 2 * LPC_ORDER, cur_lsp, prev_lsp,
436 12288, 4096, 1 << 13, 14, LPC_ORDER);
437 memcpy(lpc + 3 * LPC_ORDER, cur_lsp, LPC_ORDER * sizeof(*lpc));
439 for (i = 0; i < SUBFRAMES; i++) {
441 lpc_ptr += LPC_ORDER;
446 * Generate a train of dirac functions with period as pitch lag.
448 static void gen_dirac_train(int16_t *buf, int pitch_lag)
450 int16_t vector[SUBFRAME_LEN];
453 memcpy(vector, buf, SUBFRAME_LEN * sizeof(*vector));
454 for (i = pitch_lag; i < SUBFRAME_LEN; i += pitch_lag) {
455 for (j = 0; j < SUBFRAME_LEN - i; j++)
456 buf[i + j] += vector[j];
461 * Generate fixed codebook excitation vector.
463 * @param vector decoded excitation vector
464 * @param subfrm current subframe
465 * @param cur_rate current bitrate
466 * @param pitch_lag closed loop pitch lag
467 * @param index current subframe index
469 static void gen_fcb_excitation(int16_t *vector, G723_1_Subframe *subfrm,
470 enum Rate cur_rate, int pitch_lag, int index)
474 memset(vector, 0, SUBFRAME_LEN * sizeof(*vector));
476 if (cur_rate == RATE_6300) {
477 if (subfrm->pulse_pos >= max_pos[index])
480 /* Decode amplitudes and positions */
481 j = PULSE_MAX - pulses[index];
482 temp = subfrm->pulse_pos;
483 for (i = 0; i < SUBFRAME_LEN / GRID_SIZE; i++) {
484 temp -= combinatorial_table[j][i];
487 temp += combinatorial_table[j++][i];
488 if (subfrm->pulse_sign & (1 << (PULSE_MAX - j))) {
489 vector[subfrm->grid_index + GRID_SIZE * i] =
490 -fixed_cb_gain[subfrm->amp_index];
492 vector[subfrm->grid_index + GRID_SIZE * i] =
493 fixed_cb_gain[subfrm->amp_index];
498 if (subfrm->dirac_train == 1)
499 gen_dirac_train(vector, pitch_lag);
500 } else { /* 5300 bps */
501 int cb_gain = fixed_cb_gain[subfrm->amp_index];
502 int cb_shift = subfrm->grid_index;
503 int cb_sign = subfrm->pulse_sign;
504 int cb_pos = subfrm->pulse_pos;
505 int offset, beta, lag;
507 for (i = 0; i < 8; i += 2) {
508 offset = ((cb_pos & 7) << 3) + cb_shift + i;
509 vector[offset] = (cb_sign & 1) ? cb_gain : -cb_gain;
514 /* Enhance harmonic components */
515 lag = pitch_contrib[subfrm->ad_cb_gain << 1] + pitch_lag +
516 subfrm->ad_cb_lag - 1;
517 beta = pitch_contrib[(subfrm->ad_cb_gain << 1) + 1];
519 if (lag < SUBFRAME_LEN - 2) {
520 for (i = lag; i < SUBFRAME_LEN; i++)
521 vector[i] += beta * vector[i - lag] >> 15;
527 * Get delayed contribution from the previous excitation vector.
529 static void get_residual(int16_t *residual, int16_t *prev_excitation, int lag)
531 int offset = PITCH_MAX - PITCH_ORDER / 2 - lag;
534 residual[0] = prev_excitation[offset];
535 residual[1] = prev_excitation[offset + 1];
538 for (i = 2; i < SUBFRAME_LEN + PITCH_ORDER - 1; i++)
539 residual[i] = prev_excitation[offset + (i - 2) % lag];
542 static int dot_product(const int16_t *a, const int16_t *b, int length)
544 int sum = ff_dot_product(a,b,length);
545 return av_sat_add32(sum, sum);
549 * Generate adaptive codebook excitation.
551 static void gen_acb_excitation(int16_t *vector, int16_t *prev_excitation,
552 int pitch_lag, G723_1_Subframe *subfrm,
555 int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
556 const int16_t *cb_ptr;
557 int lag = pitch_lag + subfrm->ad_cb_lag - 1;
562 get_residual(residual, prev_excitation, lag);
564 /* Select quantization table */
565 if (cur_rate == RATE_6300 && pitch_lag < SUBFRAME_LEN - 2) {
566 cb_ptr = adaptive_cb_gain85;
568 cb_ptr = adaptive_cb_gain170;
570 /* Calculate adaptive vector */
571 cb_ptr += subfrm->ad_cb_gain * 20;
572 for (i = 0; i < SUBFRAME_LEN; i++) {
573 sum = ff_dot_product(residual + i, cb_ptr, PITCH_ORDER);
574 vector[i] = av_sat_dadd32(1 << 15, av_sat_add32(sum, sum)) >> 16;
579 * Estimate maximum auto-correlation around pitch lag.
581 * @param buf buffer with offset applied
582 * @param offset offset of the excitation vector
583 * @param ccr_max pointer to the maximum auto-correlation
584 * @param pitch_lag decoded pitch lag
585 * @param length length of autocorrelation
586 * @param dir forward lag(1) / backward lag(-1)
588 static int autocorr_max(const int16_t *buf, int offset, int *ccr_max,
589 int pitch_lag, int length, int dir)
591 int limit, ccr, lag = 0;
594 pitch_lag = FFMIN(PITCH_MAX - 3, pitch_lag);
596 limit = FFMIN(FRAME_LEN + PITCH_MAX - offset - length, pitch_lag + 3);
598 limit = pitch_lag + 3;
600 for (i = pitch_lag - 3; i <= limit; i++) {
601 ccr = dot_product(buf, buf + dir * i, length);
603 if (ccr > *ccr_max) {
612 * Calculate pitch postfilter optimal and scaling gains.
614 * @param lag pitch postfilter forward/backward lag
615 * @param ppf pitch postfilter parameters
616 * @param cur_rate current bitrate
617 * @param tgt_eng target energy
618 * @param ccr cross-correlation
619 * @param res_eng residual energy
621 static void comp_ppf_gains(int lag, PPFParam *ppf, enum Rate cur_rate,
622 int tgt_eng, int ccr, int res_eng)
624 int pf_residual; /* square of postfiltered residual */
629 temp1 = tgt_eng * res_eng >> 1;
630 temp2 = ccr * ccr << 1;
633 if (ccr >= res_eng) {
634 ppf->opt_gain = ppf_gain_weight[cur_rate];
636 ppf->opt_gain = (ccr << 15) / res_eng *
637 ppf_gain_weight[cur_rate] >> 15;
639 /* pf_res^2 = tgt_eng + 2*ccr*gain + res_eng*gain^2 */
640 temp1 = (tgt_eng << 15) + (ccr * ppf->opt_gain << 1);
641 temp2 = (ppf->opt_gain * ppf->opt_gain >> 15) * res_eng;
642 pf_residual = av_sat_add32(temp1, temp2 + (1 << 15)) >> 16;
644 if (tgt_eng >= pf_residual << 1) {
647 temp1 = (tgt_eng << 14) / pf_residual;
650 /* scaling_gain = sqrt(tgt_eng/pf_res^2) */
651 ppf->sc_gain = square_root(temp1 << 16);
654 ppf->sc_gain = 0x7fff;
657 ppf->opt_gain = av_clip_int16(ppf->opt_gain * ppf->sc_gain >> 15);
661 * Calculate pitch postfilter parameters.
663 * @param p the context
664 * @param offset offset of the excitation vector
665 * @param pitch_lag decoded pitch lag
666 * @param ppf pitch postfilter parameters
667 * @param cur_rate current bitrate
669 static void comp_ppf_coeff(G723_1_Context *p, int offset, int pitch_lag,
670 PPFParam *ppf, enum Rate cur_rate)
679 * 1 - forward cross-correlation
680 * 2 - forward residual energy
681 * 3 - backward cross-correlation
682 * 4 - backward residual energy
684 int energy[5] = {0, 0, 0, 0, 0};
685 int16_t *buf = p->audio + LPC_ORDER + offset;
686 int fwd_lag = autocorr_max(buf, offset, &energy[1], pitch_lag,
688 int back_lag = autocorr_max(buf, offset, &energy[3], pitch_lag,
693 ppf->sc_gain = 0x7fff;
695 /* Case 0, Section 3.6 */
696 if (!back_lag && !fwd_lag)
699 /* Compute target energy */
700 energy[0] = dot_product(buf, buf, SUBFRAME_LEN);
702 /* Compute forward residual energy */
704 energy[2] = dot_product(buf + fwd_lag, buf + fwd_lag, SUBFRAME_LEN);
706 /* Compute backward residual energy */
708 energy[4] = dot_product(buf - back_lag, buf - back_lag, SUBFRAME_LEN);
710 /* Normalize and shorten */
712 for (i = 0; i < 5; i++)
713 temp1 = FFMAX(energy[i], temp1);
715 scale = normalize_bits(temp1, 31);
716 for (i = 0; i < 5; i++)
717 energy[i] = (energy[i] << scale) >> 16;
719 if (fwd_lag && !back_lag) { /* Case 1 */
720 comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
722 } else if (!fwd_lag) { /* Case 2 */
723 comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
725 } else { /* Case 3 */
728 * Select the largest of energy[1]^2/energy[2]
729 * and energy[3]^2/energy[4]
731 temp1 = energy[4] * ((energy[1] * energy[1] + (1 << 14)) >> 15);
732 temp2 = energy[2] * ((energy[3] * energy[3] + (1 << 14)) >> 15);
733 if (temp1 >= temp2) {
734 comp_ppf_gains(fwd_lag, ppf, cur_rate, energy[0], energy[1],
737 comp_ppf_gains(-back_lag, ppf, cur_rate, energy[0], energy[3],
744 * Classify frames as voiced/unvoiced.
746 * @param p the context
747 * @param pitch_lag decoded pitch_lag
748 * @param exc_eng excitation energy estimation
749 * @param scale scaling factor of exc_eng
751 * @return residual interpolation index if voiced, 0 otherwise
753 static int comp_interp_index(G723_1_Context *p, int pitch_lag,
754 int *exc_eng, int *scale)
756 int offset = PITCH_MAX + 2 * SUBFRAME_LEN;
757 int16_t *buf = p->audio + LPC_ORDER;
759 int index, ccr, tgt_eng, best_eng, temp;
761 *scale = scale_vector(buf, p->excitation, FRAME_LEN + PITCH_MAX);
764 /* Compute maximum backward cross-correlation */
766 index = autocorr_max(buf, offset, &ccr, pitch_lag, SUBFRAME_LEN * 2, -1);
767 ccr = av_sat_add32(ccr, 1 << 15) >> 16;
769 /* Compute target energy */
770 tgt_eng = dot_product(buf, buf, SUBFRAME_LEN * 2);
771 *exc_eng = av_sat_add32(tgt_eng, 1 << 15) >> 16;
776 /* Compute best energy */
777 best_eng = dot_product(buf - index, buf - index, SUBFRAME_LEN * 2);
778 best_eng = av_sat_add32(best_eng, 1 << 15) >> 16;
780 temp = best_eng * *exc_eng >> 3;
782 if (temp < ccr * ccr) {
789 * Peform residual interpolation based on frame classification.
791 * @param buf decoded excitation vector
792 * @param out output vector
793 * @param lag decoded pitch lag
794 * @param gain interpolated gain
795 * @param rseed seed for random number generator
797 static void residual_interp(int16_t *buf, int16_t *out, int lag,
798 int gain, int *rseed)
801 if (lag) { /* Voiced */
802 int16_t *vector_ptr = buf + PITCH_MAX;
804 for (i = 0; i < lag; i++)
805 out[i] = vector_ptr[i - lag] * 3 >> 2;
806 av_memcpy_backptr((uint8_t*)(out + lag), lag * sizeof(*out),
807 (FRAME_LEN - lag) * sizeof(*out));
808 } else { /* Unvoiced */
809 for (i = 0; i < FRAME_LEN; i++) {
810 *rseed = *rseed * 521 + 259;
811 out[i] = gain * *rseed >> 15;
813 memset(buf, 0, (FRAME_LEN + PITCH_MAX) * sizeof(*buf));
818 * Perform IIR filtering.
820 * @param fir_coef FIR coefficients
821 * @param iir_coef IIR coefficients
822 * @param src source vector
823 * @param dest destination vector
824 * @param width width of the output, 16 bits(0) / 32 bits(1)
826 #define iir_filter(fir_coef, iir_coef, src, dest, width)\
829 int res_shift = 16 & ~-(width);\
830 int in_shift = 16 - res_shift;\
832 for (m = 0; m < SUBFRAME_LEN; m++) {\
834 for (n = 1; n <= LPC_ORDER; n++) {\
835 filter -= (fir_coef)[n - 1] * (src)[m - n] -\
836 (iir_coef)[n - 1] * ((dest)[m - n] >> in_shift);\
839 (dest)[m] = av_clipl_int32(((src)[m] << 16) + (filter << 3) +\
840 (1 << 15)) >> res_shift;\
845 * Adjust gain of postfiltered signal.
847 * @param p the context
848 * @param buf postfiltered output vector
849 * @param energy input energy coefficient
851 static void gain_scale(G723_1_Context *p, int16_t * buf, int energy)
853 int num, denom, gain, bits1, bits2;
858 for (i = 0; i < SUBFRAME_LEN; i++) {
859 int temp = buf[i] >> 2;
861 denom = av_sat_dadd32(denom, temp);
865 bits1 = normalize_bits(num, 31);
866 bits2 = normalize_bits(denom, 31);
867 num = num << bits1 >> 1;
870 bits2 = 5 + bits1 - bits2;
871 bits2 = FFMAX(0, bits2);
873 gain = (num >> 1) / (denom >> 16);
874 gain = square_root(gain << 16 >> bits2);
879 for (i = 0; i < SUBFRAME_LEN; i++) {
880 p->pf_gain = (15 * p->pf_gain + gain + (1 << 3)) >> 4;
881 buf[i] = av_clip_int16((buf[i] * (p->pf_gain + (p->pf_gain >> 4)) +
887 * Perform formant filtering.
889 * @param p the context
890 * @param lpc quantized lpc coefficients
891 * @param buf input buffer
892 * @param dst output buffer
894 static void formant_postfilter(G723_1_Context *p, int16_t *lpc,
895 int16_t *buf, int16_t *dst)
897 int16_t filter_coef[2][LPC_ORDER];
898 int filter_signal[LPC_ORDER + FRAME_LEN], *signal_ptr;
901 memcpy(buf, p->fir_mem, LPC_ORDER * sizeof(*buf));
902 memcpy(filter_signal, p->iir_mem, LPC_ORDER * sizeof(*filter_signal));
904 for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
905 for (k = 0; k < LPC_ORDER; k++) {
906 filter_coef[0][k] = (-lpc[k] * postfilter_tbl[0][k] +
908 filter_coef[1][k] = (-lpc[k] * postfilter_tbl[1][k] +
911 iir_filter(filter_coef[0], filter_coef[1], buf + i,
912 filter_signal + i, 1);
916 memcpy(p->fir_mem, buf + FRAME_LEN, LPC_ORDER * sizeof(int16_t));
917 memcpy(p->iir_mem, filter_signal + FRAME_LEN, LPC_ORDER * sizeof(int));
920 signal_ptr = filter_signal + LPC_ORDER;
921 for (i = 0; i < SUBFRAMES; i++) {
927 scale = scale_vector(dst, buf, SUBFRAME_LEN);
929 /* Compute auto correlation coefficients */
930 auto_corr[0] = dot_product(dst, dst + 1, SUBFRAME_LEN - 1);
931 auto_corr[1] = dot_product(dst, dst, SUBFRAME_LEN);
933 /* Compute reflection coefficient */
934 temp = auto_corr[1] >> 16;
936 temp = (auto_corr[0] >> 2) / temp;
938 p->reflection_coef = (3 * p->reflection_coef + temp + 2) >> 2;
939 temp = -p->reflection_coef >> 1 & ~3;
941 /* Compensation filter */
942 for (j = 0; j < SUBFRAME_LEN; j++) {
943 dst[j] = av_sat_dadd32(signal_ptr[j],
944 (signal_ptr[j - 1] >> 16) * temp) >> 16;
947 /* Compute normalized signal energy */
948 temp = 2 * scale + 4;
950 energy = av_clipl_int32((int64_t)auto_corr[1] << -temp);
952 energy = auto_corr[1] >> temp;
954 gain_scale(p, dst, energy);
957 signal_ptr += SUBFRAME_LEN;
962 static int sid_gain_to_lsp_index(int gain)
966 else if (gain < 0x20)
967 return gain - 8 << 7;
969 return gain - 20 << 8;
972 static inline int cng_rand(int *state, int base)
974 *state = (*state * 521 + 259) & 0xFFFF;
975 return (*state & 0x7FFF) * base >> 15;
978 static int estimate_sid_gain(G723_1_Context *p)
980 int i, shift, seg, seg2, t, val, val_add, x, y;
982 shift = 16 - p->cur_gain * 2;
984 t = p->sid_gain << shift;
986 t = p->sid_gain >> -shift;
987 x = t * cng_filt[0] >> 16;
989 if (x >= cng_bseg[2])
992 if (x >= cng_bseg[1]) {
997 seg = (x >= cng_bseg[0]);
999 seg2 = FFMIN(seg, 3);
1003 for (i = 0; i < shift; i++) {
1004 t = seg * 32 + (val << seg2);
1013 t = seg * 32 + (val << seg2);
1016 t = seg * 32 + (val + 1 << seg2);
1018 val = (seg2 - 1 << 4) + val;
1022 t = seg * 32 + (val - 1 << seg2);
1024 val = (seg2 - 1 << 4) + val;
1032 static void generate_noise(G723_1_Context *p)
1036 int signs[SUBFRAMES / 2 * 11], pos[SUBFRAMES / 2 * 11];
1037 int tmp[SUBFRAME_LEN * 2];
1038 int16_t *vector_ptr;
1040 int b0, c, delta, x, shift;
1042 p->pitch_lag[0] = cng_rand(&p->cng_random_seed, 21) + 123;
1043 p->pitch_lag[1] = cng_rand(&p->cng_random_seed, 19) + 123;
1045 for (i = 0; i < SUBFRAMES; i++) {
1046 p->subframe[i].ad_cb_gain = cng_rand(&p->cng_random_seed, 50) + 1;
1047 p->subframe[i].ad_cb_lag = cng_adaptive_cb_lag[i];
1050 for (i = 0; i < SUBFRAMES / 2; i++) {
1051 t = cng_rand(&p->cng_random_seed, 1 << 13);
1053 off[i * 2 + 1] = ((t >> 1) & 1) + SUBFRAME_LEN;
1055 for (j = 0; j < 11; j++) {
1056 signs[i * 11 + j] = (t & 1) * 2 - 1 << 14;
1062 for (i = 0; i < SUBFRAMES; i++) {
1063 for (j = 0; j < SUBFRAME_LEN / 2; j++)
1065 t = SUBFRAME_LEN / 2;
1066 for (j = 0; j < pulses[i]; j++, idx++) {
1067 int idx2 = cng_rand(&p->cng_random_seed, t);
1069 pos[idx] = tmp[idx2] * 2 + off[i];
1070 tmp[idx2] = tmp[--t];
1074 vector_ptr = p->audio + LPC_ORDER;
1075 memcpy(vector_ptr, p->prev_excitation,
1076 PITCH_MAX * sizeof(*p->excitation));
1077 for (i = 0; i < SUBFRAMES; i += 2) {
1078 gen_acb_excitation(vector_ptr, vector_ptr,
1079 p->pitch_lag[i >> 1], &p->subframe[i],
1081 gen_acb_excitation(vector_ptr + SUBFRAME_LEN,
1082 vector_ptr + SUBFRAME_LEN,
1083 p->pitch_lag[i >> 1], &p->subframe[i + 1],
1087 for (j = 0; j < SUBFRAME_LEN * 2; j++)
1088 t |= FFABS(vector_ptr[j]);
1089 t = FFMIN(t, 0x7FFF);
1093 shift = -10 + av_log2(t);
1099 for (j = 0; j < SUBFRAME_LEN * 2; j++) {
1100 t = vector_ptr[j] << -shift;
1105 for (j = 0; j < SUBFRAME_LEN * 2; j++) {
1106 t = vector_ptr[j] >> shift;
1113 for (j = 0; j < 11; j++)
1114 b0 += tmp[pos[(i / 2) * 11 + j]] * signs[(i / 2) * 11 + j];
1115 b0 = b0 * 2 * 2979LL + (1 << 29) >> 30; // approximated division by 11
1117 c = p->cur_gain * (p->cur_gain * SUBFRAME_LEN >> 5);
1118 if (shift * 2 + 3 >= 0)
1119 c >>= shift * 2 + 3;
1121 c <<= -(shift * 2 + 3);
1122 c = (av_clipl_int32(sum << 1) - c) * 2979LL >> 15;
1124 delta = b0 * b0 * 2 - c;
1128 delta = square_root(delta);
1131 if (FFABS(t) < FFABS(x))
1139 x = av_clip(x, -10000, 10000);
1141 for (j = 0; j < 11; j++) {
1142 idx = (i / 2) * 11 + j;
1143 vector_ptr[pos[idx]] = av_clip_int16(vector_ptr[pos[idx]] +
1144 (x * signs[idx] >> 15));
1147 /* copy decoded data to serve as a history for the next decoded subframes */
1148 memcpy(vector_ptr + PITCH_MAX, vector_ptr,
1149 sizeof(*vector_ptr) * SUBFRAME_LEN * 2);
1150 vector_ptr += SUBFRAME_LEN * 2;
1152 /* Save the excitation for the next frame */
1153 memcpy(p->prev_excitation, p->audio + LPC_ORDER + FRAME_LEN,
1154 PITCH_MAX * sizeof(*p->excitation));
1157 static int g723_1_decode_frame(AVCodecContext *avctx, void *data,
1158 int *got_frame_ptr, AVPacket *avpkt)
1160 G723_1_Context *p = avctx->priv_data;
1161 const uint8_t *buf = avpkt->data;
1162 int buf_size = avpkt->size;
1163 int dec_mode = buf[0] & 3;
1165 PPFParam ppf[SUBFRAMES];
1166 int16_t cur_lsp[LPC_ORDER];
1167 int16_t lpc[SUBFRAMES * LPC_ORDER];
1168 int16_t acb_vector[SUBFRAME_LEN];
1170 int bad_frame = 0, i, j, ret;
1171 int16_t *audio = p->audio;
1173 if (buf_size < frame_size[dec_mode]) {
1175 av_log(avctx, AV_LOG_WARNING,
1176 "Expected %d bytes, got %d - skipping packet\n",
1177 frame_size[dec_mode], buf_size);
1182 if (unpack_bitstream(p, buf, buf_size) < 0) {
1184 if (p->past_frame_type == ACTIVE_FRAME)
1185 p->cur_frame_type = ACTIVE_FRAME;
1187 p->cur_frame_type = UNTRANSMITTED_FRAME;
1190 p->frame.nb_samples = FRAME_LEN;
1191 if ((ret = ff_get_buffer(avctx, &p->frame)) < 0) {
1192 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1196 out = (int16_t *)p->frame.data[0];
1198 if (p->cur_frame_type == ACTIVE_FRAME) {
1200 p->erased_frames = 0;
1201 else if (p->erased_frames != 3)
1204 inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, bad_frame);
1205 lsp_interpolate(lpc, cur_lsp, p->prev_lsp);
1207 /* Save the lsp_vector for the next frame */
1208 memcpy(p->prev_lsp, cur_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
1210 /* Generate the excitation for the frame */
1211 memcpy(p->excitation, p->prev_excitation,
1212 PITCH_MAX * sizeof(*p->excitation));
1213 if (!p->erased_frames) {
1214 int16_t *vector_ptr = p->excitation + PITCH_MAX;
1216 /* Update interpolation gain memory */
1217 p->interp_gain = fixed_cb_gain[(p->subframe[2].amp_index +
1218 p->subframe[3].amp_index) >> 1];
1219 for (i = 0; i < SUBFRAMES; i++) {
1220 gen_fcb_excitation(vector_ptr, &p->subframe[i], p->cur_rate,
1221 p->pitch_lag[i >> 1], i);
1222 gen_acb_excitation(acb_vector, &p->excitation[SUBFRAME_LEN * i],
1223 p->pitch_lag[i >> 1], &p->subframe[i],
1225 /* Get the total excitation */
1226 for (j = 0; j < SUBFRAME_LEN; j++) {
1227 int v = av_clip_int16(vector_ptr[j] << 1);
1228 vector_ptr[j] = av_clip_int16(v + acb_vector[j]);
1230 vector_ptr += SUBFRAME_LEN;
1233 vector_ptr = p->excitation + PITCH_MAX;
1235 p->interp_index = comp_interp_index(p, p->pitch_lag[1],
1236 &p->sid_gain, &p->cur_gain);
1238 /* Peform pitch postfiltering */
1239 if (p->postfilter) {
1241 for (j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1242 comp_ppf_coeff(p, i, p->pitch_lag[j >> 1],
1243 ppf + j, p->cur_rate);
1245 for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1246 ff_acelp_weighted_vector_sum(p->audio + LPC_ORDER + i,
1248 vector_ptr + i + ppf[j].index,
1251 1 << 14, 15, SUBFRAME_LEN);
1253 audio = vector_ptr - LPC_ORDER;
1256 /* Save the excitation for the next frame */
1257 memcpy(p->prev_excitation, p->excitation + FRAME_LEN,
1258 PITCH_MAX * sizeof(*p->excitation));
1260 p->interp_gain = (p->interp_gain * 3 + 2) >> 2;
1261 if (p->erased_frames == 3) {
1263 memset(p->excitation, 0,
1264 (FRAME_LEN + PITCH_MAX) * sizeof(*p->excitation));
1265 memset(p->prev_excitation, 0,
1266 PITCH_MAX * sizeof(*p->excitation));
1267 memset(p->frame.data[0], 0,
1268 (FRAME_LEN + LPC_ORDER) * sizeof(int16_t));
1270 int16_t *buf = p->audio + LPC_ORDER;
1272 /* Regenerate frame */
1273 residual_interp(p->excitation, buf, p->interp_index,
1274 p->interp_gain, &p->random_seed);
1276 /* Save the excitation for the next frame */
1277 memcpy(p->prev_excitation, buf + (FRAME_LEN - PITCH_MAX),
1278 PITCH_MAX * sizeof(*p->excitation));
1281 p->cng_random_seed = CNG_RANDOM_SEED;
1283 if (p->cur_frame_type == SID_FRAME) {
1284 p->sid_gain = sid_gain_to_lsp_index(p->subframe[0].amp_index);
1285 inverse_quant(p->sid_lsp, p->prev_lsp, p->lsp_index, 0);
1286 } else if (p->past_frame_type == ACTIVE_FRAME) {
1287 p->sid_gain = estimate_sid_gain(p);
1290 if (p->past_frame_type == ACTIVE_FRAME)
1291 p->cur_gain = p->sid_gain;
1293 p->cur_gain = (p->cur_gain * 7 + p->sid_gain) >> 3;
1295 lsp_interpolate(lpc, p->sid_lsp, p->prev_lsp);
1296 /* Save the lsp_vector for the next frame */
1297 memcpy(p->prev_lsp, p->sid_lsp, LPC_ORDER * sizeof(*p->prev_lsp));
1300 p->past_frame_type = p->cur_frame_type;
1302 memcpy(p->audio, p->synth_mem, LPC_ORDER * sizeof(*p->audio));
1303 for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1304 ff_celp_lp_synthesis_filter(p->audio + i, &lpc[j * LPC_ORDER],
1305 audio + i, SUBFRAME_LEN, LPC_ORDER,
1307 memcpy(p->synth_mem, p->audio + FRAME_LEN, LPC_ORDER * sizeof(*p->audio));
1309 if (p->postfilter) {
1310 formant_postfilter(p, lpc, p->audio, out);
1311 } else { // if output is not postfiltered it should be scaled by 2
1312 for (i = 0; i < FRAME_LEN; i++)
1313 out[i] = av_clip_int16(p->audio[LPC_ORDER + i] << 1);
1317 *(AVFrame *)data = p->frame;
1319 return frame_size[dec_mode];
1322 #define OFFSET(x) offsetof(G723_1_Context, x)
1323 #define AD AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1325 static const AVOption options[] = {
1326 { "postfilter", "postfilter on/off", OFFSET(postfilter), AV_OPT_TYPE_INT,
1327 { .i64 = 1 }, 0, 1, AD },
1332 static const AVClass g723_1dec_class = {
1333 .class_name = "G.723.1 decoder",
1334 .item_name = av_default_item_name,
1336 .version = LIBAVUTIL_VERSION_INT,
1339 AVCodec ff_g723_1_decoder = {
1341 .type = AVMEDIA_TYPE_AUDIO,
1342 .id = AV_CODEC_ID_G723_1,
1343 .priv_data_size = sizeof(G723_1_Context),
1344 .init = g723_1_decode_init,
1345 .decode = g723_1_decode_frame,
1346 .long_name = NULL_IF_CONFIG_SMALL("G.723.1"),
1347 .capabilities = CODEC_CAP_SUBFRAMES | CODEC_CAP_DR1,
1348 .priv_class = &g723_1dec_class,
1351 #if CONFIG_G723_1_ENCODER
1352 #define BITSTREAM_WRITER_LE
1353 #include "put_bits.h"
1355 static av_cold int g723_1_encode_init(AVCodecContext *avctx)
1357 G723_1_Context *p = avctx->priv_data;
1359 if (avctx->sample_rate != 8000) {
1360 av_log(avctx, AV_LOG_ERROR, "Only 8000Hz sample rate supported\n");
1364 if (avctx->channels != 1) {
1365 av_log(avctx, AV_LOG_ERROR, "Only mono supported\n");
1366 return AVERROR(EINVAL);
1369 if (avctx->bit_rate == 6300) {
1370 p->cur_rate = RATE_6300;
1371 } else if (avctx->bit_rate == 5300) {
1372 av_log(avctx, AV_LOG_ERROR, "Bitrate not supported yet, use 6.3k\n");
1373 return AVERROR_PATCHWELCOME;
1375 av_log(avctx, AV_LOG_ERROR,
1376 "Bitrate not supported, use 6.3k\n");
1377 return AVERROR(EINVAL);
1379 avctx->frame_size = 240;
1380 memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(int16_t));
1386 * Remove DC component from the input signal.
1388 * @param buf input signal
1389 * @param fir zero memory
1390 * @param iir pole memory
1392 static void highpass_filter(int16_t *buf, int16_t *fir, int *iir)
1395 for (i = 0; i < FRAME_LEN; i++) {
1396 *iir = (buf[i] << 15) + ((-*fir) << 15) + MULL2(*iir, 0x7f00);
1398 buf[i] = av_clipl_int32((int64_t)*iir + (1 << 15)) >> 16;
1403 * Estimate autocorrelation of the input vector.
1405 * @param buf input buffer
1406 * @param autocorr autocorrelation coefficients vector
1408 static void comp_autocorr(int16_t *buf, int16_t *autocorr)
1411 int16_t vector[LPC_FRAME];
1413 scale_vector(vector, buf, LPC_FRAME);
1415 /* Apply the Hamming window */
1416 for (i = 0; i < LPC_FRAME; i++)
1417 vector[i] = (vector[i] * hamming_window[i] + (1 << 14)) >> 15;
1419 /* Compute the first autocorrelation coefficient */
1420 temp = ff_dot_product(vector, vector, LPC_FRAME);
1422 /* Apply a white noise correlation factor of (1025/1024) */
1426 scale = normalize_bits_int32(temp);
1427 autocorr[0] = av_clipl_int32((int64_t)(temp << scale) +
1430 /* Compute the remaining coefficients */
1432 memset(autocorr + 1, 0, LPC_ORDER * sizeof(int16_t));
1434 for (i = 1; i <= LPC_ORDER; i++) {
1435 temp = ff_dot_product(vector, vector + i, LPC_FRAME - i);
1436 temp = MULL2((temp << scale), binomial_window[i - 1]);
1437 autocorr[i] = av_clipl_int32((int64_t)temp + (1 << 15)) >> 16;
1443 * Use Levinson-Durbin recursion to compute LPC coefficients from
1444 * autocorrelation values.
1446 * @param lpc LPC coefficients vector
1447 * @param autocorr autocorrelation coefficients vector
1448 * @param error prediction error
1450 static void levinson_durbin(int16_t *lpc, int16_t *autocorr, int16_t error)
1452 int16_t vector[LPC_ORDER];
1453 int16_t partial_corr;
1456 memset(lpc, 0, LPC_ORDER * sizeof(int16_t));
1458 for (i = 0; i < LPC_ORDER; i++) {
1459 /* Compute the partial correlation coefficient */
1461 for (j = 0; j < i; j++)
1462 temp -= lpc[j] * autocorr[i - j - 1];
1463 temp = ((autocorr[i] << 13) + temp) << 3;
1465 if (FFABS(temp) >= (error << 16))
1468 partial_corr = temp / (error << 1);
1470 lpc[i] = av_clipl_int32((int64_t)(partial_corr << 14) +
1473 /* Update the prediction error */
1474 temp = MULL2(temp, partial_corr);
1475 error = av_clipl_int32((int64_t)(error << 16) - temp +
1478 memcpy(vector, lpc, i * sizeof(int16_t));
1479 for (j = 0; j < i; j++) {
1480 temp = partial_corr * vector[i - j - 1] << 1;
1481 lpc[j] = av_clipl_int32((int64_t)(lpc[j] << 16) - temp +
1488 * Calculate LPC coefficients for the current frame.
1490 * @param buf current frame
1491 * @param prev_data 2 trailing subframes of the previous frame
1492 * @param lpc LPC coefficients vector
1494 static void comp_lpc_coeff(int16_t *buf, int16_t *lpc)
1496 int16_t autocorr[(LPC_ORDER + 1) * SUBFRAMES];
1497 int16_t *autocorr_ptr = autocorr;
1498 int16_t *lpc_ptr = lpc;
1501 for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
1502 comp_autocorr(buf + i, autocorr_ptr);
1503 levinson_durbin(lpc_ptr, autocorr_ptr + 1, autocorr_ptr[0]);
1505 lpc_ptr += LPC_ORDER;
1506 autocorr_ptr += LPC_ORDER + 1;
1510 static void lpc2lsp(int16_t *lpc, int16_t *prev_lsp, int16_t *lsp)
1512 int f[LPC_ORDER + 2]; ///< coefficients of the sum and difference
1513 ///< polynomials (F1, F2) ordered as
1514 ///< f1[0], f2[0], ...., f1[5], f2[5]
1516 int max, shift, cur_val, prev_val, count, p;
1520 /* Initialize f1[0] and f2[0] to 1 in Q25 */
1521 for (i = 0; i < LPC_ORDER; i++)
1522 lsp[i] = (lpc[i] * bandwidth_expand[i] + (1 << 14)) >> 15;
1524 /* Apply bandwidth expansion on the LPC coefficients */
1525 f[0] = f[1] = 1 << 25;
1527 /* Compute the remaining coefficients */
1528 for (i = 0; i < LPC_ORDER / 2; i++) {
1530 f[2 * i + 2] = -f[2 * i] - ((lsp[i] + lsp[LPC_ORDER - 1 - i]) << 12);
1532 f[2 * i + 3] = f[2 * i + 1] - ((lsp[i] - lsp[LPC_ORDER - 1 - i]) << 12);
1535 /* Divide f1[5] and f2[5] by 2 for use in polynomial evaluation */
1537 f[LPC_ORDER + 1] >>= 1;
1539 /* Normalize and shorten */
1541 for (i = 1; i < LPC_ORDER + 2; i++)
1542 max = FFMAX(max, FFABS(f[i]));
1544 shift = normalize_bits_int32(max);
1546 for (i = 0; i < LPC_ORDER + 2; i++)
1547 f[i] = av_clipl_int32((int64_t)(f[i] << shift) + (1 << 15)) >> 16;
1550 * Evaluate F1 and F2 at uniform intervals of pi/256 along the
1551 * unit circle and check for zero crossings.
1555 for (i = 0; i <= LPC_ORDER / 2; i++)
1556 temp += f[2 * i] * cos_tab[0];
1557 prev_val = av_clipl_int32(temp << 1);
1559 for ( i = 1; i < COS_TBL_SIZE / 2; i++) {
1562 for (j = 0; j <= LPC_ORDER / 2; j++)
1563 temp += f[LPC_ORDER - 2 * j + p] * cos_tab[i * j % COS_TBL_SIZE];
1564 cur_val = av_clipl_int32(temp << 1);
1566 /* Check for sign change, indicating a zero crossing */
1567 if ((cur_val ^ prev_val) < 0) {
1568 int abs_cur = FFABS(cur_val);
1569 int abs_prev = FFABS(prev_val);
1570 int sum = abs_cur + abs_prev;
1572 shift = normalize_bits_int32(sum);
1574 abs_prev = abs_prev << shift >> 8;
1575 lsp[count++] = ((i - 1) << 7) + (abs_prev >> 1) / (sum >> 16);
1577 if (count == LPC_ORDER)
1580 /* Switch between sum and difference polynomials */
1585 for (j = 0; j <= LPC_ORDER / 2; j++){
1586 temp += f[LPC_ORDER - 2 * j + p] *
1587 cos_tab[i * j % COS_TBL_SIZE];
1589 cur_val = av_clipl_int32(temp<<1);
1594 if (count != LPC_ORDER)
1595 memcpy(lsp, prev_lsp, LPC_ORDER * sizeof(int16_t));
1599 * Quantize the current LSP subvector.
1601 * @param num band number
1602 * @param offset offset of the current subvector in an LPC_ORDER vector
1603 * @param size size of the current subvector
1605 #define get_index(num, offset, size) \
1607 int error, max = -1;\
1610 for (i = 0; i < LSP_CB_SIZE; i++) {\
1611 for (j = 0; j < size; j++){\
1612 temp[j] = (weight[j + (offset)] * lsp_band##num[i][j] +\
1615 error = dot_product(lsp + (offset), temp, size) << 1;\
1616 error -= dot_product(lsp_band##num[i], temp, size);\
1619 lsp_index[num] = i;\
1625 * Vector quantize the LSP frequencies.
1627 * @param lsp the current lsp vector
1628 * @param prev_lsp the previous lsp vector
1630 static void lsp_quantize(uint8_t *lsp_index, int16_t *lsp, int16_t *prev_lsp)
1632 int16_t weight[LPC_ORDER];
1636 /* Calculate the VQ weighting vector */
1637 weight[0] = (1 << 20) / (lsp[1] - lsp[0]);
1638 weight[LPC_ORDER - 1] = (1 << 20) /
1639 (lsp[LPC_ORDER - 1] - lsp[LPC_ORDER - 2]);
1641 for (i = 1; i < LPC_ORDER - 1; i++) {
1642 min = FFMIN(lsp[i] - lsp[i - 1], lsp[i + 1] - lsp[i]);
1644 weight[i] = (1 << 20) / min;
1646 weight[i] = INT16_MAX;
1651 for (i = 0; i < LPC_ORDER; i++)
1652 max = FFMAX(weight[i], max);
1654 shift = normalize_bits_int16(max);
1655 for (i = 0; i < LPC_ORDER; i++) {
1656 weight[i] <<= shift;
1659 /* Compute the VQ target vector */
1660 for (i = 0; i < LPC_ORDER; i++) {
1661 lsp[i] -= dc_lsp[i] +
1662 (((prev_lsp[i] - dc_lsp[i]) * 12288 + (1 << 14)) >> 15);
1671 * Apply the formant perceptual weighting filter.
1673 * @param flt_coef filter coefficients
1674 * @param unq_lpc unquantized lpc vector
1676 static void perceptual_filter(G723_1_Context *p, int16_t *flt_coef,
1677 int16_t *unq_lpc, int16_t *buf)
1679 int16_t vector[FRAME_LEN + LPC_ORDER];
1682 memcpy(buf, p->iir_mem, sizeof(int16_t) * LPC_ORDER);
1683 memcpy(vector, p->fir_mem, sizeof(int16_t) * LPC_ORDER);
1684 memcpy(vector + LPC_ORDER, buf + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
1686 for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
1687 for (k = 0; k < LPC_ORDER; k++) {
1688 flt_coef[k + 2 * l] = (unq_lpc[k + l] * percept_flt_tbl[0][k] +
1690 flt_coef[k + 2 * l + LPC_ORDER] = (unq_lpc[k + l] *
1691 percept_flt_tbl[1][k] +
1694 iir_filter(flt_coef + 2 * l, flt_coef + 2 * l + LPC_ORDER, vector + i,
1698 memcpy(p->iir_mem, buf + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
1699 memcpy(p->fir_mem, vector + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
1703 * Estimate the open loop pitch period.
1705 * @param buf perceptually weighted speech
1706 * @param start estimation is carried out from this position
1708 static int estimate_pitch(int16_t *buf, int start)
1711 int max_ccr = 0x4000;
1712 int max_eng = 0x7fff;
1713 int index = PITCH_MIN;
1714 int offset = start - PITCH_MIN + 1;
1716 int ccr, eng, orig_eng, ccr_eng, exp;
1721 orig_eng = ff_dot_product(buf + offset, buf + offset, HALF_FRAME_LEN);
1723 for (i = PITCH_MIN; i <= PITCH_MAX - 3; i++) {
1726 /* Update energy and compute correlation */
1727 orig_eng += buf[offset] * buf[offset] -
1728 buf[offset + HALF_FRAME_LEN] * buf[offset + HALF_FRAME_LEN];
1729 ccr = ff_dot_product(buf + start, buf + offset, HALF_FRAME_LEN);
1733 /* Split into mantissa and exponent to maintain precision */
1734 exp = normalize_bits_int32(ccr);
1735 ccr = av_clipl_int32((int64_t)(ccr << exp) + (1 << 15)) >> 16;
1738 temp = normalize_bits_int32(ccr);
1739 ccr = ccr << temp >> 16;
1742 temp = normalize_bits_int32(orig_eng);
1743 eng = av_clipl_int32((int64_t)(orig_eng << temp) + (1 << 15)) >> 16;
1753 if (exp + 1 < max_exp)
1756 /* Equalize exponents before comparison */
1757 if (exp + 1 == max_exp)
1758 temp = max_ccr >> 1;
1761 ccr_eng = ccr * max_eng;
1762 diff = ccr_eng - eng * temp;
1763 if (diff > 0 && (i - index < PITCH_MIN || diff > ccr_eng >> 2)) {
1775 * Compute harmonic noise filter parameters.
1777 * @param buf perceptually weighted speech
1778 * @param pitch_lag open loop pitch period
1779 * @param hf harmonic filter parameters
1781 static void comp_harmonic_coeff(int16_t *buf, int16_t pitch_lag, HFParam *hf)
1783 int ccr, eng, max_ccr, max_eng;
1788 for (i = 0, j = pitch_lag - 3; j <= pitch_lag + 3; i++, j++) {
1789 /* Compute residual energy */
1790 energy[i << 1] = ff_dot_product(buf - j, buf - j, SUBFRAME_LEN);
1791 /* Compute correlation */
1792 energy[(i << 1) + 1] = ff_dot_product(buf, buf - j, SUBFRAME_LEN);
1795 /* Compute target energy */
1796 energy[14] = ff_dot_product(buf, buf, SUBFRAME_LEN);
1800 for (i = 0; i < 15; i++)
1801 max = FFMAX(max, FFABS(energy[i]));
1803 exp = normalize_bits_int32(max);
1804 for (i = 0; i < 15; i++) {
1805 energy[i] = av_clipl_int32((int64_t)(energy[i] << exp) +
1814 for (i = 0; i <= 6; i++) {
1815 eng = energy[i << 1];
1816 ccr = energy[(i << 1) + 1];
1821 ccr = (ccr * ccr + (1 << 14)) >> 15;
1822 diff = ccr * max_eng - eng * max_ccr;
1830 if (hf->index == -1) {
1831 hf->index = pitch_lag;
1835 eng = energy[14] * max_eng;
1836 eng = (eng >> 2) + (eng >> 3);
1837 ccr = energy[(hf->index << 1) + 1] * energy[(hf->index << 1) + 1];
1839 eng = energy[(hf->index << 1) + 1];
1844 hf->gain = ((eng << 15) / max_eng * 0x2800 + (1 << 14)) >> 15;
1846 hf->index += pitch_lag - 3;
1850 * Apply the harmonic noise shaping filter.
1852 * @param hf filter parameters
1854 static void harmonic_filter(HFParam *hf, const int16_t *src, int16_t *dest)
1858 for (i = 0; i < SUBFRAME_LEN; i++) {
1859 int64_t temp = hf->gain * src[i - hf->index] << 1;
1860 dest[i] = av_clipl_int32((src[i] << 16) - temp + (1 << 15)) >> 16;
1864 static void harmonic_noise_sub(HFParam *hf, const int16_t *src, int16_t *dest)
1867 for (i = 0; i < SUBFRAME_LEN; i++) {
1868 int64_t temp = hf->gain * src[i - hf->index] << 1;
1869 dest[i] = av_clipl_int32(((dest[i] - src[i]) << 16) + temp +
1876 * Combined synthesis and formant perceptual weighting filer.
1878 * @param qnt_lpc quantized lpc coefficients
1879 * @param perf_lpc perceptual filter coefficients
1880 * @param perf_fir perceptual filter fir memory
1881 * @param perf_iir perceptual filter iir memory
1882 * @param scale the filter output will be scaled by 2^scale
1884 static void synth_percept_filter(int16_t *qnt_lpc, int16_t *perf_lpc,
1885 int16_t *perf_fir, int16_t *perf_iir,
1886 const int16_t *src, int16_t *dest, int scale)
1889 int16_t buf_16[SUBFRAME_LEN + LPC_ORDER];
1890 int64_t buf[SUBFRAME_LEN];
1892 int16_t *bptr_16 = buf_16 + LPC_ORDER;
1894 memcpy(buf_16, perf_fir, sizeof(int16_t) * LPC_ORDER);
1895 memcpy(dest - LPC_ORDER, perf_iir, sizeof(int16_t) * LPC_ORDER);
1897 for (i = 0; i < SUBFRAME_LEN; i++) {
1899 for (j = 1; j <= LPC_ORDER; j++)
1900 temp -= qnt_lpc[j - 1] * bptr_16[i - j];
1902 buf[i] = (src[i] << 15) + (temp << 3);
1903 bptr_16[i] = av_clipl_int32(buf[i] + (1 << 15)) >> 16;
1906 for (i = 0; i < SUBFRAME_LEN; i++) {
1907 int64_t fir = 0, iir = 0;
1908 for (j = 1; j <= LPC_ORDER; j++) {
1909 fir -= perf_lpc[j - 1] * bptr_16[i - j];
1910 iir += perf_lpc[j + LPC_ORDER - 1] * dest[i - j];
1912 dest[i] = av_clipl_int32(((buf[i] + (fir << 3)) << scale) + (iir << 3) +
1915 memcpy(perf_fir, buf_16 + SUBFRAME_LEN, sizeof(int16_t) * LPC_ORDER);
1916 memcpy(perf_iir, dest + SUBFRAME_LEN - LPC_ORDER,
1917 sizeof(int16_t) * LPC_ORDER);
1921 * Compute the adaptive codebook contribution.
1923 * @param buf input signal
1924 * @param index the current subframe index
1926 static void acb_search(G723_1_Context *p, int16_t *residual,
1927 int16_t *impulse_resp, const int16_t *buf,
1931 int16_t flt_buf[PITCH_ORDER][SUBFRAME_LEN];
1933 const int16_t *cb_tbl = adaptive_cb_gain85;
1935 int ccr_buf[PITCH_ORDER * SUBFRAMES << 2];
1937 int pitch_lag = p->pitch_lag[index >> 1];
1940 int odd_frame = index & 1;
1941 int iter = 3 + odd_frame;
1945 int i, j, k, l, max;
1949 if (pitch_lag == PITCH_MIN)
1952 pitch_lag = FFMIN(pitch_lag, PITCH_MAX - 5);
1955 for (i = 0; i < iter; i++) {
1956 get_residual(residual, p->prev_excitation, pitch_lag + i - 1);
1958 for (j = 0; j < SUBFRAME_LEN; j++) {
1960 for (k = 0; k <= j; k++)
1961 temp += residual[PITCH_ORDER - 1 + k] * impulse_resp[j - k];
1962 flt_buf[PITCH_ORDER - 1][j] = av_clipl_int32((temp << 1) +
1966 for (j = PITCH_ORDER - 2; j >= 0; j--) {
1967 flt_buf[j][0] = ((residual[j] << 13) + (1 << 14)) >> 15;
1968 for (k = 1; k < SUBFRAME_LEN; k++) {
1969 temp = (flt_buf[j + 1][k - 1] << 15) +
1970 residual[j] * impulse_resp[k];
1971 flt_buf[j][k] = av_clipl_int32((temp << 1) + (1 << 15)) >> 16;
1975 /* Compute crosscorrelation with the signal */
1976 for (j = 0; j < PITCH_ORDER; j++) {
1977 temp = ff_dot_product(buf, flt_buf[j], SUBFRAME_LEN);
1978 ccr_buf[count++] = av_clipl_int32(temp << 1);
1981 /* Compute energies */
1982 for (j = 0; j < PITCH_ORDER; j++) {
1983 ccr_buf[count++] = dot_product(flt_buf[j], flt_buf[j],
1987 for (j = 1; j < PITCH_ORDER; j++) {
1988 for (k = 0; k < j; k++) {
1989 temp = ff_dot_product(flt_buf[j], flt_buf[k], SUBFRAME_LEN);
1990 ccr_buf[count++] = av_clipl_int32(temp<<2);
1995 /* Normalize and shorten */
1997 for (i = 0; i < 20 * iter; i++)
1998 max = FFMAX(max, FFABS(ccr_buf[i]));
2000 temp = normalize_bits_int32(max);
2002 for (i = 0; i < 20 * iter; i++){
2003 ccr_buf[i] = av_clipl_int32((int64_t)(ccr_buf[i] << temp) +
2008 for (i = 0; i < iter; i++) {
2009 /* Select quantization table */
2010 if (!odd_frame && pitch_lag + i - 1 >= SUBFRAME_LEN - 2 ||
2011 odd_frame && pitch_lag >= SUBFRAME_LEN - 2) {
2012 cb_tbl = adaptive_cb_gain170;
2016 for (j = 0, k = 0; j < tbl_size; j++, k += 20) {
2018 for (l = 0; l < 20; l++)
2019 temp += ccr_buf[20 * i + l] * cb_tbl[k + l];
2020 temp = av_clipl_int32(temp);
2031 pitch_lag += acb_lag - 1;
2035 p->pitch_lag[index >> 1] = pitch_lag;
2036 p->subframe[index].ad_cb_lag = acb_lag;
2037 p->subframe[index].ad_cb_gain = acb_gain;
2041 * Subtract the adaptive codebook contribution from the input
2042 * to obtain the residual.
2044 * @param buf target vector
2046 static void sub_acb_contrib(const int16_t *residual, const int16_t *impulse_resp,
2050 /* Subtract adaptive CB contribution to obtain the residual */
2051 for (i = 0; i < SUBFRAME_LEN; i++) {
2052 int64_t temp = buf[i] << 14;
2053 for (j = 0; j <= i; j++)
2054 temp -= residual[j] * impulse_resp[i - j];
2056 buf[i] = av_clipl_int32((temp << 2) + (1 << 15)) >> 16;
2061 * Quantize the residual signal using the fixed codebook (MP-MLQ).
2063 * @param optim optimized fixed codebook parameters
2064 * @param buf excitation vector
2066 static void get_fcb_param(FCBParam *optim, int16_t *impulse_resp,
2067 int16_t *buf, int pulse_cnt, int pitch_lag)
2070 int16_t impulse_r[SUBFRAME_LEN];
2071 int16_t temp_corr[SUBFRAME_LEN];
2072 int16_t impulse_corr[SUBFRAME_LEN];
2074 int ccr1[SUBFRAME_LEN];
2075 int ccr2[SUBFRAME_LEN];
2076 int amp, err, max, max_amp_index, min, scale, i, j, k, l;
2080 /* Update impulse response */
2081 memcpy(impulse_r, impulse_resp, sizeof(int16_t) * SUBFRAME_LEN);
2082 param.dirac_train = 0;
2083 if (pitch_lag < SUBFRAME_LEN - 2) {
2084 param.dirac_train = 1;
2085 gen_dirac_train(impulse_r, pitch_lag);
2088 for (i = 0; i < SUBFRAME_LEN; i++)
2089 temp_corr[i] = impulse_r[i] >> 1;
2091 /* Compute impulse response autocorrelation */
2092 temp = dot_product(temp_corr, temp_corr, SUBFRAME_LEN);
2094 scale = normalize_bits_int32(temp);
2095 impulse_corr[0] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
2097 for (i = 1; i < SUBFRAME_LEN; i++) {
2098 temp = dot_product(temp_corr + i, temp_corr, SUBFRAME_LEN - i);
2099 impulse_corr[i] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
2102 /* Compute crosscorrelation of impulse response with residual signal */
2104 for (i = 0; i < SUBFRAME_LEN; i++){
2105 temp = dot_product(buf + i, impulse_r, SUBFRAME_LEN - i);
2107 ccr1[i] = temp >> -scale;
2109 ccr1[i] = av_clipl_int32(temp << scale);
2113 for (i = 0; i < GRID_SIZE; i++) {
2114 /* Maximize the crosscorrelation */
2116 for (j = i; j < SUBFRAME_LEN; j += GRID_SIZE) {
2117 temp = FFABS(ccr1[j]);
2120 param.pulse_pos[0] = j;
2124 /* Quantize the gain (max crosscorrelation/impulse_corr[0]) */
2127 max_amp_index = GAIN_LEVELS - 2;
2128 for (j = max_amp_index; j >= 2; j--) {
2129 temp = av_clipl_int32((int64_t)fixed_cb_gain[j] *
2130 impulse_corr[0] << 1);
2131 temp = FFABS(temp - amp);
2139 /* Select additional gain values */
2140 for (j = 1; j < 5; j++) {
2141 for (k = i; k < SUBFRAME_LEN; k += GRID_SIZE) {
2145 param.amp_index = max_amp_index + j - 2;
2146 amp = fixed_cb_gain[param.amp_index];
2148 param.pulse_sign[0] = (ccr2[param.pulse_pos[0]] < 0) ? -amp : amp;
2149 temp_corr[param.pulse_pos[0]] = 1;
2151 for (k = 1; k < pulse_cnt; k++) {
2153 for (l = i; l < SUBFRAME_LEN; l += GRID_SIZE) {
2156 temp = impulse_corr[FFABS(l - param.pulse_pos[k - 1])];
2157 temp = av_clipl_int32((int64_t)temp *
2158 param.pulse_sign[k - 1] << 1);
2160 temp = FFABS(ccr2[l]);
2163 param.pulse_pos[k] = l;
2167 param.pulse_sign[k] = (ccr2[param.pulse_pos[k]] < 0) ?
2169 temp_corr[param.pulse_pos[k]] = 1;
2172 /* Create the error vector */
2173 memset(temp_corr, 0, sizeof(int16_t) * SUBFRAME_LEN);
2175 for (k = 0; k < pulse_cnt; k++)
2176 temp_corr[param.pulse_pos[k]] = param.pulse_sign[k];
2178 for (k = SUBFRAME_LEN - 1; k >= 0; k--) {
2180 for (l = 0; l <= k; l++) {
2181 int prod = av_clipl_int32((int64_t)temp_corr[l] *
2182 impulse_r[k - l] << 1);
2183 temp = av_clipl_int32(temp + prod);
2185 temp_corr[k] = temp << 2 >> 16;
2188 /* Compute square of error */
2190 for (k = 0; k < SUBFRAME_LEN; k++) {
2192 prod = av_clipl_int32((int64_t)buf[k] * temp_corr[k] << 1);
2193 err = av_clipl_int32(err - prod);
2194 prod = av_clipl_int32((int64_t)temp_corr[k] * temp_corr[k]);
2195 err = av_clipl_int32(err + prod);
2199 if (err < optim->min_err) {
2200 optim->min_err = err;
2201 optim->grid_index = i;
2202 optim->amp_index = param.amp_index;
2203 optim->dirac_train = param.dirac_train;
2205 for (k = 0; k < pulse_cnt; k++) {
2206 optim->pulse_sign[k] = param.pulse_sign[k];
2207 optim->pulse_pos[k] = param.pulse_pos[k];
2215 * Encode the pulse position and gain of the current subframe.
2217 * @param optim optimized fixed CB parameters
2218 * @param buf excitation vector
2220 static void pack_fcb_param(G723_1_Subframe *subfrm, FCBParam *optim,
2221 int16_t *buf, int pulse_cnt)
2225 j = PULSE_MAX - pulse_cnt;
2227 subfrm->pulse_sign = 0;
2228 subfrm->pulse_pos = 0;
2230 for (i = 0; i < SUBFRAME_LEN >> 1; i++) {
2231 int val = buf[optim->grid_index + (i << 1)];
2233 subfrm->pulse_pos += combinatorial_table[j][i];
2235 subfrm->pulse_sign <<= 1;
2236 if (val < 0) subfrm->pulse_sign++;
2239 if (j == PULSE_MAX) break;
2242 subfrm->amp_index = optim->amp_index;
2243 subfrm->grid_index = optim->grid_index;
2244 subfrm->dirac_train = optim->dirac_train;
2248 * Compute the fixed codebook excitation.
2250 * @param buf target vector
2251 * @param impulse_resp impulse response of the combined filter
2253 static void fcb_search(G723_1_Context *p, int16_t *impulse_resp,
2254 int16_t *buf, int index)
2257 int pulse_cnt = pulses[index];
2260 optim.min_err = 1 << 30;
2261 get_fcb_param(&optim, impulse_resp, buf, pulse_cnt, SUBFRAME_LEN);
2263 if (p->pitch_lag[index >> 1] < SUBFRAME_LEN - 2) {
2264 get_fcb_param(&optim, impulse_resp, buf, pulse_cnt,
2265 p->pitch_lag[index >> 1]);
2268 /* Reconstruct the excitation */
2269 memset(buf, 0, sizeof(int16_t) * SUBFRAME_LEN);
2270 for (i = 0; i < pulse_cnt; i++)
2271 buf[optim.pulse_pos[i]] = optim.pulse_sign[i];
2273 pack_fcb_param(&p->subframe[index], &optim, buf, pulse_cnt);
2275 if (optim.dirac_train)
2276 gen_dirac_train(buf, p->pitch_lag[index >> 1]);
2280 * Pack the frame parameters into output bitstream.
2282 * @param frame output buffer
2283 * @param size size of the buffer
2285 static int pack_bitstream(G723_1_Context *p, unsigned char *frame, int size)
2288 int info_bits, i, temp;
2290 init_put_bits(&pb, frame, size);
2292 if (p->cur_rate == RATE_6300) {
2294 put_bits(&pb, 2, info_bits);
2297 put_bits(&pb, 8, p->lsp_index[2]);
2298 put_bits(&pb, 8, p->lsp_index[1]);
2299 put_bits(&pb, 8, p->lsp_index[0]);
2301 put_bits(&pb, 7, p->pitch_lag[0] - PITCH_MIN);
2302 put_bits(&pb, 2, p->subframe[1].ad_cb_lag);
2303 put_bits(&pb, 7, p->pitch_lag[1] - PITCH_MIN);
2304 put_bits(&pb, 2, p->subframe[3].ad_cb_lag);
2306 /* Write 12 bit combined gain */
2307 for (i = 0; i < SUBFRAMES; i++) {
2308 temp = p->subframe[i].ad_cb_gain * GAIN_LEVELS +
2309 p->subframe[i].amp_index;
2310 if (p->cur_rate == RATE_6300)
2311 temp += p->subframe[i].dirac_train << 11;
2312 put_bits(&pb, 12, temp);
2315 put_bits(&pb, 1, p->subframe[0].grid_index);
2316 put_bits(&pb, 1, p->subframe[1].grid_index);
2317 put_bits(&pb, 1, p->subframe[2].grid_index);
2318 put_bits(&pb, 1, p->subframe[3].grid_index);
2320 if (p->cur_rate == RATE_6300) {
2321 skip_put_bits(&pb, 1); /* reserved bit */
2323 /* Write 13 bit combined position index */
2324 temp = (p->subframe[0].pulse_pos >> 16) * 810 +
2325 (p->subframe[1].pulse_pos >> 14) * 90 +
2326 (p->subframe[2].pulse_pos >> 16) * 9 +
2327 (p->subframe[3].pulse_pos >> 14);
2328 put_bits(&pb, 13, temp);
2330 put_bits(&pb, 16, p->subframe[0].pulse_pos & 0xffff);
2331 put_bits(&pb, 14, p->subframe[1].pulse_pos & 0x3fff);
2332 put_bits(&pb, 16, p->subframe[2].pulse_pos & 0xffff);
2333 put_bits(&pb, 14, p->subframe[3].pulse_pos & 0x3fff);
2335 put_bits(&pb, 6, p->subframe[0].pulse_sign);
2336 put_bits(&pb, 5, p->subframe[1].pulse_sign);
2337 put_bits(&pb, 6, p->subframe[2].pulse_sign);
2338 put_bits(&pb, 5, p->subframe[3].pulse_sign);
2341 flush_put_bits(&pb);
2342 return frame_size[info_bits];
2345 static int g723_1_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
2346 const AVFrame *frame, int *got_packet_ptr)
2348 G723_1_Context *p = avctx->priv_data;
2349 int16_t unq_lpc[LPC_ORDER * SUBFRAMES];
2350 int16_t qnt_lpc[LPC_ORDER * SUBFRAMES];
2351 int16_t cur_lsp[LPC_ORDER];
2352 int16_t weighted_lpc[LPC_ORDER * SUBFRAMES << 1];
2353 int16_t vector[FRAME_LEN + PITCH_MAX];
2355 int16_t *in = (const int16_t *)frame->data[0];
2360 highpass_filter(in, &p->hpf_fir_mem, &p->hpf_iir_mem);
2362 memcpy(vector, p->prev_data, HALF_FRAME_LEN * sizeof(int16_t));
2363 memcpy(vector + HALF_FRAME_LEN, in, FRAME_LEN * sizeof(int16_t));
2365 comp_lpc_coeff(vector, unq_lpc);
2366 lpc2lsp(&unq_lpc[LPC_ORDER * 3], p->prev_lsp, cur_lsp);
2367 lsp_quantize(p->lsp_index, cur_lsp, p->prev_lsp);
2370 memcpy(vector + LPC_ORDER, p->prev_data + SUBFRAME_LEN,
2371 sizeof(int16_t) * SUBFRAME_LEN);
2372 memcpy(vector + LPC_ORDER + SUBFRAME_LEN, in,
2373 sizeof(int16_t) * (HALF_FRAME_LEN + SUBFRAME_LEN));
2374 memcpy(p->prev_data, in + HALF_FRAME_LEN,
2375 sizeof(int16_t) * HALF_FRAME_LEN);
2376 memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
2378 perceptual_filter(p, weighted_lpc, unq_lpc, vector);
2380 memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
2381 memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
2382 memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
2384 scale_vector(vector, vector, FRAME_LEN + PITCH_MAX);
2386 p->pitch_lag[0] = estimate_pitch(vector, PITCH_MAX);
2387 p->pitch_lag[1] = estimate_pitch(vector, PITCH_MAX + HALF_FRAME_LEN);
2389 for (i = PITCH_MAX, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
2390 comp_harmonic_coeff(vector + i, p->pitch_lag[j >> 1], hf + j);
2392 memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
2393 memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
2394 memcpy(p->prev_weight_sig, vector + FRAME_LEN, sizeof(int16_t) * PITCH_MAX);
2396 for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
2397 harmonic_filter(hf + j, vector + PITCH_MAX + i, in + i);
2399 inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, 0);
2400 lsp_interpolate(qnt_lpc, cur_lsp, p->prev_lsp);
2402 memcpy(p->prev_lsp, cur_lsp, sizeof(int16_t) * LPC_ORDER);
2405 for (i = 0; i < SUBFRAMES; i++) {
2406 int16_t impulse_resp[SUBFRAME_LEN];
2407 int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
2408 int16_t flt_in[SUBFRAME_LEN];
2409 int16_t zero[LPC_ORDER], fir[LPC_ORDER], iir[LPC_ORDER];
2412 * Compute the combined impulse response of the synthesis filter,
2413 * formant perceptual weighting filter and harmonic noise shaping filter
2415 memset(zero, 0, sizeof(int16_t) * LPC_ORDER);
2416 memset(vector, 0, sizeof(int16_t) * PITCH_MAX);
2417 memset(flt_in, 0, sizeof(int16_t) * SUBFRAME_LEN);
2419 flt_in[0] = 1 << 13; /* Unit impulse */
2420 synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
2421 zero, zero, flt_in, vector + PITCH_MAX, 1);
2422 harmonic_filter(hf + i, vector + PITCH_MAX, impulse_resp);
2424 /* Compute the combined zero input response */
2426 memcpy(fir, p->perf_fir_mem, sizeof(int16_t) * LPC_ORDER);
2427 memcpy(iir, p->perf_iir_mem, sizeof(int16_t) * LPC_ORDER);
2429 synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
2430 fir, iir, flt_in, vector + PITCH_MAX, 0);
2431 memcpy(vector, p->harmonic_mem, sizeof(int16_t) * PITCH_MAX);
2432 harmonic_noise_sub(hf + i, vector + PITCH_MAX, in);
2434 acb_search(p, residual, impulse_resp, in, i);
2435 gen_acb_excitation(residual, p->prev_excitation,p->pitch_lag[i >> 1],
2436 &p->subframe[i], p->cur_rate);
2437 sub_acb_contrib(residual, impulse_resp, in);
2439 fcb_search(p, impulse_resp, in, i);
2441 /* Reconstruct the excitation */
2442 gen_acb_excitation(impulse_resp, p->prev_excitation, p->pitch_lag[i >> 1],
2443 &p->subframe[i], RATE_6300);
2445 memmove(p->prev_excitation, p->prev_excitation + SUBFRAME_LEN,
2446 sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
2447 for (j = 0; j < SUBFRAME_LEN; j++)
2448 in[j] = av_clip_int16((in[j] << 1) + impulse_resp[j]);
2449 memcpy(p->prev_excitation + PITCH_MAX - SUBFRAME_LEN, in,
2450 sizeof(int16_t) * SUBFRAME_LEN);
2452 /* Update filter memories */
2453 synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
2454 p->perf_fir_mem, p->perf_iir_mem,
2455 in, vector + PITCH_MAX, 0);
2456 memmove(p->harmonic_mem, p->harmonic_mem + SUBFRAME_LEN,
2457 sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
2458 memcpy(p->harmonic_mem + PITCH_MAX - SUBFRAME_LEN, vector + PITCH_MAX,
2459 sizeof(int16_t) * SUBFRAME_LEN);
2462 offset += LPC_ORDER;
2465 if ((ret = ff_alloc_packet2(avctx, avpkt, 24)))
2468 *got_packet_ptr = 1;
2469 avpkt->size = pack_bitstream(p, avpkt->data, avpkt->size);
2473 AVCodec ff_g723_1_encoder = {
2475 .type = AVMEDIA_TYPE_AUDIO,
2476 .id = AV_CODEC_ID_G723_1,
2477 .priv_data_size = sizeof(G723_1_Context),
2478 .init = g723_1_encode_init,
2479 .encode2 = g723_1_encode_frame,
2480 .long_name = NULL_IF_CONFIG_SMALL("G.723.1"),
2481 .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,
2482 AV_SAMPLE_FMT_NONE},