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
44 * Hamming window coefficients scaled by 2^15
46 static const int16_t hamming_window[LPC_FRAME] = {
47 2621, 2631, 2659, 2705, 2770, 2853, 2955, 3074, 3212, 3367,
48 3541, 3731, 3939, 4164, 4405, 4663, 4937, 5226, 5531, 5851,
49 6186, 6534, 6897, 7273, 7661, 8062, 8475, 8899, 9334, 9780,
50 10235, 10699, 11172, 11653, 12141, 12636, 13138, 13645, 14157, 14673,
51 15193, 15716, 16242, 16769, 17298, 17827, 18356, 18884, 19411, 19935,
52 20457, 20975, 21489, 21999, 22503, 23002, 23494, 23978, 24455, 24924,
53 25384, 25834, 26274, 26704, 27122, 27529, 27924, 28306, 28675, 29031,
54 29373, 29700, 30012, 30310, 30592, 30857, 31107, 31340, 31557, 31756,
55 31938, 32102, 32249, 32377, 32488, 32580, 32654, 32710, 32747, 32766,
56 32766, 32747, 32710, 32654, 32580, 32488, 32377, 32249, 32102, 31938,
57 31756, 31557, 31340, 31107, 30857, 30592, 30310, 30012, 29700, 29373,
58 29031, 28675, 28306, 27924, 27529, 27122, 26704, 26274, 25834, 25384,
59 24924, 24455, 23978, 23494, 23002, 22503, 21999, 21489, 20975, 20457,
60 19935, 19411, 18884, 18356, 17827, 17298, 16769, 16242, 15716, 15193,
61 14673, 14157, 13645, 13138, 12636, 12141, 11653, 11172, 10699, 10235,
62 9780, 9334, 8899, 8475, 8062, 7661, 7273, 6897, 6534, 6186,
63 5851, 5531, 5226, 4937, 4663, 4405, 4164, 3939, 3731, 3541,
64 3367, 3212, 3074, 2955, 2853, 2770, 2705, 2659, 2631, 2621
68 * Binomial window coefficients scaled by 2^15
70 static const int16_t binomial_window[LPC_ORDER] = {
71 32749, 32695, 32604, 32477, 32315, 32118, 31887, 31622, 31324, 30995
75 * 0.994^i scaled by 2^15
77 static const int16_t bandwidth_expand[LPC_ORDER] = {
78 32571, 32376, 32182, 31989, 31797, 31606, 31416, 31228, 31040, 30854
82 * 0.5^i scaled by 2^15
84 static const int16_t percept_flt_tbl[2][LPC_ORDER] = {
86 {29491, 26542, 23888, 21499, 19349, 17414, 15673, 14106, 12695, 11425},
88 {16384, 8192, 4096, 2048, 1024, 512, 256, 128, 64, 32}
91 static av_cold int g723_1_encode_init(AVCodecContext *avctx)
93 G723_1_Context *s = avctx->priv_data;
94 G723_1_ChannelContext *p = &s->ch[0];
96 if (avctx->sample_rate != 8000) {
97 av_log(avctx, AV_LOG_ERROR, "Only 8000Hz sample rate supported\n");
98 return AVERROR(EINVAL);
101 if (avctx->channels != 1) {
102 av_log(avctx, AV_LOG_ERROR, "Only mono supported\n");
103 return AVERROR(EINVAL);
106 if (avctx->bit_rate == 6300) {
107 p->cur_rate = RATE_6300;
108 } else if (avctx->bit_rate == 5300) {
109 av_log(avctx, AV_LOG_ERROR, "Use bitrate 6300 instead of 5300.\n");
110 avpriv_report_missing_feature(avctx, "Bitrate 5300");
111 return AVERROR_PATCHWELCOME;
113 av_log(avctx, AV_LOG_ERROR, "Bitrate not supported, use 6300\n");
114 return AVERROR(EINVAL);
116 avctx->frame_size = 240;
117 memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(int16_t));
123 * Remove DC component from the input signal.
125 * @param buf input signal
126 * @param fir zero memory
127 * @param iir pole memory
129 static void highpass_filter(int16_t *buf, int16_t *fir, int *iir)
132 for (i = 0; i < FRAME_LEN; i++) {
133 *iir = (buf[i] << 15) + ((-*fir) << 15) + MULL2(*iir, 0x7f00);
135 buf[i] = av_clipl_int32((int64_t)*iir + (1 << 15)) >> 16;
140 * Estimate autocorrelation of the input vector.
142 * @param buf input buffer
143 * @param autocorr autocorrelation coefficients vector
145 static void comp_autocorr(int16_t *buf, int16_t *autocorr)
148 int16_t vector[LPC_FRAME];
150 ff_g723_1_scale_vector(vector, buf, LPC_FRAME);
152 /* Apply the Hamming window */
153 for (i = 0; i < LPC_FRAME; i++)
154 vector[i] = (vector[i] * hamming_window[i] + (1 << 14)) >> 15;
156 /* Compute the first autocorrelation coefficient */
157 temp = ff_dot_product(vector, vector, LPC_FRAME);
159 /* Apply a white noise correlation factor of (1025/1024) */
163 scale = ff_g723_1_normalize_bits(temp, 31);
164 autocorr[0] = av_clipl_int32((int64_t) (temp << scale) +
167 /* Compute the remaining coefficients */
169 memset(autocorr + 1, 0, LPC_ORDER * sizeof(int16_t));
171 for (i = 1; i <= LPC_ORDER; i++) {
172 temp = ff_dot_product(vector, vector + i, LPC_FRAME - i);
173 temp = MULL2((temp << scale), binomial_window[i - 1]);
174 autocorr[i] = av_clipl_int32((int64_t) temp + (1 << 15)) >> 16;
180 * Use Levinson-Durbin recursion to compute LPC coefficients from
181 * autocorrelation values.
183 * @param lpc LPC coefficients vector
184 * @param autocorr autocorrelation coefficients vector
185 * @param error prediction error
187 static void levinson_durbin(int16_t *lpc, int16_t *autocorr, int16_t error)
189 int16_t vector[LPC_ORDER];
190 int16_t partial_corr;
193 memset(lpc, 0, LPC_ORDER * sizeof(int16_t));
195 for (i = 0; i < LPC_ORDER; i++) {
196 /* Compute the partial correlation coefficient */
198 for (j = 0; j < i; j++)
199 temp -= lpc[j] * autocorr[i - j - 1];
200 temp = ((autocorr[i] << 13) + temp) << 3;
202 if (FFABS(temp) >= (error << 16))
205 partial_corr = temp / (error << 1);
207 lpc[i] = av_clipl_int32((int64_t) (partial_corr << 14) +
210 /* Update the prediction error */
211 temp = MULL2(temp, partial_corr);
212 error = av_clipl_int32((int64_t) (error << 16) - temp +
215 memcpy(vector, lpc, i * sizeof(int16_t));
216 for (j = 0; j < i; j++) {
217 temp = partial_corr * vector[i - j - 1] << 1;
218 lpc[j] = av_clipl_int32((int64_t) (lpc[j] << 16) - temp +
225 * Calculate LPC coefficients for the current frame.
227 * @param buf current frame
228 * @param prev_data 2 trailing subframes of the previous frame
229 * @param lpc LPC coefficients vector
231 static void comp_lpc_coeff(int16_t *buf, int16_t *lpc)
233 int16_t autocorr[(LPC_ORDER + 1) * SUBFRAMES];
234 int16_t *autocorr_ptr = autocorr;
235 int16_t *lpc_ptr = lpc;
238 for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
239 comp_autocorr(buf + i, autocorr_ptr);
240 levinson_durbin(lpc_ptr, autocorr_ptr + 1, autocorr_ptr[0]);
242 lpc_ptr += LPC_ORDER;
243 autocorr_ptr += LPC_ORDER + 1;
247 static void lpc2lsp(int16_t *lpc, int16_t *prev_lsp, int16_t *lsp)
249 int f[LPC_ORDER + 2]; ///< coefficients of the sum and difference
250 ///< polynomials (F1, F2) ordered as
251 ///< f1[0], f2[0], ...., f1[5], f2[5]
253 int max, shift, cur_val, prev_val, count, p;
257 /* Initialize f1[0] and f2[0] to 1 in Q25 */
258 for (i = 0; i < LPC_ORDER; i++)
259 lsp[i] = (lpc[i] * bandwidth_expand[i] + (1 << 14)) >> 15;
261 /* Apply bandwidth expansion on the LPC coefficients */
262 f[0] = f[1] = 1 << 25;
264 /* Compute the remaining coefficients */
265 for (i = 0; i < LPC_ORDER / 2; i++) {
267 f[2 * i + 2] = -f[2 * i] - ((lsp[i] + lsp[LPC_ORDER - 1 - i]) << 12);
269 f[2 * i + 3] = f[2 * i + 1] - ((lsp[i] - lsp[LPC_ORDER - 1 - i]) << 12);
272 /* Divide f1[5] and f2[5] by 2 for use in polynomial evaluation */
274 f[LPC_ORDER + 1] >>= 1;
276 /* Normalize and shorten */
278 for (i = 1; i < LPC_ORDER + 2; i++)
279 max = FFMAX(max, FFABS(f[i]));
281 shift = ff_g723_1_normalize_bits(max, 31);
283 for (i = 0; i < LPC_ORDER + 2; i++)
284 f[i] = av_clipl_int32((int64_t) (f[i] << shift) + (1 << 15)) >> 16;
287 * Evaluate F1 and F2 at uniform intervals of pi/256 along the
288 * unit circle and check for zero crossings.
292 for (i = 0; i <= LPC_ORDER / 2; i++)
293 temp += f[2 * i] * G723_1_COS_TAB_FIRST_ELEMENT;
294 prev_val = av_clipl_int32(temp << 1);
296 for (i = 1; i < COS_TBL_SIZE / 2; i++) {
299 for (j = 0; j <= LPC_ORDER / 2; j++)
300 temp += f[LPC_ORDER - 2 * j + p] * ff_g723_1_cos_tab[i * j % COS_TBL_SIZE];
301 cur_val = av_clipl_int32(temp << 1);
303 /* Check for sign change, indicating a zero crossing */
304 if ((cur_val ^ prev_val) < 0) {
305 int abs_cur = FFABS(cur_val);
306 int abs_prev = FFABS(prev_val);
307 int sum = abs_cur + abs_prev;
309 shift = ff_g723_1_normalize_bits(sum, 31);
311 abs_prev = abs_prev << shift >> 8;
312 lsp[count++] = ((i - 1) << 7) + (abs_prev >> 1) / (sum >> 16);
314 if (count == LPC_ORDER)
317 /* Switch between sum and difference polynomials */
322 for (j = 0; j <= LPC_ORDER / 2; j++)
323 temp += f[LPC_ORDER - 2 * j + p] *
324 ff_g723_1_cos_tab[i * j % COS_TBL_SIZE];
325 cur_val = av_clipl_int32(temp << 1);
330 if (count != LPC_ORDER)
331 memcpy(lsp, prev_lsp, LPC_ORDER * sizeof(int16_t));
335 * Quantize the current LSP subvector.
337 * @param num band number
338 * @param offset offset of the current subvector in an LPC_ORDER vector
339 * @param size size of the current subvector
341 #define get_index(num, offset, size) \
343 int error, max = -1; \
347 for (i = 0; i < LSP_CB_SIZE; i++) { \
348 for (j = 0; j < size; j++){ \
349 temp[j] = (weight[j + (offset)] * ff_g723_1_lsp_band##num[i][j] + \
352 error = ff_g723_1_dot_product(lsp + (offset), temp, size) << 1; \
353 error -= ff_g723_1_dot_product(ff_g723_1_lsp_band##num[i], temp, size); \
356 lsp_index[num] = i; \
362 * Vector quantize the LSP frequencies.
364 * @param lsp the current lsp vector
365 * @param prev_lsp the previous lsp vector
367 static void lsp_quantize(uint8_t *lsp_index, int16_t *lsp, int16_t *prev_lsp)
369 int16_t weight[LPC_ORDER];
373 /* Calculate the VQ weighting vector */
374 weight[0] = (1 << 20) / (lsp[1] - lsp[0]);
375 weight[LPC_ORDER - 1] = (1 << 20) /
376 (lsp[LPC_ORDER - 1] - lsp[LPC_ORDER - 2]);
378 for (i = 1; i < LPC_ORDER - 1; i++) {
379 min = FFMIN(lsp[i] - lsp[i - 1], lsp[i + 1] - lsp[i]);
381 weight[i] = (1 << 20) / min;
383 weight[i] = INT16_MAX;
388 for (i = 0; i < LPC_ORDER; i++)
389 max = FFMAX(weight[i], max);
391 shift = ff_g723_1_normalize_bits(max, 15);
392 for (i = 0; i < LPC_ORDER; i++) {
396 /* Compute the VQ target vector */
397 for (i = 0; i < LPC_ORDER; i++) {
398 lsp[i] -= dc_lsp[i] +
399 (((prev_lsp[i] - dc_lsp[i]) * 12288 + (1 << 14)) >> 15);
408 * Perform IIR filtering.
410 * @param fir_coef FIR coefficients
411 * @param iir_coef IIR coefficients
412 * @param src source vector
413 * @param dest destination vector
415 static void iir_filter(int16_t *fir_coef, int16_t *iir_coef,
416 int16_t *src, int16_t *dest)
420 for (m = 0; m < SUBFRAME_LEN; m++) {
422 for (n = 1; n <= LPC_ORDER; n++) {
423 filter -= fir_coef[n - 1] * src[m - n] -
424 iir_coef[n - 1] * dest[m - n];
427 dest[m] = av_clipl_int32((src[m] << 16) + (filter << 3) +
433 * Apply the formant perceptual weighting filter.
435 * @param flt_coef filter coefficients
436 * @param unq_lpc unquantized lpc vector
438 static void perceptual_filter(G723_1_ChannelContext *p, int16_t *flt_coef,
439 int16_t *unq_lpc, int16_t *buf)
441 int16_t vector[FRAME_LEN + LPC_ORDER];
444 memcpy(buf, p->iir_mem, sizeof(int16_t) * LPC_ORDER);
445 memcpy(vector, p->fir_mem, sizeof(int16_t) * LPC_ORDER);
446 memcpy(vector + LPC_ORDER, buf + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
448 for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
449 for (k = 0; k < LPC_ORDER; k++) {
450 flt_coef[k + 2 * l] = (unq_lpc[k + l] * percept_flt_tbl[0][k] +
452 flt_coef[k + 2 * l + LPC_ORDER] = (unq_lpc[k + l] *
453 percept_flt_tbl[1][k] +
456 iir_filter(flt_coef + 2 * l, flt_coef + 2 * l + LPC_ORDER,
457 vector + i, buf + i);
460 memcpy(p->iir_mem, buf + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
461 memcpy(p->fir_mem, vector + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
465 * Estimate the open loop pitch period.
467 * @param buf perceptually weighted speech
468 * @param start estimation is carried out from this position
470 static int estimate_pitch(int16_t *buf, int start)
473 int max_ccr = 0x4000;
474 int max_eng = 0x7fff;
475 int index = PITCH_MIN;
476 int offset = start - PITCH_MIN + 1;
478 int ccr, eng, orig_eng, ccr_eng, exp;
483 orig_eng = ff_dot_product(buf + offset, buf + offset, HALF_FRAME_LEN);
485 for (i = PITCH_MIN; i <= PITCH_MAX - 3; i++) {
488 /* Update energy and compute correlation */
489 orig_eng += buf[offset] * buf[offset] -
490 buf[offset + HALF_FRAME_LEN] * buf[offset + HALF_FRAME_LEN];
491 ccr = ff_dot_product(buf + start, buf + offset, HALF_FRAME_LEN);
495 /* Split into mantissa and exponent to maintain precision */
496 exp = ff_g723_1_normalize_bits(ccr, 31);
497 ccr = av_clipl_int32((int64_t) (ccr << exp) + (1 << 15)) >> 16;
500 temp = ff_g723_1_normalize_bits(ccr, 31);
501 ccr = ccr << temp >> 16;
504 temp = ff_g723_1_normalize_bits(orig_eng, 31);
505 eng = av_clipl_int32((int64_t) (orig_eng << temp) + (1 << 15)) >> 16;
515 if (exp + 1 < max_exp)
518 /* Equalize exponents before comparison */
519 if (exp + 1 == max_exp)
523 ccr_eng = ccr * max_eng;
524 diff = ccr_eng - eng * temp;
525 if (diff > 0 && (i - index < PITCH_MIN || diff > ccr_eng >> 2)) {
537 * Compute harmonic noise filter parameters.
539 * @param buf perceptually weighted speech
540 * @param pitch_lag open loop pitch period
541 * @param hf harmonic filter parameters
543 static void comp_harmonic_coeff(int16_t *buf, int16_t pitch_lag, HFParam *hf)
545 int ccr, eng, max_ccr, max_eng;
550 for (i = 0, j = pitch_lag - 3; j <= pitch_lag + 3; i++, j++) {
551 /* Compute residual energy */
552 energy[i << 1] = ff_dot_product(buf - j, buf - j, SUBFRAME_LEN);
553 /* Compute correlation */
554 energy[(i << 1) + 1] = ff_dot_product(buf, buf - j, SUBFRAME_LEN);
557 /* Compute target energy */
558 energy[14] = ff_dot_product(buf, buf, SUBFRAME_LEN);
562 for (i = 0; i < 15; i++)
563 max = FFMAX(max, FFABS(energy[i]));
565 exp = ff_g723_1_normalize_bits(max, 31);
566 for (i = 0; i < 15; i++) {
567 energy[i] = av_clipl_int32((int64_t)(energy[i] << exp) +
576 for (i = 0; i <= 6; i++) {
577 eng = energy[i << 1];
578 ccr = energy[(i << 1) + 1];
583 ccr = (ccr * ccr + (1 << 14)) >> 15;
584 diff = ccr * max_eng - eng * max_ccr;
592 if (hf->index == -1) {
593 hf->index = pitch_lag;
597 eng = energy[14] * max_eng;
598 eng = (eng >> 2) + (eng >> 3);
599 ccr = energy[(hf->index << 1) + 1] * energy[(hf->index << 1) + 1];
601 eng = energy[(hf->index << 1) + 1];
606 hf->gain = ((eng << 15) / max_eng * 0x2800 + (1 << 14)) >> 15;
608 hf->index += pitch_lag - 3;
612 * Apply the harmonic noise shaping filter.
614 * @param hf filter parameters
616 static void harmonic_filter(HFParam *hf, const int16_t *src, int16_t *dest)
620 for (i = 0; i < SUBFRAME_LEN; i++) {
621 int64_t temp = hf->gain * src[i - hf->index] << 1;
622 dest[i] = av_clipl_int32((src[i] << 16) - temp + (1 << 15)) >> 16;
626 static void harmonic_noise_sub(HFParam *hf, const int16_t *src, int16_t *dest)
629 for (i = 0; i < SUBFRAME_LEN; i++) {
630 int64_t temp = hf->gain * src[i - hf->index] << 1;
631 dest[i] = av_clipl_int32(((dest[i] - src[i]) << 16) + temp +
637 * Combined synthesis and formant perceptual weighting filer.
639 * @param qnt_lpc quantized lpc coefficients
640 * @param perf_lpc perceptual filter coefficients
641 * @param perf_fir perceptual filter fir memory
642 * @param perf_iir perceptual filter iir memory
643 * @param scale the filter output will be scaled by 2^scale
645 static void synth_percept_filter(int16_t *qnt_lpc, int16_t *perf_lpc,
646 int16_t *perf_fir, int16_t *perf_iir,
647 const int16_t *src, int16_t *dest, int scale)
650 int16_t buf_16[SUBFRAME_LEN + LPC_ORDER];
651 int64_t buf[SUBFRAME_LEN];
653 int16_t *bptr_16 = buf_16 + LPC_ORDER;
655 memcpy(buf_16, perf_fir, sizeof(int16_t) * LPC_ORDER);
656 memcpy(dest - LPC_ORDER, perf_iir, sizeof(int16_t) * LPC_ORDER);
658 for (i = 0; i < SUBFRAME_LEN; i++) {
660 for (j = 1; j <= LPC_ORDER; j++)
661 temp -= qnt_lpc[j - 1] * bptr_16[i - j];
663 buf[i] = (src[i] << 15) + (temp << 3);
664 bptr_16[i] = av_clipl_int32(buf[i] + (1 << 15)) >> 16;
667 for (i = 0; i < SUBFRAME_LEN; i++) {
668 int64_t fir = 0, iir = 0;
669 for (j = 1; j <= LPC_ORDER; j++) {
670 fir -= perf_lpc[j - 1] * bptr_16[i - j];
671 iir += perf_lpc[j + LPC_ORDER - 1] * dest[i - j];
673 dest[i] = av_clipl_int32(((buf[i] + (fir << 3)) << scale) + (iir << 3) +
676 memcpy(perf_fir, buf_16 + SUBFRAME_LEN, sizeof(int16_t) * LPC_ORDER);
677 memcpy(perf_iir, dest + SUBFRAME_LEN - LPC_ORDER,
678 sizeof(int16_t) * LPC_ORDER);
682 * Compute the adaptive codebook contribution.
684 * @param buf input signal
685 * @param index the current subframe index
687 static void acb_search(G723_1_ChannelContext *p, int16_t *residual,
688 int16_t *impulse_resp, const int16_t *buf,
691 int16_t flt_buf[PITCH_ORDER][SUBFRAME_LEN];
693 const int16_t *cb_tbl = ff_g723_1_adaptive_cb_gain85;
695 int ccr_buf[PITCH_ORDER * SUBFRAMES << 2];
697 int pitch_lag = p->pitch_lag[index >> 1];
700 int odd_frame = index & 1;
701 int iter = 3 + odd_frame;
709 if (pitch_lag == PITCH_MIN)
712 pitch_lag = FFMIN(pitch_lag, PITCH_MAX - 5);
715 for (i = 0; i < iter; i++) {
716 ff_g723_1_get_residual(residual, p->prev_excitation, pitch_lag + i - 1);
718 for (j = 0; j < SUBFRAME_LEN; j++) {
720 for (k = 0; k <= j; k++)
721 temp += residual[PITCH_ORDER - 1 + k] * impulse_resp[j - k];
722 flt_buf[PITCH_ORDER - 1][j] = av_clipl_int32((temp << 1) +
726 for (j = PITCH_ORDER - 2; j >= 0; j--) {
727 flt_buf[j][0] = ((residual[j] << 13) + (1 << 14)) >> 15;
728 for (k = 1; k < SUBFRAME_LEN; k++) {
729 temp = (flt_buf[j + 1][k - 1] << 15) +
730 residual[j] * impulse_resp[k];
731 flt_buf[j][k] = av_clipl_int32((temp << 1) + (1 << 15)) >> 16;
735 /* Compute crosscorrelation with the signal */
736 for (j = 0; j < PITCH_ORDER; j++) {
737 temp = ff_dot_product(buf, flt_buf[j], SUBFRAME_LEN);
738 ccr_buf[count++] = av_clipl_int32(temp << 1);
741 /* Compute energies */
742 for (j = 0; j < PITCH_ORDER; j++) {
743 ccr_buf[count++] = ff_g723_1_dot_product(flt_buf[j], flt_buf[j],
747 for (j = 1; j < PITCH_ORDER; j++) {
748 for (k = 0; k < j; k++) {
749 temp = ff_dot_product(flt_buf[j], flt_buf[k], SUBFRAME_LEN);
750 ccr_buf[count++] = av_clipl_int32(temp << 2);
755 /* Normalize and shorten */
757 for (i = 0; i < 20 * iter; i++)
758 max = FFMAX(max, FFABS(ccr_buf[i]));
760 temp = ff_g723_1_normalize_bits(max, 31);
762 for (i = 0; i < 20 * iter; i++)
763 ccr_buf[i] = av_clipl_int32((int64_t) (ccr_buf[i] << temp) +
767 for (i = 0; i < iter; i++) {
768 /* Select quantization table */
769 if (!odd_frame && pitch_lag + i - 1 >= SUBFRAME_LEN - 2 ||
770 odd_frame && pitch_lag >= SUBFRAME_LEN - 2) {
771 cb_tbl = ff_g723_1_adaptive_cb_gain170;
775 for (j = 0, k = 0; j < tbl_size; j++, k += 20) {
777 for (l = 0; l < 20; l++)
778 temp += ccr_buf[20 * i + l] * cb_tbl[k + l];
779 temp = av_clipl_int32(temp);
790 pitch_lag += acb_lag - 1;
794 p->pitch_lag[index >> 1] = pitch_lag;
795 p->subframe[index].ad_cb_lag = acb_lag;
796 p->subframe[index].ad_cb_gain = acb_gain;
800 * Subtract the adaptive codebook contribution from the input
801 * to obtain the residual.
803 * @param buf target vector
805 static void sub_acb_contrib(const int16_t *residual, const int16_t *impulse_resp,
809 /* Subtract adaptive CB contribution to obtain the residual */
810 for (i = 0; i < SUBFRAME_LEN; i++) {
811 int64_t temp = buf[i] << 14;
812 for (j = 0; j <= i; j++)
813 temp -= residual[j] * impulse_resp[i - j];
815 buf[i] = av_clipl_int32((temp << 2) + (1 << 15)) >> 16;
820 * Quantize the residual signal using the fixed codebook (MP-MLQ).
822 * @param optim optimized fixed codebook parameters
823 * @param buf excitation vector
825 static void get_fcb_param(FCBParam *optim, int16_t *impulse_resp,
826 int16_t *buf, int pulse_cnt, int pitch_lag)
829 int16_t impulse_r[SUBFRAME_LEN];
830 int16_t temp_corr[SUBFRAME_LEN];
831 int16_t impulse_corr[SUBFRAME_LEN];
833 int ccr1[SUBFRAME_LEN];
834 int ccr2[SUBFRAME_LEN];
835 int amp, err, max, max_amp_index, min, scale, i, j, k, l;
839 /* Update impulse response */
840 memcpy(impulse_r, impulse_resp, sizeof(int16_t) * SUBFRAME_LEN);
841 param.dirac_train = 0;
842 if (pitch_lag < SUBFRAME_LEN - 2) {
843 param.dirac_train = 1;
844 ff_g723_1_gen_dirac_train(impulse_r, pitch_lag);
847 for (i = 0; i < SUBFRAME_LEN; i++)
848 temp_corr[i] = impulse_r[i] >> 1;
850 /* Compute impulse response autocorrelation */
851 temp = ff_g723_1_dot_product(temp_corr, temp_corr, SUBFRAME_LEN);
853 scale = ff_g723_1_normalize_bits(temp, 31);
854 impulse_corr[0] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
856 for (i = 1; i < SUBFRAME_LEN; i++) {
857 temp = ff_g723_1_dot_product(temp_corr + i, temp_corr,
859 impulse_corr[i] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
862 /* Compute crosscorrelation of impulse response with residual signal */
864 for (i = 0; i < SUBFRAME_LEN; i++) {
865 temp = ff_g723_1_dot_product(buf + i, impulse_r, SUBFRAME_LEN - i);
867 ccr1[i] = temp >> -scale;
869 ccr1[i] = av_clipl_int32(temp << scale);
873 for (i = 0; i < GRID_SIZE; i++) {
874 /* Maximize the crosscorrelation */
876 for (j = i; j < SUBFRAME_LEN; j += GRID_SIZE) {
877 temp = FFABS(ccr1[j]);
880 param.pulse_pos[0] = j;
884 /* Quantize the gain (max crosscorrelation/impulse_corr[0]) */
887 max_amp_index = GAIN_LEVELS - 2;
888 for (j = max_amp_index; j >= 2; j--) {
889 temp = av_clipl_int32((int64_t) ff_g723_1_fixed_cb_gain[j] *
890 impulse_corr[0] << 1);
891 temp = FFABS(temp - amp);
899 /* Select additional gain values */
900 for (j = 1; j < 5; j++) {
901 for (k = i; k < SUBFRAME_LEN; k += GRID_SIZE) {
905 param.amp_index = max_amp_index + j - 2;
906 amp = ff_g723_1_fixed_cb_gain[param.amp_index];
908 param.pulse_sign[0] = (ccr2[param.pulse_pos[0]] < 0) ? -amp : amp;
909 temp_corr[param.pulse_pos[0]] = 1;
911 for (k = 1; k < pulse_cnt; k++) {
913 for (l = i; l < SUBFRAME_LEN; l += GRID_SIZE) {
916 temp = impulse_corr[FFABS(l - param.pulse_pos[k - 1])];
917 temp = av_clipl_int32((int64_t) temp *
918 param.pulse_sign[k - 1] << 1);
920 temp = FFABS(ccr2[l]);
923 param.pulse_pos[k] = l;
927 param.pulse_sign[k] = (ccr2[param.pulse_pos[k]] < 0) ?
929 temp_corr[param.pulse_pos[k]] = 1;
932 /* Create the error vector */
933 memset(temp_corr, 0, sizeof(int16_t) * SUBFRAME_LEN);
935 for (k = 0; k < pulse_cnt; k++)
936 temp_corr[param.pulse_pos[k]] = param.pulse_sign[k];
938 for (k = SUBFRAME_LEN - 1; k >= 0; k--) {
940 for (l = 0; l <= k; l++) {
941 int prod = av_clipl_int32((int64_t) temp_corr[l] *
942 impulse_r[k - l] << 1);
943 temp = av_clipl_int32(temp + prod);
945 temp_corr[k] = temp << 2 >> 16;
948 /* Compute square of error */
950 for (k = 0; k < SUBFRAME_LEN; k++) {
952 prod = av_clipl_int32((int64_t) buf[k] * temp_corr[k] << 1);
953 err = av_clipl_int32(err - prod);
954 prod = av_clipl_int32((int64_t) temp_corr[k] * temp_corr[k]);
955 err = av_clipl_int32(err + prod);
959 if (err < optim->min_err) {
960 optim->min_err = err;
961 optim->grid_index = i;
962 optim->amp_index = param.amp_index;
963 optim->dirac_train = param.dirac_train;
965 for (k = 0; k < pulse_cnt; k++) {
966 optim->pulse_sign[k] = param.pulse_sign[k];
967 optim->pulse_pos[k] = param.pulse_pos[k];
975 * Encode the pulse position and gain of the current subframe.
977 * @param optim optimized fixed CB parameters
978 * @param buf excitation vector
980 static void pack_fcb_param(G723_1_Subframe *subfrm, FCBParam *optim,
981 int16_t *buf, int pulse_cnt)
985 j = PULSE_MAX - pulse_cnt;
987 subfrm->pulse_sign = 0;
988 subfrm->pulse_pos = 0;
990 for (i = 0; i < SUBFRAME_LEN >> 1; i++) {
991 int val = buf[optim->grid_index + (i << 1)];
993 subfrm->pulse_pos += ff_g723_1_combinatorial_table[j][i];
995 subfrm->pulse_sign <<= 1;
997 subfrm->pulse_sign++;
1004 subfrm->amp_index = optim->amp_index;
1005 subfrm->grid_index = optim->grid_index;
1006 subfrm->dirac_train = optim->dirac_train;
1010 * Compute the fixed codebook excitation.
1012 * @param buf target vector
1013 * @param impulse_resp impulse response of the combined filter
1015 static void fcb_search(G723_1_ChannelContext *p, int16_t *impulse_resp,
1016 int16_t *buf, int index)
1019 int pulse_cnt = pulses[index];
1022 optim.min_err = 1 << 30;
1023 get_fcb_param(&optim, impulse_resp, buf, pulse_cnt, SUBFRAME_LEN);
1025 if (p->pitch_lag[index >> 1] < SUBFRAME_LEN - 2) {
1026 get_fcb_param(&optim, impulse_resp, buf, pulse_cnt,
1027 p->pitch_lag[index >> 1]);
1030 /* Reconstruct the excitation */
1031 memset(buf, 0, sizeof(int16_t) * SUBFRAME_LEN);
1032 for (i = 0; i < pulse_cnt; i++)
1033 buf[optim.pulse_pos[i]] = optim.pulse_sign[i];
1035 pack_fcb_param(&p->subframe[index], &optim, buf, pulse_cnt);
1037 if (optim.dirac_train)
1038 ff_g723_1_gen_dirac_train(buf, p->pitch_lag[index >> 1]);
1042 * Pack the frame parameters into output bitstream.
1044 * @param frame output buffer
1045 * @param size size of the buffer
1047 static int pack_bitstream(G723_1_ChannelContext *p, AVPacket *avpkt)
1053 init_put_bits(&pb, avpkt->data, avpkt->size);
1055 put_bits(&pb, 2, info_bits);
1057 put_bits(&pb, 8, p->lsp_index[2]);
1058 put_bits(&pb, 8, p->lsp_index[1]);
1059 put_bits(&pb, 8, p->lsp_index[0]);
1061 put_bits(&pb, 7, p->pitch_lag[0] - PITCH_MIN);
1062 put_bits(&pb, 2, p->subframe[1].ad_cb_lag);
1063 put_bits(&pb, 7, p->pitch_lag[1] - PITCH_MIN);
1064 put_bits(&pb, 2, p->subframe[3].ad_cb_lag);
1066 /* Write 12 bit combined gain */
1067 for (i = 0; i < SUBFRAMES; i++) {
1068 temp = p->subframe[i].ad_cb_gain * GAIN_LEVELS +
1069 p->subframe[i].amp_index;
1070 if (p->cur_rate == RATE_6300)
1071 temp += p->subframe[i].dirac_train << 11;
1072 put_bits(&pb, 12, temp);
1075 put_bits(&pb, 1, p->subframe[0].grid_index);
1076 put_bits(&pb, 1, p->subframe[1].grid_index);
1077 put_bits(&pb, 1, p->subframe[2].grid_index);
1078 put_bits(&pb, 1, p->subframe[3].grid_index);
1080 if (p->cur_rate == RATE_6300) {
1081 put_bits(&pb, 1, 0); /* reserved bit */
1083 /* Write 13 bit combined position index */
1084 temp = (p->subframe[0].pulse_pos >> 16) * 810 +
1085 (p->subframe[1].pulse_pos >> 14) * 90 +
1086 (p->subframe[2].pulse_pos >> 16) * 9 +
1087 (p->subframe[3].pulse_pos >> 14);
1088 put_bits(&pb, 13, temp);
1090 put_bits(&pb, 16, p->subframe[0].pulse_pos & 0xffff);
1091 put_bits(&pb, 14, p->subframe[1].pulse_pos & 0x3fff);
1092 put_bits(&pb, 16, p->subframe[2].pulse_pos & 0xffff);
1093 put_bits(&pb, 14, p->subframe[3].pulse_pos & 0x3fff);
1095 put_bits(&pb, 6, p->subframe[0].pulse_sign);
1096 put_bits(&pb, 5, p->subframe[1].pulse_sign);
1097 put_bits(&pb, 6, p->subframe[2].pulse_sign);
1098 put_bits(&pb, 5, p->subframe[3].pulse_sign);
1101 flush_put_bits(&pb);
1102 return frame_size[info_bits];
1105 static int g723_1_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1106 const AVFrame *frame, int *got_packet_ptr)
1108 G723_1_Context *s = avctx->priv_data;
1109 G723_1_ChannelContext *p = &s->ch[0];
1110 int16_t unq_lpc[LPC_ORDER * SUBFRAMES];
1111 int16_t qnt_lpc[LPC_ORDER * SUBFRAMES];
1112 int16_t cur_lsp[LPC_ORDER];
1113 int16_t weighted_lpc[LPC_ORDER * SUBFRAMES << 1];
1114 int16_t vector[FRAME_LEN + PITCH_MAX];
1115 int offset, ret, i, j;
1116 int16_t *in, *start;
1119 /* duplicate input */
1120 start = in = av_malloc(frame->nb_samples * sizeof(int16_t));
1122 return AVERROR(ENOMEM);
1123 memcpy(in, frame->data[0], frame->nb_samples * sizeof(int16_t));
1125 highpass_filter(in, &p->hpf_fir_mem, &p->hpf_iir_mem);
1127 memcpy(vector, p->prev_data, HALF_FRAME_LEN * sizeof(int16_t));
1128 memcpy(vector + HALF_FRAME_LEN, in, FRAME_LEN * sizeof(int16_t));
1130 comp_lpc_coeff(vector, unq_lpc);
1131 lpc2lsp(&unq_lpc[LPC_ORDER * 3], p->prev_lsp, cur_lsp);
1132 lsp_quantize(p->lsp_index, cur_lsp, p->prev_lsp);
1135 memcpy(vector + LPC_ORDER, p->prev_data + SUBFRAME_LEN,
1136 sizeof(int16_t) * SUBFRAME_LEN);
1137 memcpy(vector + LPC_ORDER + SUBFRAME_LEN, in,
1138 sizeof(int16_t) * (HALF_FRAME_LEN + SUBFRAME_LEN));
1139 memcpy(p->prev_data, in + HALF_FRAME_LEN,
1140 sizeof(int16_t) * HALF_FRAME_LEN);
1141 memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
1143 perceptual_filter(p, weighted_lpc, unq_lpc, vector);
1145 memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
1146 memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
1147 memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
1149 ff_g723_1_scale_vector(vector, vector, FRAME_LEN + PITCH_MAX);
1151 p->pitch_lag[0] = estimate_pitch(vector, PITCH_MAX);
1152 p->pitch_lag[1] = estimate_pitch(vector, PITCH_MAX + HALF_FRAME_LEN);
1154 for (i = PITCH_MAX, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1155 comp_harmonic_coeff(vector + i, p->pitch_lag[j >> 1], hf + j);
1157 memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
1158 memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
1159 memcpy(p->prev_weight_sig, vector + FRAME_LEN, sizeof(int16_t) * PITCH_MAX);
1161 for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1162 harmonic_filter(hf + j, vector + PITCH_MAX + i, in + i);
1164 ff_g723_1_inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, 0);
1165 ff_g723_1_lsp_interpolate(qnt_lpc, cur_lsp, p->prev_lsp);
1167 memcpy(p->prev_lsp, cur_lsp, sizeof(int16_t) * LPC_ORDER);
1170 for (i = 0; i < SUBFRAMES; i++) {
1171 int16_t impulse_resp[SUBFRAME_LEN];
1172 int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
1173 int16_t flt_in[SUBFRAME_LEN];
1174 int16_t zero[LPC_ORDER], fir[LPC_ORDER], iir[LPC_ORDER];
1177 * Compute the combined impulse response of the synthesis filter,
1178 * formant perceptual weighting filter and harmonic noise shaping filter
1180 memset(zero, 0, sizeof(int16_t) * LPC_ORDER);
1181 memset(vector, 0, sizeof(int16_t) * PITCH_MAX);
1182 memset(flt_in, 0, sizeof(int16_t) * SUBFRAME_LEN);
1184 flt_in[0] = 1 << 13; /* Unit impulse */
1185 synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
1186 zero, zero, flt_in, vector + PITCH_MAX, 1);
1187 harmonic_filter(hf + i, vector + PITCH_MAX, impulse_resp);
1189 /* Compute the combined zero input response */
1191 memcpy(fir, p->perf_fir_mem, sizeof(int16_t) * LPC_ORDER);
1192 memcpy(iir, p->perf_iir_mem, sizeof(int16_t) * LPC_ORDER);
1194 synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
1195 fir, iir, flt_in, vector + PITCH_MAX, 0);
1196 memcpy(vector, p->harmonic_mem, sizeof(int16_t) * PITCH_MAX);
1197 harmonic_noise_sub(hf + i, vector + PITCH_MAX, in);
1199 acb_search(p, residual, impulse_resp, in, i);
1200 ff_g723_1_gen_acb_excitation(residual, p->prev_excitation,
1201 p->pitch_lag[i >> 1], &p->subframe[i],
1203 sub_acb_contrib(residual, impulse_resp, in);
1205 fcb_search(p, impulse_resp, in, i);
1207 /* Reconstruct the excitation */
1208 ff_g723_1_gen_acb_excitation(impulse_resp, p->prev_excitation,
1209 p->pitch_lag[i >> 1], &p->subframe[i],
1212 memmove(p->prev_excitation, p->prev_excitation + SUBFRAME_LEN,
1213 sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
1214 for (j = 0; j < SUBFRAME_LEN; j++)
1215 in[j] = av_clip_int16((in[j] << 1) + impulse_resp[j]);
1216 memcpy(p->prev_excitation + PITCH_MAX - SUBFRAME_LEN, in,
1217 sizeof(int16_t) * SUBFRAME_LEN);
1219 /* Update filter memories */
1220 synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
1221 p->perf_fir_mem, p->perf_iir_mem,
1222 in, vector + PITCH_MAX, 0);
1223 memmove(p->harmonic_mem, p->harmonic_mem + SUBFRAME_LEN,
1224 sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
1225 memcpy(p->harmonic_mem + PITCH_MAX - SUBFRAME_LEN, vector + PITCH_MAX,
1226 sizeof(int16_t) * SUBFRAME_LEN);
1229 offset += LPC_ORDER;
1234 if ((ret = ff_alloc_packet2(avctx, avpkt, 24, 0)) < 0)
1237 *got_packet_ptr = 1;
1238 avpkt->size = pack_bitstream(p, avpkt);
1242 static const AVCodecDefault defaults[] = {
1247 const AVCodec ff_g723_1_encoder = {
1249 .long_name = NULL_IF_CONFIG_SMALL("G.723.1"),
1250 .type = AVMEDIA_TYPE_AUDIO,
1251 .id = AV_CODEC_ID_G723_1,
1252 .priv_data_size = sizeof(G723_1_Context),
1253 .init = g723_1_encode_init,
1254 .encode2 = g723_1_encode_frame,
1255 .defaults = defaults,
1256 .sample_fmts = (const enum AVSampleFormat[]) {
1257 AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE