lavc: G.723.1 encoder
[libav.git] / libavcodec / g723_1enc.c
1 /*
2 * G.723.1 compatible encoder
3 * Copyright (c) Mohamed Naufal <naufal22@gmail.com>
4 *
5 * This file is part of Libav.
6 *
7 * Libav 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.
11 *
12 * Libav 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.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 /**
23 * @file
24 * G.723.1 compatible encoder
25 */
26
27 #include <stdint.h>
28 #include <string.h>
29
30 #include "libavutil/channel_layout.h"
31 #include "libavutil/common.h"
32 #include "libavutil/mem.h"
33 #include "libavutil/opt.h"
34
35 #include "avcodec.h"
36 #include "celp_math.h"
37 #include "g723_1.h"
38 #include "internal.h"
39
40 #define BITSTREAM_WRITER_LE
41 #include "put_bits.h"
42
43 static av_cold int g723_1_encode_init(AVCodecContext *avctx)
44 {
45 G723_1_Context *p = avctx->priv_data;
46
47 if (avctx->sample_rate != 8000) {
48 av_log(avctx, AV_LOG_ERROR, "Only 8000Hz sample rate supported\n");
49 return AVERROR(EINVAL);
50 }
51
52 if (avctx->channels != 1) {
53 av_log(avctx, AV_LOG_ERROR, "Only mono supported\n");
54 return AVERROR(EINVAL);
55 }
56
57 if (avctx->bit_rate == 6300) {
58 p->cur_rate = RATE_6300;
59 } else if (avctx->bit_rate == 5300) {
60 av_log(avctx, AV_LOG_ERROR, "Bitrate not supported yet, use 6300\n");
61 return AVERROR_PATCHWELCOME;
62 } else {
63 av_log(avctx, AV_LOG_ERROR, "Bitrate not supported, use 6300\n");
64 return AVERROR(EINVAL);
65 }
66 avctx->frame_size = 240;
67 memcpy(p->prev_lsp, dc_lsp, LPC_ORDER * sizeof(int16_t));
68
69 return 0;
70 }
71
72 /**
73 * Remove DC component from the input signal.
74 *
75 * @param buf input signal
76 * @param fir zero memory
77 * @param iir pole memory
78 */
79 static void highpass_filter(int16_t *buf, int16_t *fir, int *iir)
80 {
81 int i;
82 for (i = 0; i < FRAME_LEN; i++) {
83 *iir = (buf[i] << 15) + ((-*fir) << 15) + MULL2(*iir, 0x7f00);
84 *fir = buf[i];
85 buf[i] = av_clipl_int32((int64_t) *iir + (1 << 15)) >> 16;
86 }
87 }
88
89 /**
90 * Estimate autocorrelation of the input vector.
91 *
92 * @param buf input buffer
93 * @param autocorr autocorrelation coefficients vector
94 */
95 static void comp_autocorr(int16_t *buf, int16_t *autocorr)
96 {
97 int i, scale, temp;
98 int16_t vector[LPC_FRAME];
99
100 ff_g723_1_scale_vector(vector, buf, LPC_FRAME);
101
102 /* Apply the Hamming window */
103 for (i = 0; i < LPC_FRAME; i++)
104 vector[i] = (vector[i] * hamming_window[i] + (1 << 14)) >> 15;
105
106 /* Compute the first autocorrelation coefficient */
107 temp = ff_dot_product(vector, vector, LPC_FRAME);
108
109 /* Apply a white noise correlation factor of (1025/1024) */
110 temp += temp >> 10;
111
112 /* Normalize */
113 scale = ff_g723_1_normalize_bits(temp, 31);
114 autocorr[0] = av_clipl_int32((int64_t) (temp << scale) +
115 (1 << 15)) >> 16;
116
117 /* Compute the remaining coefficients */
118 if (!autocorr[0]) {
119 memset(autocorr + 1, 0, LPC_ORDER * sizeof(int16_t));
120 } else {
121 for (i = 1; i <= LPC_ORDER; i++) {
122 temp = ff_dot_product(vector, vector + i, LPC_FRAME - i);
123 temp = MULL2((temp << scale), binomial_window[i - 1]);
124 autocorr[i] = av_clipl_int32((int64_t) temp + (1 << 15)) >> 16;
125 }
126 }
127 }
128
129 /**
130 * Use Levinson-Durbin recursion to compute LPC coefficients from
131 * autocorrelation values.
132 *
133 * @param lpc LPC coefficients vector
134 * @param autocorr autocorrelation coefficients vector
135 * @param error prediction error
136 */
137 static void levinson_durbin(int16_t *lpc, int16_t *autocorr, int16_t error)
138 {
139 int16_t vector[LPC_ORDER];
140 int16_t partial_corr;
141 int i, j, temp;
142
143 memset(lpc, 0, LPC_ORDER * sizeof(int16_t));
144
145 for (i = 0; i < LPC_ORDER; i++) {
146 /* Compute the partial correlation coefficient */
147 temp = 0;
148 for (j = 0; j < i; j++)
149 temp -= lpc[j] * autocorr[i - j - 1];
150 temp = ((autocorr[i] << 13) + temp) << 3;
151
152 if (FFABS(temp) >= (error << 16))
153 break;
154
155 partial_corr = temp / (error << 1);
156
157 lpc[i] = av_clipl_int32((int64_t) (partial_corr << 14) +
158 (1 << 15)) >> 16;
159
160 /* Update the prediction error */
161 temp = MULL2(temp, partial_corr);
162 error = av_clipl_int32((int64_t) (error << 16) - temp +
163 (1 << 15)) >> 16;
164
165 memcpy(vector, lpc, i * sizeof(int16_t));
166 for (j = 0; j < i; j++) {
167 temp = partial_corr * vector[i - j - 1] << 1;
168 lpc[j] = av_clipl_int32((int64_t) (lpc[j] << 16) - temp +
169 (1 << 15)) >> 16;
170 }
171 }
172 }
173
174 /**
175 * Calculate LPC coefficients for the current frame.
176 *
177 * @param buf current frame
178 * @param prev_data 2 trailing subframes of the previous frame
179 * @param lpc LPC coefficients vector
180 */
181 static void comp_lpc_coeff(int16_t *buf, int16_t *lpc)
182 {
183 int16_t autocorr[(LPC_ORDER + 1) * SUBFRAMES];
184 int16_t *autocorr_ptr = autocorr;
185 int16_t *lpc_ptr = lpc;
186 int i, j;
187
188 for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
189 comp_autocorr(buf + i, autocorr_ptr);
190 levinson_durbin(lpc_ptr, autocorr_ptr + 1, autocorr_ptr[0]);
191
192 lpc_ptr += LPC_ORDER;
193 autocorr_ptr += LPC_ORDER + 1;
194 }
195 }
196
197 static void lpc2lsp(int16_t *lpc, int16_t *prev_lsp, int16_t *lsp)
198 {
199 int f[LPC_ORDER + 2]; ///< coefficients of the sum and difference
200 ///< polynomials (F1, F2) ordered as
201 ///< f1[0], f2[0], ...., f1[5], f2[5]
202
203 int max, shift, cur_val, prev_val, count, p;
204 int i, j;
205 int64_t temp;
206
207 /* Initialize f1[0] and f2[0] to 1 in Q25 */
208 for (i = 0; i < LPC_ORDER; i++)
209 lsp[i] = (lpc[i] * bandwidth_expand[i] + (1 << 14)) >> 15;
210
211 /* Apply bandwidth expansion on the LPC coefficients */
212 f[0] = f[1] = 1 << 25;
213
214 /* Compute the remaining coefficients */
215 for (i = 0; i < LPC_ORDER / 2; i++) {
216 /* f1 */
217 f[2 * i + 2] = -f[2 * i] - ((lsp[i] + lsp[LPC_ORDER - 1 - i]) << 12);
218 /* f2 */
219 f[2 * i + 3] = f[2 * i + 1] - ((lsp[i] - lsp[LPC_ORDER - 1 - i]) << 12);
220 }
221
222 /* Divide f1[5] and f2[5] by 2 for use in polynomial evaluation */
223 f[LPC_ORDER] >>= 1;
224 f[LPC_ORDER + 1] >>= 1;
225
226 /* Normalize and shorten */
227 max = FFABS(f[0]);
228 for (i = 1; i < LPC_ORDER + 2; i++)
229 max = FFMAX(max, FFABS(f[i]));
230
231 shift = ff_g723_1_normalize_bits(max, 31);
232
233 for (i = 0; i < LPC_ORDER + 2; i++)
234 f[i] = av_clipl_int32((int64_t) (f[i] << shift) + (1 << 15)) >> 16;
235
236 /**
237 * Evaluate F1 and F2 at uniform intervals of pi/256 along the
238 * unit circle and check for zero crossings.
239 */
240 p = 0;
241 temp = 0;
242 for (i = 0; i <= LPC_ORDER / 2; i++)
243 temp += f[2 * i] * cos_tab[0];
244 prev_val = av_clipl_int32(temp << 1);
245 count = 0;
246 for (i = 1; i < COS_TBL_SIZE / 2; i++) {
247 /* Evaluate */
248 temp = 0;
249 for (j = 0; j <= LPC_ORDER / 2; j++)
250 temp += f[LPC_ORDER - 2 * j + p] * cos_tab[i * j % COS_TBL_SIZE];
251 cur_val = av_clipl_int32(temp << 1);
252
253 /* Check for sign change, indicating a zero crossing */
254 if ((cur_val ^ prev_val) < 0) {
255 int abs_cur = FFABS(cur_val);
256 int abs_prev = FFABS(prev_val);
257 int sum = abs_cur + abs_prev;
258
259 shift = ff_g723_1_normalize_bits(sum, 31);
260 sum <<= shift;
261 abs_prev = abs_prev << shift >> 8;
262 lsp[count++] = ((i - 1) << 7) + (abs_prev >> 1) / (sum >> 16);
263
264 if (count == LPC_ORDER)
265 break;
266
267 /* Switch between sum and difference polynomials */
268 p ^= 1;
269
270 /* Evaluate */
271 temp = 0;
272 for (j = 0; j <= LPC_ORDER / 2; j++)
273 temp += f[LPC_ORDER - 2 * j + p] *
274 cos_tab[i * j % COS_TBL_SIZE];
275 cur_val = av_clipl_int32(temp << 1);
276 }
277 prev_val = cur_val;
278 }
279
280 if (count != LPC_ORDER)
281 memcpy(lsp, prev_lsp, LPC_ORDER * sizeof(int16_t));
282 }
283
284 /**
285 * Quantize the current LSP subvector.
286 *
287 * @param num band number
288 * @param offset offset of the current subvector in an LPC_ORDER vector
289 * @param size size of the current subvector
290 */
291 #define get_index(num, offset, size) \
292 { \
293 int error, max = -1; \
294 int16_t temp[4]; \
295 int i, j; \
296 \
297 for (i = 0; i < LSP_CB_SIZE; i++) { \
298 for (j = 0; j < size; j++){ \
299 temp[j] = (weight[j + (offset)] * lsp_band##num[i][j] + \
300 (1 << 14)) >> 15; \
301 } \
302 error = ff_g723_1_dot_product(lsp + (offset), temp, size) << 1; \
303 error -= ff_g723_1_dot_product(lsp_band##num[i], temp, size); \
304 if (error > max) { \
305 max = error; \
306 lsp_index[num] = i; \
307 } \
308 } \
309 }
310
311 /**
312 * Vector quantize the LSP frequencies.
313 *
314 * @param lsp the current lsp vector
315 * @param prev_lsp the previous lsp vector
316 */
317 static void lsp_quantize(uint8_t *lsp_index, int16_t *lsp, int16_t *prev_lsp)
318 {
319 int16_t weight[LPC_ORDER];
320 int16_t min, max;
321 int shift, i;
322
323 /* Calculate the VQ weighting vector */
324 weight[0] = (1 << 20) / (lsp[1] - lsp[0]);
325 weight[LPC_ORDER - 1] = (1 << 20) /
326 (lsp[LPC_ORDER - 1] - lsp[LPC_ORDER - 2]);
327
328 for (i = 1; i < LPC_ORDER - 1; i++) {
329 min = FFMIN(lsp[i] - lsp[i - 1], lsp[i + 1] - lsp[i]);
330 if (min > 0x20)
331 weight[i] = (1 << 20) / min;
332 else
333 weight[i] = INT16_MAX;
334 }
335
336 /* Normalize */
337 max = 0;
338 for (i = 0; i < LPC_ORDER; i++)
339 max = FFMAX(weight[i], max);
340
341 shift = ff_g723_1_normalize_bits(max, 15);
342 for (i = 0; i < LPC_ORDER; i++) {
343 weight[i] <<= shift;
344 }
345
346 /* Compute the VQ target vector */
347 for (i = 0; i < LPC_ORDER; i++) {
348 lsp[i] -= dc_lsp[i] +
349 (((prev_lsp[i] - dc_lsp[i]) * 12288 + (1 << 14)) >> 15);
350 }
351
352 get_index(0, 0, 3);
353 get_index(1, 3, 3);
354 get_index(2, 6, 4);
355 }
356
357 /**
358 * Perform IIR filtering.
359 *
360 * @param fir_coef FIR coefficients
361 * @param iir_coef IIR coefficients
362 * @param src source vector
363 * @param dest destination vector
364 */
365 static void iir_filter(int16_t *fir_coef, int16_t *iir_coef,
366 int16_t *src, int16_t *dest)
367 {
368 int m, n;
369
370 for (m = 0; m < SUBFRAME_LEN; m++) {
371 int64_t filter = 0;
372 for (n = 1; n <= LPC_ORDER; n++) {
373 filter -= fir_coef[n - 1] * src[m - n] -
374 iir_coef[n - 1] * dest[m - n];
375 }
376
377 dest[m] = av_clipl_int32((src[m] << 16) + (filter << 3) +
378 (1 << 15)) >> 16;
379 }
380 }
381
382 /**
383 * Apply the formant perceptual weighting filter.
384 *
385 * @param flt_coef filter coefficients
386 * @param unq_lpc unquantized lpc vector
387 */
388 static void perceptual_filter(G723_1_Context *p, int16_t *flt_coef,
389 int16_t *unq_lpc, int16_t *buf)
390 {
391 int16_t vector[FRAME_LEN + LPC_ORDER];
392 int i, j, k, l = 0;
393
394 memcpy(buf, p->iir_mem, sizeof(int16_t) * LPC_ORDER);
395 memcpy(vector, p->fir_mem, sizeof(int16_t) * LPC_ORDER);
396 memcpy(vector + LPC_ORDER, buf + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
397
398 for (i = LPC_ORDER, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++) {
399 for (k = 0; k < LPC_ORDER; k++) {
400 flt_coef[k + 2 * l] = (unq_lpc[k + l] * percept_flt_tbl[0][k] +
401 (1 << 14)) >> 15;
402 flt_coef[k + 2 * l + LPC_ORDER] = (unq_lpc[k + l] *
403 percept_flt_tbl[1][k] +
404 (1 << 14)) >> 15;
405 }
406 iir_filter(flt_coef + 2 * l, flt_coef + 2 * l + LPC_ORDER,
407 vector + i, buf + i);
408 l += LPC_ORDER;
409 }
410 memcpy(p->iir_mem, buf + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
411 memcpy(p->fir_mem, vector + FRAME_LEN, sizeof(int16_t) * LPC_ORDER);
412 }
413
414 /**
415 * Estimate the open loop pitch period.
416 *
417 * @param buf perceptually weighted speech
418 * @param start estimation is carried out from this position
419 */
420 static int estimate_pitch(int16_t *buf, int start)
421 {
422 int max_exp = 32;
423 int max_ccr = 0x4000;
424 int max_eng = 0x7fff;
425 int index = PITCH_MIN;
426 int offset = start - PITCH_MIN + 1;
427
428 int ccr, eng, orig_eng, ccr_eng, exp;
429 int diff, temp;
430
431 int i;
432
433 orig_eng = ff_dot_product(buf + offset, buf + offset, HALF_FRAME_LEN);
434
435 for (i = PITCH_MIN; i <= PITCH_MAX - 3; i++) {
436 offset--;
437
438 /* Update energy and compute correlation */
439 orig_eng += buf[offset] * buf[offset] -
440 buf[offset + HALF_FRAME_LEN] * buf[offset + HALF_FRAME_LEN];
441 ccr = ff_dot_product(buf + start, buf + offset, HALF_FRAME_LEN);
442 if (ccr <= 0)
443 continue;
444
445 /* Split into mantissa and exponent to maintain precision */
446 exp = ff_g723_1_normalize_bits(ccr, 31);
447 ccr = av_clipl_int32((int64_t) (ccr << exp) + (1 << 15)) >> 16;
448 exp <<= 1;
449 ccr *= ccr;
450 temp = ff_g723_1_normalize_bits(ccr, 31);
451 ccr = ccr << temp >> 16;
452 exp += temp;
453
454 temp = ff_g723_1_normalize_bits(orig_eng, 31);
455 eng = av_clipl_int32((int64_t) (orig_eng << temp) + (1 << 15)) >> 16;
456 exp -= temp;
457
458 if (ccr >= eng) {
459 exp--;
460 ccr >>= 1;
461 }
462 if (exp > max_exp)
463 continue;
464
465 if (exp + 1 < max_exp)
466 goto update;
467
468 /* Equalize exponents before comparison */
469 if (exp + 1 == max_exp)
470 temp = max_ccr >> 1;
471 else
472 temp = max_ccr;
473 ccr_eng = ccr * max_eng;
474 diff = ccr_eng - eng * temp;
475 if (diff > 0 && (i - index < PITCH_MIN || diff > ccr_eng >> 2)) {
476 update:
477 index = i;
478 max_exp = exp;
479 max_ccr = ccr;
480 max_eng = eng;
481 }
482 }
483 return index;
484 }
485
486 /**
487 * Compute harmonic noise filter parameters.
488 *
489 * @param buf perceptually weighted speech
490 * @param pitch_lag open loop pitch period
491 * @param hf harmonic filter parameters
492 */
493 static void comp_harmonic_coeff(int16_t *buf, int16_t pitch_lag, HFParam *hf)
494 {
495 int ccr, eng, max_ccr, max_eng;
496 int exp, max, diff;
497 int energy[15];
498 int i, j;
499
500 for (i = 0, j = pitch_lag - 3; j <= pitch_lag + 3; i++, j++) {
501 /* Compute residual energy */
502 energy[i << 1] = ff_dot_product(buf - j, buf - j, SUBFRAME_LEN);
503 /* Compute correlation */
504 energy[(i << 1) + 1] = ff_dot_product(buf, buf - j, SUBFRAME_LEN);
505 }
506
507 /* Compute target energy */
508 energy[14] = ff_dot_product(buf, buf, SUBFRAME_LEN);
509
510 /* Normalize */
511 max = 0;
512 for (i = 0; i < 15; i++)
513 max = FFMAX(max, FFABS(energy[i]));
514
515 exp = ff_g723_1_normalize_bits(max, 31);
516 for (i = 0; i < 15; i++) {
517 energy[i] = av_clipl_int32((int64_t)(energy[i] << exp) +
518 (1 << 15)) >> 16;
519 }
520
521 hf->index = -1;
522 hf->gain = 0;
523 max_ccr = 1;
524 max_eng = 0x7fff;
525
526 for (i = 0; i <= 6; i++) {
527 eng = energy[i << 1];
528 ccr = energy[(i << 1) + 1];
529
530 if (ccr <= 0)
531 continue;
532
533 ccr = (ccr * ccr + (1 << 14)) >> 15;
534 diff = ccr * max_eng - eng * max_ccr;
535 if (diff > 0) {
536 max_ccr = ccr;
537 max_eng = eng;
538 hf->index = i;
539 }
540 }
541
542 if (hf->index == -1) {
543 hf->index = pitch_lag;
544 return;
545 }
546
547 eng = energy[14] * max_eng;
548 eng = (eng >> 2) + (eng >> 3);
549 ccr = energy[(hf->index << 1) + 1] * energy[(hf->index << 1) + 1];
550 if (eng < ccr) {
551 eng = energy[(hf->index << 1) + 1];
552
553 if (eng >= max_eng)
554 hf->gain = 0x2800;
555 else
556 hf->gain = ((eng << 15) / max_eng * 0x2800 + (1 << 14)) >> 15;
557 }
558 hf->index += pitch_lag - 3;
559 }
560
561 /**
562 * Apply the harmonic noise shaping filter.
563 *
564 * @param hf filter parameters
565 */
566 static void harmonic_filter(HFParam *hf, const int16_t *src, int16_t *dest)
567 {
568 int i;
569
570 for (i = 0; i < SUBFRAME_LEN; i++) {
571 int64_t temp = hf->gain * src[i - hf->index] << 1;
572 dest[i] = av_clipl_int32((src[i] << 16) - temp + (1 << 15)) >> 16;
573 }
574 }
575
576 static void harmonic_noise_sub(HFParam *hf, const int16_t *src, int16_t *dest)
577 {
578 int i;
579 for (i = 0; i < SUBFRAME_LEN; i++) {
580 int64_t temp = hf->gain * src[i - hf->index] << 1;
581 dest[i] = av_clipl_int32(((dest[i] - src[i]) << 16) + temp +
582 (1 << 15)) >> 16;
583 }
584 }
585
586 /**
587 * Combined synthesis and formant perceptual weighting filer.
588 *
589 * @param qnt_lpc quantized lpc coefficients
590 * @param perf_lpc perceptual filter coefficients
591 * @param perf_fir perceptual filter fir memory
592 * @param perf_iir perceptual filter iir memory
593 * @param scale the filter output will be scaled by 2^scale
594 */
595 static void synth_percept_filter(int16_t *qnt_lpc, int16_t *perf_lpc,
596 int16_t *perf_fir, int16_t *perf_iir,
597 const int16_t *src, int16_t *dest, int scale)
598 {
599 int i, j;
600 int16_t buf_16[SUBFRAME_LEN + LPC_ORDER];
601 int64_t buf[SUBFRAME_LEN];
602
603 int16_t *bptr_16 = buf_16 + LPC_ORDER;
604
605 memcpy(buf_16, perf_fir, sizeof(int16_t) * LPC_ORDER);
606 memcpy(dest - LPC_ORDER, perf_iir, sizeof(int16_t) * LPC_ORDER);
607
608 for (i = 0; i < SUBFRAME_LEN; i++) {
609 int64_t temp = 0;
610 for (j = 1; j <= LPC_ORDER; j++)
611 temp -= qnt_lpc[j - 1] * bptr_16[i - j];
612
613 buf[i] = (src[i] << 15) + (temp << 3);
614 bptr_16[i] = av_clipl_int32(buf[i] + (1 << 15)) >> 16;
615 }
616
617 for (i = 0; i < SUBFRAME_LEN; i++) {
618 int64_t fir = 0, iir = 0;
619 for (j = 1; j <= LPC_ORDER; j++) {
620 fir -= perf_lpc[j - 1] * bptr_16[i - j];
621 iir += perf_lpc[j + LPC_ORDER - 1] * dest[i - j];
622 }
623 dest[i] = av_clipl_int32(((buf[i] + (fir << 3)) << scale) + (iir << 3) +
624 (1 << 15)) >> 16;
625 }
626 memcpy(perf_fir, buf_16 + SUBFRAME_LEN, sizeof(int16_t) * LPC_ORDER);
627 memcpy(perf_iir, dest + SUBFRAME_LEN - LPC_ORDER,
628 sizeof(int16_t) * LPC_ORDER);
629 }
630
631 /**
632 * Compute the adaptive codebook contribution.
633 *
634 * @param buf input signal
635 * @param index the current subframe index
636 */
637 static void acb_search(G723_1_Context *p, int16_t *residual,
638 int16_t *impulse_resp, const int16_t *buf,
639 int index)
640 {
641 int16_t flt_buf[PITCH_ORDER][SUBFRAME_LEN];
642
643 const int16_t *cb_tbl = adaptive_cb_gain85;
644
645 int ccr_buf[PITCH_ORDER * SUBFRAMES << 2];
646
647 int pitch_lag = p->pitch_lag[index >> 1];
648 int acb_lag = 1;
649 int acb_gain = 0;
650 int odd_frame = index & 1;
651 int iter = 3 + odd_frame;
652 int count = 0;
653 int tbl_size = 85;
654
655 int i, j, k, l, max;
656 int64_t temp;
657
658 if (!odd_frame) {
659 if (pitch_lag == PITCH_MIN)
660 pitch_lag++;
661 else
662 pitch_lag = FFMIN(pitch_lag, PITCH_MAX - 5);
663 }
664
665 for (i = 0; i < iter; i++) {
666 ff_g723_1_get_residual(residual, p->prev_excitation, pitch_lag + i - 1);
667
668 for (j = 0; j < SUBFRAME_LEN; j++) {
669 temp = 0;
670 for (k = 0; k <= j; k++)
671 temp += residual[PITCH_ORDER - 1 + k] * impulse_resp[j - k];
672 flt_buf[PITCH_ORDER - 1][j] = av_clipl_int32((temp << 1) +
673 (1 << 15)) >> 16;
674 }
675
676 for (j = PITCH_ORDER - 2; j >= 0; j--) {
677 flt_buf[j][0] = ((residual[j] << 13) + (1 << 14)) >> 15;
678 for (k = 1; k < SUBFRAME_LEN; k++) {
679 temp = (flt_buf[j + 1][k - 1] << 15) +
680 residual[j] * impulse_resp[k];
681 flt_buf[j][k] = av_clipl_int32((temp << 1) + (1 << 15)) >> 16;
682 }
683 }
684
685 /* Compute crosscorrelation with the signal */
686 for (j = 0; j < PITCH_ORDER; j++) {
687 temp = ff_dot_product(buf, flt_buf[j], SUBFRAME_LEN);
688 ccr_buf[count++] = av_clipl_int32(temp << 1);
689 }
690
691 /* Compute energies */
692 for (j = 0; j < PITCH_ORDER; j++) {
693 ccr_buf[count++] = ff_g723_1_dot_product(flt_buf[j], flt_buf[j],
694 SUBFRAME_LEN);
695 }
696
697 for (j = 1; j < PITCH_ORDER; j++) {
698 for (k = 0; k < j; k++) {
699 temp = ff_dot_product(flt_buf[j], flt_buf[k], SUBFRAME_LEN);
700 ccr_buf[count++] = av_clipl_int32(temp << 2);
701 }
702 }
703 }
704
705 /* Normalize and shorten */
706 max = 0;
707 for (i = 0; i < 20 * iter; i++)
708 max = FFMAX(max, FFABS(ccr_buf[i]));
709
710 temp = ff_g723_1_normalize_bits(max, 31);
711
712 for (i = 0; i < 20 * iter; i++)
713 ccr_buf[i] = av_clipl_int32((int64_t) (ccr_buf[i] << temp) +
714 (1 << 15)) >> 16;
715
716 max = 0;
717 for (i = 0; i < iter; i++) {
718 /* Select quantization table */
719 if (!odd_frame && pitch_lag + i - 1 >= SUBFRAME_LEN - 2 ||
720 odd_frame && pitch_lag >= SUBFRAME_LEN - 2) {
721 cb_tbl = adaptive_cb_gain170;
722 tbl_size = 170;
723 }
724
725 for (j = 0, k = 0; j < tbl_size; j++, k += 20) {
726 temp = 0;
727 for (l = 0; l < 20; l++)
728 temp += ccr_buf[20 * i + l] * cb_tbl[k + l];
729 temp = av_clipl_int32(temp);
730
731 if (temp > max) {
732 max = temp;
733 acb_gain = j;
734 acb_lag = i;
735 }
736 }
737 }
738
739 if (!odd_frame) {
740 pitch_lag += acb_lag - 1;
741 acb_lag = 1;
742 }
743
744 p->pitch_lag[index >> 1] = pitch_lag;
745 p->subframe[index].ad_cb_lag = acb_lag;
746 p->subframe[index].ad_cb_gain = acb_gain;
747 }
748
749 /**
750 * Subtract the adaptive codebook contribution from the input
751 * to obtain the residual.
752 *
753 * @param buf target vector
754 */
755 static void sub_acb_contrib(const int16_t *residual, const int16_t *impulse_resp,
756 int16_t *buf)
757 {
758 int i, j;
759 /* Subtract adaptive CB contribution to obtain the residual */
760 for (i = 0; i < SUBFRAME_LEN; i++) {
761 int64_t temp = buf[i] << 14;
762 for (j = 0; j <= i; j++)
763 temp -= residual[j] * impulse_resp[i - j];
764
765 buf[i] = av_clipl_int32((temp << 2) + (1 << 15)) >> 16;
766 }
767 }
768
769 /**
770 * Quantize the residual signal using the fixed codebook (MP-MLQ).
771 *
772 * @param optim optimized fixed codebook parameters
773 * @param buf excitation vector
774 */
775 static void get_fcb_param(FCBParam *optim, int16_t *impulse_resp,
776 int16_t *buf, int pulse_cnt, int pitch_lag)
777 {
778 FCBParam param;
779 int16_t impulse_r[SUBFRAME_LEN];
780 int16_t temp_corr[SUBFRAME_LEN];
781 int16_t impulse_corr[SUBFRAME_LEN];
782
783 int ccr1[SUBFRAME_LEN];
784 int ccr2[SUBFRAME_LEN];
785 int amp, err, max, max_amp_index, min, scale, i, j, k, l;
786
787 int64_t temp;
788
789 /* Update impulse response */
790 memcpy(impulse_r, impulse_resp, sizeof(int16_t) * SUBFRAME_LEN);
791 param.dirac_train = 0;
792 if (pitch_lag < SUBFRAME_LEN - 2) {
793 param.dirac_train = 1;
794 ff_g723_1_gen_dirac_train(impulse_r, pitch_lag);
795 }
796
797 for (i = 0; i < SUBFRAME_LEN; i++)
798 temp_corr[i] = impulse_r[i] >> 1;
799
800 /* Compute impulse response autocorrelation */
801 temp = ff_g723_1_dot_product(temp_corr, temp_corr, SUBFRAME_LEN);
802
803 scale = ff_g723_1_normalize_bits(temp, 31);
804 impulse_corr[0] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
805
806 for (i = 1; i < SUBFRAME_LEN; i++) {
807 temp = ff_g723_1_dot_product(temp_corr + i, temp_corr,
808 SUBFRAME_LEN - i);
809 impulse_corr[i] = av_clipl_int32((temp << scale) + (1 << 15)) >> 16;
810 }
811
812 /* Compute crosscorrelation of impulse response with residual signal */
813 scale -= 4;
814 for (i = 0; i < SUBFRAME_LEN; i++) {
815 temp = ff_g723_1_dot_product(buf + i, impulse_r, SUBFRAME_LEN - i);
816 if (scale < 0)
817 ccr1[i] = temp >> -scale;
818 else
819 ccr1[i] = av_clipl_int32(temp << scale);
820 }
821
822 /* Search loop */
823 for (i = 0; i < GRID_SIZE; i++) {
824 /* Maximize the crosscorrelation */
825 max = 0;
826 for (j = i; j < SUBFRAME_LEN; j += GRID_SIZE) {
827 temp = FFABS(ccr1[j]);
828 if (temp >= max) {
829 max = temp;
830 param.pulse_pos[0] = j;
831 }
832 }
833
834 /* Quantize the gain (max crosscorrelation/impulse_corr[0]) */
835 amp = max;
836 min = 1 << 30;
837 max_amp_index = GAIN_LEVELS - 2;
838 for (j = max_amp_index; j >= 2; j--) {
839 temp = av_clipl_int32((int64_t) fixed_cb_gain[j] *
840 impulse_corr[0] << 1);
841 temp = FFABS(temp - amp);
842 if (temp < min) {
843 min = temp;
844 max_amp_index = j;
845 }
846 }
847
848 max_amp_index--;
849 /* Select additional gain values */
850 for (j = 1; j < 5; j++) {
851 for (k = i; k < SUBFRAME_LEN; k += GRID_SIZE) {
852 temp_corr[k] = 0;
853 ccr2[k] = ccr1[k];
854 }
855 param.amp_index = max_amp_index + j - 2;
856 amp = fixed_cb_gain[param.amp_index];
857
858 param.pulse_sign[0] = (ccr2[param.pulse_pos[0]] < 0) ? -amp : amp;
859 temp_corr[param.pulse_pos[0]] = 1;
860
861 for (k = 1; k < pulse_cnt; k++) {
862 max = INT_MIN;
863 for (l = i; l < SUBFRAME_LEN; l += GRID_SIZE) {
864 if (temp_corr[l])
865 continue;
866 temp = impulse_corr[FFABS(l - param.pulse_pos[k - 1])];
867 temp = av_clipl_int32((int64_t) temp *
868 param.pulse_sign[k - 1] << 1);
869 ccr2[l] -= temp;
870 temp = FFABS(ccr2[l]);
871 if (temp > max) {
872 max = temp;
873 param.pulse_pos[k] = l;
874 }
875 }
876
877 param.pulse_sign[k] = (ccr2[param.pulse_pos[k]] < 0) ?
878 -amp : amp;
879 temp_corr[param.pulse_pos[k]] = 1;
880 }
881
882 /* Create the error vector */
883 memset(temp_corr, 0, sizeof(int16_t) * SUBFRAME_LEN);
884
885 for (k = 0; k < pulse_cnt; k++)
886 temp_corr[param.pulse_pos[k]] = param.pulse_sign[k];
887
888 for (k = SUBFRAME_LEN - 1; k >= 0; k--) {
889 temp = 0;
890 for (l = 0; l <= k; l++) {
891 int prod = av_clipl_int32((int64_t) temp_corr[l] *
892 impulse_r[k - l] << 1);
893 temp = av_clipl_int32(temp + prod);
894 }
895 temp_corr[k] = temp << 2 >> 16;
896 }
897
898 /* Compute square of error */
899 err = 0;
900 for (k = 0; k < SUBFRAME_LEN; k++) {
901 int64_t prod;
902 prod = av_clipl_int32((int64_t) buf[k] * temp_corr[k] << 1);
903 err = av_clipl_int32(err - prod);
904 prod = av_clipl_int32((int64_t) temp_corr[k] * temp_corr[k]);
905 err = av_clipl_int32(err + prod);
906 }
907
908 /* Minimize */
909 if (err < optim->min_err) {
910 optim->min_err = err;
911 optim->grid_index = i;
912 optim->amp_index = param.amp_index;
913 optim->dirac_train = param.dirac_train;
914
915 for (k = 0; k < pulse_cnt; k++) {
916 optim->pulse_sign[k] = param.pulse_sign[k];
917 optim->pulse_pos[k] = param.pulse_pos[k];
918 }
919 }
920 }
921 }
922 }
923
924 /**
925 * Encode the pulse position and gain of the current subframe.
926 *
927 * @param optim optimized fixed CB parameters
928 * @param buf excitation vector
929 */
930 static void pack_fcb_param(G723_1_Subframe *subfrm, FCBParam *optim,
931 int16_t *buf, int pulse_cnt)
932 {
933 int i, j;
934
935 j = PULSE_MAX - pulse_cnt;
936
937 subfrm->pulse_sign = 0;
938 subfrm->pulse_pos = 0;
939
940 for (i = 0; i < SUBFRAME_LEN >> 1; i++) {
941 int val = buf[optim->grid_index + (i << 1)];
942 if (!val) {
943 subfrm->pulse_pos += combinatorial_table[j][i];
944 } else {
945 subfrm->pulse_sign <<= 1;
946 if (val < 0)
947 subfrm->pulse_sign++;
948 j++;
949
950 if (j == PULSE_MAX)
951 break;
952 }
953 }
954 subfrm->amp_index = optim->amp_index;
955 subfrm->grid_index = optim->grid_index;
956 subfrm->dirac_train = optim->dirac_train;
957 }
958
959 /**
960 * Compute the fixed codebook excitation.
961 *
962 * @param buf target vector
963 * @param impulse_resp impulse response of the combined filter
964 */
965 static void fcb_search(G723_1_Context *p, int16_t *impulse_resp,
966 int16_t *buf, int index)
967 {
968 FCBParam optim;
969 int pulse_cnt = pulses[index];
970 int i;
971
972 optim.min_err = 1 << 30;
973 get_fcb_param(&optim, impulse_resp, buf, pulse_cnt, SUBFRAME_LEN);
974
975 if (p->pitch_lag[index >> 1] < SUBFRAME_LEN - 2) {
976 get_fcb_param(&optim, impulse_resp, buf, pulse_cnt,
977 p->pitch_lag[index >> 1]);
978 }
979
980 /* Reconstruct the excitation */
981 memset(buf, 0, sizeof(int16_t) * SUBFRAME_LEN);
982 for (i = 0; i < pulse_cnt; i++)
983 buf[optim.pulse_pos[i]] = optim.pulse_sign[i];
984
985 pack_fcb_param(&p->subframe[index], &optim, buf, pulse_cnt);
986
987 if (optim.dirac_train)
988 ff_g723_1_gen_dirac_train(buf, p->pitch_lag[index >> 1]);
989 }
990
991 /**
992 * Pack the frame parameters into output bitstream.
993 *
994 * @param frame output buffer
995 * @param size size of the buffer
996 */
997 static int pack_bitstream(G723_1_Context *p, AVPacket *avpkt)
998 {
999 PutBitContext pb;
1000 int info_bits = 0;
1001 int i, temp;
1002
1003 init_put_bits(&pb, avpkt->data, avpkt->size);
1004
1005 put_bits(&pb, 2, info_bits);
1006
1007 put_bits(&pb, 8, p->lsp_index[2]);
1008 put_bits(&pb, 8, p->lsp_index[1]);
1009 put_bits(&pb, 8, p->lsp_index[0]);
1010
1011 put_bits(&pb, 7, p->pitch_lag[0] - PITCH_MIN);
1012 put_bits(&pb, 2, p->subframe[1].ad_cb_lag);
1013 put_bits(&pb, 7, p->pitch_lag[1] - PITCH_MIN);
1014 put_bits(&pb, 2, p->subframe[3].ad_cb_lag);
1015
1016 /* Write 12 bit combined gain */
1017 for (i = 0; i < SUBFRAMES; i++) {
1018 temp = p->subframe[i].ad_cb_gain * GAIN_LEVELS +
1019 p->subframe[i].amp_index;
1020 if (p->cur_rate == RATE_6300)
1021 temp += p->subframe[i].dirac_train << 11;
1022 put_bits(&pb, 12, temp);
1023 }
1024
1025 put_bits(&pb, 1, p->subframe[0].grid_index);
1026 put_bits(&pb, 1, p->subframe[1].grid_index);
1027 put_bits(&pb, 1, p->subframe[2].grid_index);
1028 put_bits(&pb, 1, p->subframe[3].grid_index);
1029
1030 if (p->cur_rate == RATE_6300) {
1031 skip_put_bits(&pb, 1); /* reserved bit */
1032
1033 /* Write 13 bit combined position index */
1034 temp = (p->subframe[0].pulse_pos >> 16) * 810 +
1035 (p->subframe[1].pulse_pos >> 14) * 90 +
1036 (p->subframe[2].pulse_pos >> 16) * 9 +
1037 (p->subframe[3].pulse_pos >> 14);
1038 put_bits(&pb, 13, temp);
1039
1040 put_bits(&pb, 16, p->subframe[0].pulse_pos & 0xffff);
1041 put_bits(&pb, 14, p->subframe[1].pulse_pos & 0x3fff);
1042 put_bits(&pb, 16, p->subframe[2].pulse_pos & 0xffff);
1043 put_bits(&pb, 14, p->subframe[3].pulse_pos & 0x3fff);
1044
1045 put_bits(&pb, 6, p->subframe[0].pulse_sign);
1046 put_bits(&pb, 5, p->subframe[1].pulse_sign);
1047 put_bits(&pb, 6, p->subframe[2].pulse_sign);
1048 put_bits(&pb, 5, p->subframe[3].pulse_sign);
1049 }
1050
1051 flush_put_bits(&pb);
1052 return frame_size[info_bits];
1053 }
1054
1055 static int g723_1_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1056 const AVFrame *frame, int *got_packet_ptr)
1057 {
1058 G723_1_Context *p = avctx->priv_data;
1059 int16_t unq_lpc[LPC_ORDER * SUBFRAMES];
1060 int16_t qnt_lpc[LPC_ORDER * SUBFRAMES];
1061 int16_t cur_lsp[LPC_ORDER];
1062 int16_t weighted_lpc[LPC_ORDER * SUBFRAMES << 1];
1063 int16_t vector[FRAME_LEN + PITCH_MAX];
1064 int offset, ret, i, j;
1065 int16_t *in, *start;
1066 HFParam hf[4];
1067
1068 /* duplicate input */
1069 start = in = av_malloc(frame->nb_samples * sizeof(int16_t));
1070 if (!in)
1071 return AVERROR(ENOMEM);
1072 memcpy(in, frame->data[0], frame->nb_samples * sizeof(int16_t));
1073
1074 highpass_filter(in, &p->hpf_fir_mem, &p->hpf_iir_mem);
1075
1076 memcpy(vector, p->prev_data, HALF_FRAME_LEN * sizeof(int16_t));
1077 memcpy(vector + HALF_FRAME_LEN, in, FRAME_LEN * sizeof(int16_t));
1078
1079 comp_lpc_coeff(vector, unq_lpc);
1080 lpc2lsp(&unq_lpc[LPC_ORDER * 3], p->prev_lsp, cur_lsp);
1081 lsp_quantize(p->lsp_index, cur_lsp, p->prev_lsp);
1082
1083 /* Update memory */
1084 memcpy(vector + LPC_ORDER, p->prev_data + SUBFRAME_LEN,
1085 sizeof(int16_t) * SUBFRAME_LEN);
1086 memcpy(vector + LPC_ORDER + SUBFRAME_LEN, in,
1087 sizeof(int16_t) * (HALF_FRAME_LEN + SUBFRAME_LEN));
1088 memcpy(p->prev_data, in + HALF_FRAME_LEN,
1089 sizeof(int16_t) * HALF_FRAME_LEN);
1090 memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
1091
1092 perceptual_filter(p, weighted_lpc, unq_lpc, vector);
1093
1094 memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);
1095 memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
1096 memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
1097
1098 ff_g723_1_scale_vector(vector, vector, FRAME_LEN + PITCH_MAX);
1099
1100 p->pitch_lag[0] = estimate_pitch(vector, PITCH_MAX);
1101 p->pitch_lag[1] = estimate_pitch(vector, PITCH_MAX + HALF_FRAME_LEN);
1102
1103 for (i = PITCH_MAX, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1104 comp_harmonic_coeff(vector + i, p->pitch_lag[j >> 1], hf + j);
1105
1106 memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);
1107 memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);
1108 memcpy(p->prev_weight_sig, vector + FRAME_LEN, sizeof(int16_t) * PITCH_MAX);
1109
1110 for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)
1111 harmonic_filter(hf + j, vector + PITCH_MAX + i, in + i);
1112
1113 ff_g723_1_inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, 0);
1114 ff_g723_1_lsp_interpolate(qnt_lpc, cur_lsp, p->prev_lsp);
1115
1116 memcpy(p->prev_lsp, cur_lsp, sizeof(int16_t) * LPC_ORDER);
1117
1118 offset = 0;
1119 for (i = 0; i < SUBFRAMES; i++) {
1120 int16_t impulse_resp[SUBFRAME_LEN];
1121 int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];
1122 int16_t flt_in[SUBFRAME_LEN];
1123 int16_t zero[LPC_ORDER], fir[LPC_ORDER], iir[LPC_ORDER];
1124
1125 /**
1126 * Compute the combined impulse response of the synthesis filter,
1127 * formant perceptual weighting filter and harmonic noise shaping filter
1128 */
1129 memset(zero, 0, sizeof(int16_t) * LPC_ORDER);
1130 memset(vector, 0, sizeof(int16_t) * PITCH_MAX);
1131 memset(flt_in, 0, sizeof(int16_t) * SUBFRAME_LEN);
1132
1133 flt_in[0] = 1 << 13; /* Unit impulse */
1134 synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
1135 zero, zero, flt_in, vector + PITCH_MAX, 1);
1136 harmonic_filter(hf + i, vector + PITCH_MAX, impulse_resp);
1137
1138 /* Compute the combined zero input response */
1139 flt_in[0] = 0;
1140 memcpy(fir, p->perf_fir_mem, sizeof(int16_t) * LPC_ORDER);
1141 memcpy(iir, p->perf_iir_mem, sizeof(int16_t) * LPC_ORDER);
1142
1143 synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
1144 fir, iir, flt_in, vector + PITCH_MAX, 0);
1145 memcpy(vector, p->harmonic_mem, sizeof(int16_t) * PITCH_MAX);
1146 harmonic_noise_sub(hf + i, vector + PITCH_MAX, in);
1147
1148 acb_search(p, residual, impulse_resp, in, i);
1149 ff_g723_1_gen_acb_excitation(residual, p->prev_excitation,
1150 p->pitch_lag[i >> 1], &p->subframe[i],
1151 RATE_6300);
1152 sub_acb_contrib(residual, impulse_resp, in);
1153
1154 fcb_search(p, impulse_resp, in, i);
1155
1156 /* Reconstruct the excitation */
1157 ff_g723_1_gen_acb_excitation(impulse_resp, p->prev_excitation,
1158 p->pitch_lag[i >> 1], &p->subframe[i],
1159 RATE_6300);
1160
1161 memmove(p->prev_excitation, p->prev_excitation + SUBFRAME_LEN,
1162 sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
1163 for (j = 0; j < SUBFRAME_LEN; j++)
1164 in[j] = av_clip_int16((in[j] << 1) + impulse_resp[j]);
1165 memcpy(p->prev_excitation + PITCH_MAX - SUBFRAME_LEN, in,
1166 sizeof(int16_t) * SUBFRAME_LEN);
1167
1168 /* Update filter memories */
1169 synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),
1170 p->perf_fir_mem, p->perf_iir_mem,
1171 in, vector + PITCH_MAX, 0);
1172 memmove(p->harmonic_mem, p->harmonic_mem + SUBFRAME_LEN,
1173 sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));
1174 memcpy(p->harmonic_mem + PITCH_MAX - SUBFRAME_LEN, vector + PITCH_MAX,
1175 sizeof(int16_t) * SUBFRAME_LEN);
1176
1177 in += SUBFRAME_LEN;
1178 offset += LPC_ORDER;
1179 }
1180
1181 av_free(start);
1182
1183 ret = ff_alloc_packet(avpkt, 24);
1184 if (ret < 0)
1185 return ret;
1186
1187 *got_packet_ptr = 1;
1188 return pack_bitstream(p, avpkt);
1189 }
1190
1191 AVCodec ff_g723_1_encoder = {
1192 .name = "g723_1",
1193 .long_name = NULL_IF_CONFIG_SMALL("G.723.1"),
1194 .type = AVMEDIA_TYPE_AUDIO,
1195 .id = AV_CODEC_ID_G723_1,
1196 .priv_data_size = sizeof(G723_1_Context),
1197 .init = g723_1_encode_init,
1198 .encode2 = g723_1_encode_frame,
1199 .sample_fmts = (const enum AVSampleFormat[]) {
1200 AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_NONE
1201 },
1202 };