2 * G.723.1 compatible encoder
3 * Copyright (c) Mohamed Naufal <naufal22@gmail.com>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * G.723.1 compatible encoder
30 #include "libavutil/channel_layout.h"
31 #include "libavutil/common.h"
32 #include "libavutil/mem.h"
33 #include "libavutil/opt.h"
36 #include "celp_math.h"
40 #define BITSTREAM_WRITER_LE
43 static av_cold int g723_1_encode_init(AVCodecContext *avctx)
45 G723_1_Context *s = avctx->priv_data;
46 G723_1_ChannelContext *p = &s->ch[0];
48 if (avctx->sample_rate != 8000) {
49 av_log(avctx, AV_LOG_ERROR, "Only 8000Hz sample rate supported\n");
50 return AVERROR(EINVAL);
53 if (avctx->channels != 1) {
54 av_log(avctx, AV_LOG_ERROR, "Only mono supported\n");
55 return AVERROR(EINVAL);
58 if (avctx->bit_rate == 6300) {
59 p->cur_rate = RATE_6300;
60 } else if (avctx->bit_rate == 5300) {
61 av_log(avctx, AV_LOG_ERROR, "Use bitrate 6300 instead of 5300.\n");
62 avpriv_report_missing_feature(avctx, "Bitrate 5300");
63 return AVERROR_PATCHWELCOME;
65 av_log(avctx, AV_LOG_ERROR, "Bitrate not supported, use 6300\n");
66 return AVERROR(EINVAL);
68 avctx->frame_size = 240;
69 memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(int16_t));
75 * Remove DC component from the input signal.
77 * @param buf input signal
78 * @param fir zero memory
79 * @param iir pole memory
81 static void highpass_filter(int16_t *buf, int16_t *fir, int *iir)
84 for (i = 0; i < FRAME_LEN; i++) {
85 *iir = (buf[i] << 15) + ((-*fir) << 15) + MULL2(*iir, 0x7f00);
87 buf[i] = av_clipl_int32((int64_t)*iir + (1 << 15)) >> 16;
92 * Estimate autocorrelation of the input vector.
94 * @param buf input buffer
95 * @param autocorr autocorrelation coefficients vector
97 static void comp_autocorr(int16_t *buf, int16_t *autocorr)
100 int16_t vector[LPC_FRAME];
102 ff_g723_1_scale_vector(vector, buf, LPC_FRAME);
104 /* Apply the Hamming window */
105 for (i = 0; i < LPC_FRAME; i++)
106 vector[i] = (vector[i] * hamming_window[i] + (1 << 14)) >> 15;
108 /* Compute the first autocorrelation coefficient */
109 temp = ff_dot_product(vector, vector, LPC_FRAME);
111 /* Apply a white noise correlation factor of (1025/1024) */
115 scale = ff_g723_1_normalize_bits(temp, 31);
116 autocorr[0] = av_clipl_int32((int64_t) (temp << scale) +
119 /* Compute the remaining coefficients */
121 memset(autocorr + 1, 0, LPC_ORDER * sizeof(int16_t));
123 for (i = 1; i <= LPC_ORDER; i++) {
124 temp = ff_dot_product(vector, vector + i, LPC_FRAME - i);
125 temp = MULL2((temp << scale), binomial_window[i - 1]);
126 autocorr[i] = av_clipl_int32((int64_t) temp + (1 << 15)) >> 16;
132 * Use Levinson-Durbin recursion to compute LPC coefficients from
133 * autocorrelation values.
135 * @param lpc LPC coefficients vector
136 * @param autocorr autocorrelation coefficients vector
137 * @param error prediction error
139 static void levinson_durbin(int16_t *lpc, int16_t *autocorr, int16_t error)
141 int16_t vector[LPC_ORDER];
142 int16_t partial_corr;
145 memset(lpc, 0, LPC_ORDER * sizeof(int16_t));
147 for (i = 0; i < LPC_ORDER; i++) {
148 /* Compute the partial correlation coefficient */
150 for (j = 0; j < i; j++)
151 temp -= lpc[j] * autocorr[i - j - 1];
152 temp = ((autocorr[i] << 13) + temp) << 3;
154 if (FFABS(temp) >= (error << 16))
157 partial_corr = temp / (error << 1);
159 lpc[i] = av_clipl_int32((int64_t) (partial_corr << 14) +
162 /* Update the prediction error */
163 temp = MULL2(temp, partial_corr);
164 error = av_clipl_int32((int64_t) (error << 16) - temp +
167 memcpy(vector, lpc, i * sizeof(int16_t));
168 for (j = 0; j < i; j++) {
169 temp = partial_corr * vector[i - j - 1] << 1;
170 lpc[j] = av_clipl_int32((int64_t) (lpc[j] << 16) - temp +
177 * Calculate LPC coefficients for the current frame.
179 * @param buf current frame
180 * @param prev_data 2 trailing subframes of the previous frame
181 * @param lpc LPC coefficients vector
183 static void comp_lpc_coeff(int16_t *buf, int16_t *lpc)
185 int16_t autocorr[(LPC_ORDER + 1) * SUBFRAMES];
186 int16_t *autocorr_ptr = autocorr;
187 int16_t *lpc_ptr = lpc;
190 for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
191 comp_autocorr(buf + i, autocorr_ptr);
192 levinson_durbin(lpc_ptr, autocorr_ptr + 1, autocorr_ptr[0]);
194 lpc_ptr += LPC_ORDER;
195 autocorr_ptr += LPC_ORDER + 1;
199 static void lpc2lsp(int16_t *lpc, int16_t *prev_lsp, int16_t *lsp)
201 int f[LPC_ORDER + 2]; ///< coefficients of the sum and difference
202 ///< polynomials (F1, F2) ordered as
203 ///< f1[0], f2[0], ...., f1[5], f2[5]
205 int max, shift, cur_val, prev_val, count, p;
209 /* Initialize f1[0] and f2[0] to 1 in Q25 */
210 for (i = 0; i < LPC_ORDER; i++)
211 lsp[i] = (lpc[i] * bandwidth_expand[i] + (1 << 14)) >> 15;
213 /* Apply bandwidth expansion on the LPC coefficients */
214 f[0] = f[1] = 1 << 25;
216 /* Compute the remaining coefficients */
217 for (i = 0; i < LPC_ORDER / 2; i++) {
219 f[2 * i + 2] = -f[2 * i] - ((lsp[i] + lsp[LPC_ORDER - 1 - i]) << 12);
221 f[2 * i + 3] = f[2 * i + 1] - ((lsp[i] - lsp[LPC_ORDER - 1 - i]) << 12);
224 /* Divide f1[5] and f2[5] by 2 for use in polynomial evaluation */
226 f[LPC_ORDER + 1] >>= 1;
228 /* Normalize and shorten */
230 for (i = 1; i < LPC_ORDER + 2; i++)
231 max = FFMAX(max, FFABS(f[i]));
233 shift = ff_g723_1_normalize_bits(max, 31);
235 for (i = 0; i < LPC_ORDER + 2; i++)
236 f[i] = av_clipl_int32((int64_t) (f[i] << shift) + (1 << 15)) >> 16;
239 * Evaluate F1 and F2 at uniform intervals of pi/256 along the
240 * unit circle and check for zero crossings.
244 for (i = 0; i <= LPC_ORDER / 2; i++)
245 temp += f[2 * i] * cos_tab[0];
246 prev_val = av_clipl_int32(temp << 1);
248 for (i = 1; i < COS_TBL_SIZE / 2; i++) {
251 for (j = 0; j <= LPC_ORDER / 2; j++)
252 temp += f[LPC_ORDER - 2 * j + p] * cos_tab[i * j % COS_TBL_SIZE];
253 cur_val = av_clipl_int32(temp << 1);
255 /* Check for sign change, indicating a zero crossing */
256 if ((cur_val ^ prev_val) < 0) {
257 int abs_cur = FFABS(cur_val);
258 int abs_prev = FFABS(prev_val);
259 int sum = abs_cur + abs_prev;
261 shift = ff_g723_1_normalize_bits(sum, 31);
263 abs_prev = abs_prev << shift >> 8;
264 lsp[count++] = ((i - 1) << 7) + (abs_prev >> 1) / (sum >> 16);
266 if (count == LPC_ORDER)
269 /* Switch between sum and difference polynomials */
274 for (j = 0; j <= LPC_ORDER / 2; j++)
275 temp += f[LPC_ORDER - 2 * j + p] *
276 cos_tab[i * j % COS_TBL_SIZE];
277 cur_val = av_clipl_int32(temp << 1);
282 if (count != LPC_ORDER)
283 memcpy(lsp, prev_lsp, LPC_ORDER * sizeof(int16_t));
287 * Quantize the current LSP subvector.
289 * @param num band number
290 * @param offset offset of the current subvector in an LPC_ORDER vector
291 * @param size size of the current subvector
293 #define get_index(num, offset, size) \
295 int error, max = -1; \
299 for (i = 0; i < LSP_CB_SIZE; i++) { \
300 for (j = 0; j < size; j++){ \
301 temp[j] = (weight[j + (offset)] * lsp_band##num[i][j] + \
304 error = ff_g723_1_dot_product(lsp + (offset), temp, size) << 1; \
305 error -= ff_g723_1_dot_product(lsp_band##num[i], temp, size); \
308 lsp_index[num] = i; \
314 * Vector quantize the LSP frequencies.
316 * @param lsp the current lsp vector
317 * @param prev_lsp the previous lsp vector
319 static void lsp_quantize(uint8_t *lsp_index, int16_t *lsp, int16_t *prev_lsp)
321 int16_t weight[LPC_ORDER];
325 /* Calculate the VQ weighting vector */
326 weight[0] = (1 << 20) / (lsp[1] - lsp[0]);
327 weight[LPC_ORDER - 1] = (1 << 20) /
328 (lsp[LPC_ORDER - 1] - lsp[LPC_ORDER - 2]);
330 for (i = 1; i < LPC_ORDER - 1; i++) {
331 min = FFMIN(lsp[i] - lsp[i - 1], lsp[i + 1] - lsp[i]);
333 weight[i] = (1 << 20) / min;
335 weight[i] = INT16_MAX;
340 for (i = 0; i < LPC_ORDER; i++)
341 max = FFMAX(weight[i], max);
343 shift = ff_g723_1_normalize_bits(max, 15);
344 for (i = 0; i < LPC_ORDER; i++) {
348 /* Compute the VQ target vector */
349 for (i = 0; i < LPC_ORDER; i++) {
350 lsp[i] -= dc_lsp[i] +
351 (((prev_lsp[i] - dc_lsp[i]) * 12288 + (1 << 14)) >> 15);
360 * Perform IIR filtering.
362 * @param fir_coef FIR coefficients
363 * @param iir_coef IIR coefficients
364 * @param src source vector
365 * @param dest destination vector
367 static void iir_filter(int16_t *fir_coef, int16_t *iir_coef,
368 int16_t *src, int16_t *dest)
372 for (m = 0; m < SUBFRAME_LEN; m++) {
374 for (n = 1; n <= LPC_ORDER; n++) {
375 filter -= fir_coef[n - 1] * src[m - n] -
376 iir_coef[n - 1] * dest[m - n];
379 dest[m] = av_clipl_int32((src[m] << 16) + (filter << 3) +
385 * Apply the formant perceptual weighting filter.
387 * @param flt_coef filter coefficients
388 * @param unq_lpc unquantized lpc vector
390 static void perceptual_filter(G723_1_ChannelContext *p, int16_t *flt_coef,
391 int16_t *unq_lpc, int16_t *buf)
393 int16_t vector[FRAME_LEN + LPC_ORDER];
396 memcpy(buf, p->iir_mem, sizeof(int16_t) * LPC_ORDER);
397 memcpy(vector, p->fir_mem, sizeof(int16_t) * LPC_ORDER);
398 memcpy(vector + LPC_ORDER, buf + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
400 for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
401 for (k = 0; k < LPC_ORDER; k++) {
402 flt_coef[k + 2 * l] = (unq_lpc[k + l] * percept_flt_tbl[0][k] +
404 flt_coef[k + 2 * l + LPC_ORDER] = (unq_lpc[k + l] *
405 percept_flt_tbl[1][k] +
408 iir_filter(flt_coef + 2 * l, flt_coef + 2 * l + LPC_ORDER,
409 vector + i, buf + i);
412 memcpy(p->iir_mem, buf + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
413 memcpy(p->fir_mem, vector + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
417 * Estimate the open loop pitch period.
419 * @param buf perceptually weighted speech
420 * @param start estimation is carried out from this position
422 static int estimate_pitch(int16_t *buf, int start)
425 int max_ccr = 0x4000;
426 int max_eng = 0x7fff;
427 int index = PITCH_MIN;
428 int offset = start - PITCH_MIN + 1;
430 int ccr, eng, orig_eng, ccr_eng, exp;
435 orig_eng = ff_dot_product(buf + offset, buf + offset, HALF_FRAME_LEN);
437 for (i = PITCH_MIN; i <= PITCH_MAX - 3; i++) {
440 /* Update energy and compute correlation */
441 orig_eng += buf[offset] * buf[offset] -
442 buf[offset + HALF_FRAME_LEN] * buf[offset + HALF_FRAME_LEN];
443 ccr = ff_dot_product(buf + start, buf + offset, HALF_FRAME_LEN);
447 /* Split into mantissa and exponent to maintain precision */
448 exp = ff_g723_1_normalize_bits(ccr, 31);
449 ccr = av_clipl_int32((int64_t) (ccr << exp) + (1 << 15)) >> 16;
452 temp = ff_g723_1_normalize_bits(ccr, 31);
453 ccr = ccr << temp >> 16;
456 temp = ff_g723_1_normalize_bits(orig_eng, 31);
457 eng = av_clipl_int32((int64_t) (orig_eng << temp) + (1 << 15)) >> 16;
467 if (exp + 1 < max_exp)
470 /* Equalize exponents before comparison */
471 if (exp + 1 == max_exp)
475 ccr_eng = ccr * max_eng;
476 diff = ccr_eng - eng * temp;
477 if (diff > 0 && (i - index < PITCH_MIN || diff > ccr_eng >> 2)) {
489 * Compute harmonic noise filter parameters.
491 * @param buf perceptually weighted speech
492 * @param pitch_lag open loop pitch period
493 * @param hf harmonic filter parameters
495 static void comp_harmonic_coeff(int16_t *buf, int16_t pitch_lag, HFParam *hf)
497 int ccr, eng, max_ccr, max_eng;
502 for (i = 0, j = pitch_lag - 3; j <= pitch_lag + 3; i++, j++) {
503 /* Compute residual energy */
504 energy[i << 1] = ff_dot_product(buf - j, buf - j, SUBFRAME_LEN);
505 /* Compute correlation */
506 energy[(i << 1) + 1] = ff_dot_product(buf, buf - j, SUBFRAME_LEN);
509 /* Compute target energy */
510 energy[14] = ff_dot_product(buf, buf, SUBFRAME_LEN);
514 for (i = 0; i < 15; i++)
515 max = FFMAX(max, FFABS(energy[i]));
517 exp = ff_g723_1_normalize_bits(max, 31);
518 for (i = 0; i < 15; i++) {
519 energy[i] = av_clipl_int32((int64_t)(energy[i] << exp) +
528 for (i = 0; i <= 6; i++) {
529 eng = energy[i << 1];
530 ccr = energy[(i << 1) + 1];
535 ccr = (ccr * ccr + (1 << 14)) >> 15;
536 diff = ccr * max_eng - eng * max_ccr;
544 if (hf->index == -1) {
545 hf->index = pitch_lag;
549 eng = energy[14] * max_eng;
550 eng = (eng >> 2) + (eng >> 3);
551 ccr = energy[(hf->index << 1) + 1] * energy[(hf->index << 1) + 1];
553 eng = energy[(hf->index << 1) + 1];
558 hf->gain = ((eng << 15) / max_eng * 0x2800 + (1 << 14)) >> 15;
560 hf->index += pitch_lag - 3;
564 * Apply the harmonic noise shaping filter.
566 * @param hf filter parameters
568 static void harmonic_filter(HFParam *hf, const int16_t *src, int16_t *dest)
572 for (i = 0; i < SUBFRAME_LEN; i++) {
573 int64_t temp = hf->gain * src[i - hf->index] << 1;
574 dest[i] = av_clipl_int32((src[i] << 16) - temp + (1 << 15)) >> 16;
578 static void harmonic_noise_sub(HFParam *hf, const int16_t *src, int16_t *dest)
581 for (i = 0; i < SUBFRAME_LEN; i++) {
582 int64_t temp = hf->gain * src[i - hf->index] << 1;
583 dest[i] = av_clipl_int32(((dest[i] - src[i]) << 16) + temp +
589 * Combined synthesis and formant perceptual weighting filer.
591 * @param qnt_lpc quantized lpc coefficients
592 * @param perf_lpc perceptual filter coefficients
593 * @param perf_fir perceptual filter fir memory
594 * @param perf_iir perceptual filter iir memory
595 * @param scale the filter output will be scaled by 2^scale
597 static void synth_percept_filter(int16_t *qnt_lpc, int16_t *perf_lpc,
598 int16_t *perf_fir, int16_t *perf_iir,
599 const int16_t *src, int16_t *dest, int scale)
602 int16_t buf_16[SUBFRAME_LEN + LPC_ORDER];
603 int64_t buf[SUBFRAME_LEN];
605 int16_t *bptr_16 = buf_16 + LPC_ORDER;
607 memcpy(buf_16, perf_fir, sizeof(int16_t) * LPC_ORDER);
608 memcpy(dest - LPC_ORDER, perf_iir, sizeof(int16_t) * LPC_ORDER);
610 for (i = 0; i < SUBFRAME_LEN; i++) {
612 for (j = 1; j <= LPC_ORDER; j++)
613 temp -= qnt_lpc[j - 1] * bptr_16[i - j];
615 buf[i] = (src[i] << 15) + (temp << 3);
616 bptr_16[i] = av_clipl_int32(buf[i] + (1 << 15)) >> 16;
619 for (i = 0; i < SUBFRAME_LEN; i++) {
620 int64_t fir = 0, iir = 0;
621 for (j = 1; j <= LPC_ORDER; j++) {
622 fir -= perf_lpc[j - 1] * bptr_16[i - j];
623 iir += perf_lpc[j + LPC_ORDER - 1] * dest[i - j];
625 dest[i] = av_clipl_int32(((buf[i] + (fir << 3)) << scale) + (iir << 3) +
628 memcpy(perf_fir, buf_16 + SUBFRAME_LEN, sizeof(int16_t) * LPC_ORDER);
629 memcpy(perf_iir, dest + SUBFRAME_LEN - LPC_ORDER,
630 sizeof(int16_t) * LPC_ORDER);
634 * Compute the adaptive codebook contribution.
636 * @param buf input signal
637 * @param index the current subframe index
639 static void acb_search(G723_1_ChannelContext *p, int16_t *residual,
640 int16_t *impulse_resp, const int16_t *buf,
643 int16_t flt_buf[PITCH_ORDER][SUBFRAME_LEN];
645 const int16_t *cb_tbl = adaptive_cb_gain85;
647 int ccr_buf[PITCH_ORDER * SUBFRAMES << 2];
649 int pitch_lag = p->pitch_lag[index >> 1];
652 int odd_frame = index & 1;
653 int iter = 3 + odd_frame;
661 if (pitch_lag == PITCH_MIN)
664 pitch_lag = FFMIN(pitch_lag, PITCH_MAX - 5);
667 for (i = 0; i < iter; i++) {
668 ff_g723_1_get_residual(residual, p->prev_excitation, pitch_lag + i - 1);
670 for (j = 0; j < SUBFRAME_LEN; j++) {
672 for (k = 0; k <= j; k++)
673 temp += residual[PITCH_ORDER - 1 + k] * impulse_resp[j - k];
674 flt_buf[PITCH_ORDER - 1][j] = av_clipl_int32((temp << 1) +
678 for (j = PITCH_ORDER - 2; j >= 0; j--) {
679 flt_buf[j][0] = ((residual[j] << 13) + (1 << 14)) >> 15;
680 for (k = 1; k < SUBFRAME_LEN; k++) {
681 temp = (flt_buf[j + 1][k - 1] << 15) +
682 residual[j] * impulse_resp[k];
683 flt_buf[j][k] = av_clipl_int32((temp << 1) + (1 << 15)) >> 16;
687 /* Compute crosscorrelation with the signal */
688 for (j = 0; j < PITCH_ORDER; j++) {
689 temp = ff_dot_product(buf, flt_buf[j], SUBFRAME_LEN);
690 ccr_buf[count++] = av_clipl_int32(temp << 1);
693 /* Compute energies */
694 for (j = 0; j < PITCH_ORDER; j++) {
695 ccr_buf[count++] = ff_g723_1_dot_product(flt_buf[j], flt_buf[j],
699 for (j = 1; j < PITCH_ORDER; j++) {
700 for (k = 0; k < j; k++) {
701 temp = ff_dot_product(flt_buf[j], flt_buf[k], SUBFRAME_LEN);
702 ccr_buf[count++] = av_clipl_int32(temp << 2);
707 /* Normalize and shorten */
709 for (i = 0; i < 20 * iter; i++)
710 max = FFMAX(max, FFABS(ccr_buf[i]));
712 temp = ff_g723_1_normalize_bits(max, 31);
714 for (i = 0; i < 20 * iter; i++)
715 ccr_buf[i] = av_clipl_int32((int64_t) (ccr_buf[i] << temp) +
719 for (i = 0; i < iter; i++) {
720 /* Select quantization table */
721 if (!odd_frame && pitch_lag + i - 1 >= SUBFRAME_LEN - 2 ||
722 odd_frame && pitch_lag >= SUBFRAME_LEN - 2) {
723 cb_tbl = adaptive_cb_gain170;
727 for (j = 0, k = 0; j < tbl_size; j++, k += 20) {
729 for (l = 0; l < 20; l++)
730 temp += ccr_buf[20 * i + l] * cb_tbl[k + l];
731 temp = av_clipl_int32(temp);
742 pitch_lag += acb_lag - 1;
746 p->pitch_lag[index >> 1] = pitch_lag;
747 p->subframe[index].ad_cb_lag = acb_lag;
748 p->subframe[index].ad_cb_gain = acb_gain;
752 * Subtract the adaptive codebook contribution from the input
753 * to obtain the residual.
755 * @param buf target vector
757 static void sub_acb_contrib(const int16_t *residual, const int16_t *impulse_resp,
761 /* Subtract adaptive CB contribution to obtain the residual */
762 for (i = 0; i < SUBFRAME_LEN; i++) {
763 int64_t temp = buf[i] << 14;
764 for (j = 0; j <= i; j++)
765 temp -= residual[j] * impulse_resp[i - j];
767 buf[i] = av_clipl_int32((temp << 2) + (1 << 15)) >> 16;
772 * Quantize the residual signal using the fixed codebook (MP-MLQ).
774 * @param optim optimized fixed codebook parameters
775 * @param buf excitation vector
777 static void get_fcb_param(FCBParam *optim, int16_t *impulse_resp,
778 int16_t *buf, int pulse_cnt, int pitch_lag)
781 int16_t impulse_r[SUBFRAME_LEN];
782 int16_t temp_corr[SUBFRAME_LEN];
783 int16_t impulse_corr[SUBFRAME_LEN];
785 int ccr1[SUBFRAME_LEN];
786 int ccr2[SUBFRAME_LEN];
787 int amp, err, max, max_amp_index, min, scale, i, j, k, l;
791 /* Update impulse response */
792 memcpy(impulse_r, impulse_resp, sizeof(int16_t) * SUBFRAME_LEN);
793 param.dirac_train = 0;
794 if (pitch_lag < SUBFRAME_LEN - 2) {
795 param.dirac_train = 1;
796 ff_g723_1_gen_dirac_train(impulse_r, pitch_lag);
799 for (i = 0; i < SUBFRAME_LEN; i++)
800 temp_corr[i] = impulse_r[i] >> 1;
802 /* Compute impulse response autocorrelation */
803 temp = ff_g723_1_dot_product(temp_corr, temp_corr, SUBFRAME_LEN);
805 scale = ff_g723_1_normalize_bits(temp, 31);
806 impulse_corr[0] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
808 for (i = 1; i < SUBFRAME_LEN; i++) {
809 temp = ff_g723_1_dot_product(temp_corr + i, temp_corr,
811 impulse_corr[i] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
814 /* Compute crosscorrelation of impulse response with residual signal */
816 for (i = 0; i < SUBFRAME_LEN; i++) {
817 temp = ff_g723_1_dot_product(buf + i, impulse_r, SUBFRAME_LEN - i);
819 ccr1[i] = temp >> -scale;
821 ccr1[i] = av_clipl_int32(temp << scale);
825 for (i = 0; i < GRID_SIZE; i++) {
826 /* Maximize the crosscorrelation */
828 for (j = i; j < SUBFRAME_LEN; j += GRID_SIZE) {
829 temp = FFABS(ccr1[j]);
832 param.pulse_pos[0] = j;
836 /* Quantize the gain (max crosscorrelation/impulse_corr[0]) */
839 max_amp_index = GAIN_LEVELS - 2;
840 for (j = max_amp_index; j >= 2; j--) {
841 temp = av_clipl_int32((int64_t) fixed_cb_gain[j] *
842 impulse_corr[0] << 1);
843 temp = FFABS(temp - amp);
851 /* Select additional gain values */
852 for (j = 1; j < 5; j++) {
853 for (k = i; k < SUBFRAME_LEN; k += GRID_SIZE) {
857 param.amp_index = max_amp_index + j - 2;
858 amp = fixed_cb_gain[param.amp_index];
860 param.pulse_sign[0] = (ccr2[param.pulse_pos[0]] < 0) ? -amp : amp;
861 temp_corr[param.pulse_pos[0]] = 1;
863 for (k = 1; k < pulse_cnt; k++) {
865 for (l = i; l < SUBFRAME_LEN; l += GRID_SIZE) {
868 temp = impulse_corr[FFABS(l - param.pulse_pos[k - 1])];
869 temp = av_clipl_int32((int64_t) temp *
870 param.pulse_sign[k - 1] << 1);
872 temp = FFABS(ccr2[l]);
875 param.pulse_pos[k] = l;
879 param.pulse_sign[k] = (ccr2[param.pulse_pos[k]] < 0) ?
881 temp_corr[param.pulse_pos[k]] = 1;
884 /* Create the error vector */
885 memset(temp_corr, 0, sizeof(int16_t) * SUBFRAME_LEN);
887 for (k = 0; k < pulse_cnt; k++)
888 temp_corr[param.pulse_pos[k]] = param.pulse_sign[k];
890 for (k = SUBFRAME_LEN - 1; k >= 0; k--) {
892 for (l = 0; l <= k; l++) {
893 int prod = av_clipl_int32((int64_t) temp_corr[l] *
894 impulse_r[k - l] << 1);
895 temp = av_clipl_int32(temp + prod);
897 temp_corr[k] = temp << 2 >> 16;
900 /* Compute square of error */
902 for (k = 0; k < SUBFRAME_LEN; k++) {
904 prod = av_clipl_int32((int64_t) buf[k] * temp_corr[k] << 1);
905 err = av_clipl_int32(err - prod);
906 prod = av_clipl_int32((int64_t) temp_corr[k] * temp_corr[k]);
907 err = av_clipl_int32(err + prod);
911 if (err < optim->min_err) {
912 optim->min_err = err;
913 optim->grid_index = i;
914 optim->amp_index = param.amp_index;
915 optim->dirac_train = param.dirac_train;
917 for (k = 0; k < pulse_cnt; k++) {
918 optim->pulse_sign[k] = param.pulse_sign[k];
919 optim->pulse_pos[k] = param.pulse_pos[k];
927 * Encode the pulse position and gain of the current subframe.
929 * @param optim optimized fixed CB parameters
930 * @param buf excitation vector
932 static void pack_fcb_param(G723_1_Subframe *subfrm, FCBParam *optim,
933 int16_t *buf, int pulse_cnt)
937 j = PULSE_MAX - pulse_cnt;
939 subfrm->pulse_sign = 0;
940 subfrm->pulse_pos = 0;
942 for (i = 0; i < SUBFRAME_LEN >> 1; i++) {
943 int val = buf[optim->grid_index + (i << 1)];
945 subfrm->pulse_pos += combinatorial_table[j][i];
947 subfrm->pulse_sign <<= 1;
949 subfrm->pulse_sign++;
956 subfrm->amp_index = optim->amp_index;
957 subfrm->grid_index = optim->grid_index;
958 subfrm->dirac_train = optim->dirac_train;
962 * Compute the fixed codebook excitation.
964 * @param buf target vector
965 * @param impulse_resp impulse response of the combined filter
967 static void fcb_search(G723_1_ChannelContext *p, int16_t *impulse_resp,
968 int16_t *buf, int index)
971 int pulse_cnt = pulses[index];
974 optim.min_err = 1 << 30;
975 get_fcb_param(&optim, impulse_resp, buf, pulse_cnt, SUBFRAME_LEN);
977 if (p->pitch_lag[index >> 1] < SUBFRAME_LEN - 2) {
978 get_fcb_param(&optim, impulse_resp, buf, pulse_cnt,
979 p->pitch_lag[index >> 1]);
982 /* Reconstruct the excitation */
983 memset(buf, 0, sizeof(int16_t) * SUBFRAME_LEN);
984 for (i = 0; i < pulse_cnt; i++)
985 buf[optim.pulse_pos[i]] = optim.pulse_sign[i];
987 pack_fcb_param(&p->subframe[index], &optim, buf, pulse_cnt);
989 if (optim.dirac_train)
990 ff_g723_1_gen_dirac_train(buf, p->pitch_lag[index >> 1]);
994 * Pack the frame parameters into output bitstream.
996 * @param frame output buffer
997 * @param size size of the buffer
999 static int pack_bitstream(G723_1_ChannelContext *p, AVPacket *avpkt)
1005 init_put_bits(&pb, avpkt->data, avpkt->size);
1007 put_bits(&pb, 2, info_bits);
1009 put_bits(&pb, 8, p->lsp_index[2]);
1010 put_bits(&pb, 8, p->lsp_index[1]);
1011 put_bits(&pb, 8, p->lsp_index[0]);
1013 put_bits(&pb, 7, p->pitch_lag[0] - PITCH_MIN);
1014 put_bits(&pb, 2, p->subframe[1].ad_cb_lag);
1015 put_bits(&pb, 7, p->pitch_lag[1] - PITCH_MIN);
1016 put_bits(&pb, 2, p->subframe[3].ad_cb_lag);
1018 /* Write 12 bit combined gain */
1019 for (i = 0; i < SUBFRAMES; i++) {
1020 temp = p->subframe[i].ad_cb_gain * GAIN_LEVELS +
1021 p->subframe[i].amp_index;
1022 if (p->cur_rate == RATE_6300)
1023 temp += p->subframe[i].dirac_train << 11;
1024 put_bits(&pb, 12, temp);
1027 put_bits(&pb, 1, p->subframe[0].grid_index);
1028 put_bits(&pb, 1, p->subframe[1].grid_index);
1029 put_bits(&pb, 1, p->subframe[2].grid_index);
1030 put_bits(&pb, 1, p->subframe[3].grid_index);
1032 if (p->cur_rate == RATE_6300) {
1033 skip_put_bits(&pb, 1); /* reserved bit */
1035 /* Write 13 bit combined position index */
1036 temp = (p->subframe[0].pulse_pos >> 16) * 810 +
1037 (p->subframe[1].pulse_pos >> 14) * 90 +
1038 (p->subframe[2].pulse_pos >> 16) * 9 +
1039 (p->subframe[3].pulse_pos >> 14);
1040 put_bits(&pb, 13, temp);
1042 put_bits(&pb, 16, p->subframe[0].pulse_pos & 0xffff);
1043 put_bits(&pb, 14, p->subframe[1].pulse_pos & 0x3fff);
1044 put_bits(&pb, 16, p->subframe[2].pulse_pos & 0xffff);
1045 put_bits(&pb, 14, p->subframe[3].pulse_pos & 0x3fff);
1047 put_bits(&pb, 6, p->subframe[0].pulse_sign);
1048 put_bits(&pb, 5, p->subframe[1].pulse_sign);
1049 put_bits(&pb, 6, p->subframe[2].pulse_sign);
1050 put_bits(&pb, 5, p->subframe[3].pulse_sign);
1053 flush_put_bits(&pb);
1054 return frame_size[info_bits];
1057 static int g723_1_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1058 const AVFrame *frame, int *got_packet_ptr)
1060 G723_1_Context *s = avctx->priv_data;
1061 G723_1_ChannelContext *p = &s->ch[0];
1062 int16_t unq_lpc[LPC_ORDER * SUBFRAMES];
1063 int16_t qnt_lpc[LPC_ORDER * SUBFRAMES];
1064 int16_t cur_lsp[LPC_ORDER];
1065 int16_t weighted_lpc[LPC_ORDER * SUBFRAMES << 1];
1066 int16_t vector[FRAME_LEN + PITCH_MAX];
1067 int offset, ret, i, j;
1068 int16_t *in, *start;
1071 /* duplicate input */
1072 start = in = av_malloc(frame->nb_samples * sizeof(int16_t));
1074 return AVERROR(ENOMEM);
1075 memcpy(in, frame->data[0], frame->nb_samples * sizeof(int16_t));
1077 highpass_filter(in, &p->hpf_fir_mem, &p->hpf_iir_mem);
1079 memcpy(vector, p->prev_data, HALF_FRAME_LEN * sizeof(int16_t));
1080 memcpy(vector + HALF_FRAME_LEN, in, FRAME_LEN * sizeof(int16_t));
1082 comp_lpc_coeff(vector, unq_lpc);
1083 lpc2lsp(&unq_lpc[LPC_ORDER * 3], p->prev_lsp, cur_lsp);
1084 lsp_quantize(p->lsp_index, cur_lsp, p->prev_lsp);
1087 memcpy(vector + LPC_ORDER, p->prev_data + SUBFRAME_LEN,
1088 sizeof(int16_t) * SUBFRAME_LEN);
1089 memcpy(vector + LPC_ORDER + SUBFRAME_LEN, in,
1090 sizeof(int16_t) * (HALF_FRAME_LEN + SUBFRAME_LEN));
1091 memcpy(p->prev_data, in + HALF_FRAME_LEN,
1092 sizeof(int16_t) * HALF_FRAME_LEN);
1093 memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
1095 perceptual_filter(p, weighted_lpc, unq_lpc, vector);
1097 memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
1098 memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
1099 memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
1101 ff_g723_1_scale_vector(vector, vector, FRAME_LEN + PITCH_MAX);
1103 p->pitch_lag[0] = estimate_pitch(vector, PITCH_MAX);
1104 p->pitch_lag[1] = estimate_pitch(vector, PITCH_MAX + HALF_FRAME_LEN);
1106 for (i = PITCH_MAX, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1107 comp_harmonic_coeff(vector + i, p->pitch_lag[j >> 1], hf + j);
1109 memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
1110 memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
1111 memcpy(p->prev_weight_sig, vector + FRAME_LEN, sizeof(int16_t) * PITCH_MAX);
1113 for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1114 harmonic_filter(hf + j, vector + PITCH_MAX + i, in + i);
1116 ff_g723_1_inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, 0);
1117 ff_g723_1_lsp_interpolate(qnt_lpc, cur_lsp, p->prev_lsp);
1119 memcpy(p->prev_lsp, cur_lsp, sizeof(int16_t) * LPC_ORDER);
1122 for (i = 0; i < SUBFRAMES; i++) {
1123 int16_t impulse_resp[SUBFRAME_LEN];
1124 int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
1125 int16_t flt_in[SUBFRAME_LEN];
1126 int16_t zero[LPC_ORDER], fir[LPC_ORDER], iir[LPC_ORDER];
1129 * Compute the combined impulse response of the synthesis filter,
1130 * formant perceptual weighting filter and harmonic noise shaping filter
1132 memset(zero, 0, sizeof(int16_t) * LPC_ORDER);
1133 memset(vector, 0, sizeof(int16_t) * PITCH_MAX);
1134 memset(flt_in, 0, sizeof(int16_t) * SUBFRAME_LEN);
1136 flt_in[0] = 1 << 13; /* Unit impulse */
1137 synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
1138 zero, zero, flt_in, vector + PITCH_MAX, 1);
1139 harmonic_filter(hf + i, vector + PITCH_MAX, impulse_resp);
1141 /* Compute the combined zero input response */
1143 memcpy(fir, p->perf_fir_mem, sizeof(int16_t) * LPC_ORDER);
1144 memcpy(iir, p->perf_iir_mem, sizeof(int16_t) * LPC_ORDER);
1146 synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
1147 fir, iir, flt_in, vector + PITCH_MAX, 0);
1148 memcpy(vector, p->harmonic_mem, sizeof(int16_t) * PITCH_MAX);
1149 harmonic_noise_sub(hf + i, vector + PITCH_MAX, in);
1151 acb_search(p, residual, impulse_resp, in, i);
1152 ff_g723_1_gen_acb_excitation(residual, p->prev_excitation,
1153 p->pitch_lag[i >> 1], &p->subframe[i],
1155 sub_acb_contrib(residual, impulse_resp, in);
1157 fcb_search(p, impulse_resp, in, i);
1159 /* Reconstruct the excitation */
1160 ff_g723_1_gen_acb_excitation(impulse_resp, p->prev_excitation,
1161 p->pitch_lag[i >> 1], &p->subframe[i],
1164 memmove(p->prev_excitation, p->prev_excitation + SUBFRAME_LEN,
1165 sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
1166 for (j = 0; j < SUBFRAME_LEN; j++)
1167 in[j] = av_clip_int16((in[j] << 1) + impulse_resp[j]);
1168 memcpy(p->prev_excitation + PITCH_MAX - SUBFRAME_LEN, in,
1169 sizeof(int16_t) * SUBFRAME_LEN);
1171 /* Update filter memories */
1172 synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
1173 p->perf_fir_mem, p->perf_iir_mem,
1174 in, vector + PITCH_MAX, 0);
1175 memmove(p->harmonic_mem, p->harmonic_mem + SUBFRAME_LEN,
1176 sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
1177 memcpy(p->harmonic_mem + PITCH_MAX - SUBFRAME_LEN, vector + PITCH_MAX,
1178 sizeof(int16_t) * SUBFRAME_LEN);
1181 offset += LPC_ORDER;
1186 if ((ret = ff_alloc_packet2(avctx, avpkt, 24, 0)) < 0)
1189 *got_packet_ptr = 1;
1190 avpkt->size = pack_bitstream(p, avpkt);
1194 static const AVCodecDefault defaults[] = {
1199 AVCodec ff_g723_1_encoder = {
1201 .long_name = NULL_IF_CONFIG_SMALL("G.723.1"),
1202 .type = AVMEDIA_TYPE_AUDIO,
1203 .id = AV_CODEC_ID_G723_1,
1204 .priv_data_size = sizeof(G723_1_Context),
1205 .init = g723_1_encode_init,
1206 .encode2 = g723_1_encode_frame,
1207 .defaults = defaults,
1208 .sample_fmts = (const enum AVSampleFormat[]) {
1209 AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE