2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
7 * Kevin P. Fleming <kpfleming@digium.com>
9 * Based on frompcm.c and topcm.c from the Emiliano MIPL browser/
10 * interpreter. See http://www.bsdtelephony.com.mx
12 * See http://www.asterisk.org for more information about
13 * the Asterisk project. Please do not directly contact
14 * any of the maintainers of this project for assistance;
15 * the project provides a web site, mailing lists and IRC
16 * channels for your use.
18 * This program is free software, distributed under the terms of
19 * the GNU General Public License Version 2. See the LICENSE file
20 * at the top of the source tree.
25 * \brief codec_g726.c - translate between signed linear and ITU G.726-32kbps (both RFC3551 and AAL2 codeword packing)
32 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
34 #include "asterisk/lock.h"
35 #include "asterisk/linkedlists.h"
36 #include "asterisk/module.h"
37 #include "asterisk/config.h"
38 #include "asterisk/translate.h"
39 #include "asterisk/utils.h"
44 /* define NOT_BLI to use a faster but not bit-level identical version */
48 # if defined(_MSC_VER)
49 typedef __int64 sint64;
50 # elif defined(__GNUC__)
51 typedef long long sint64;
53 # error 64-bit integer type is not defined for your compiler/platform
57 #define BUFFER_SAMPLES 8096 /* size for the translation buffers */
60 /* Sample frame data */
61 #include "asterisk/slin.h"
65 * The following is the definition of the state structure
66 * used by the G.726 encoder and decoder to preserve their internal
67 * state between successive calls. The meanings of the majority
68 * of the state structure fields are explained in detail in the
69 * CCITT Recommendation G.721. The field names are essentially identical
70 * to variable names in the bit level description of the coding algorithm
71 * included in this Recommendation.
74 long yl; /* Locked or steady state step size multiplier. */
75 int yu; /* Unlocked or non-steady state step size multiplier. */
76 int dms; /* Short term energy estimate. */
77 int dml; /* Long term energy estimate. */
78 int ap; /* Linear weighting coefficient of 'yl' and 'yu'. */
79 int a[2]; /* Coefficients of pole portion of prediction filter.
80 * stored as fixed-point 1==2^14 */
81 int b[6]; /* Coefficients of zero portion of prediction filter.
82 * stored as fixed-point 1==2^14 */
83 int pk[2]; /* Signs of previous two samples of a partially
84 * reconstructed signal. */
85 int dq[6]; /* Previous 6 samples of the quantized difference signal
86 * stored as fixed point 1==2^12,
87 * or in internal floating point format */
88 int sr[2]; /* Previous 2 samples of the quantized difference signal
89 * stored as fixed point 1==2^12,
90 * or in internal floating point format */
91 int td; /* delayed tone detect, new in 1988 version */
94 static int qtab_721[7] = {-124, 80, 178, 246, 300, 349, 400};
96 * Maps G.721 code word to reconstructed scale factor normalized log
99 static int _dqlntab[16] = {-2048, 4, 135, 213, 273, 323, 373, 425,
100 425, 373, 323, 273, 213, 135, 4, -2048};
102 /* Maps G.721 code word to log of scale factor multiplier. */
103 static int _witab[16] = {-12, 18, 41, 64, 112, 198, 355, 1122,
104 1122, 355, 198, 112, 64, 41, 18, -12};
106 * Maps G.721 code words to a set of values whose long and short
107 * term averages are computed and then compared to give an indication
108 * how stationary (steady state) the signal is.
110 static int _fitab[16] = {0, 0, 0, 0x200, 0x200, 0x200, 0x600, 0xE00,
111 0xE00, 0x600, 0x200, 0x200, 0x200, 0, 0, 0};
117 * This routine initializes and/or resets the g726_state structure
118 * pointed to by 'state_ptr'.
119 * All the initial state values are specified in the CCITT G.721 document.
121 static void g726_init_state(struct g726_state *state_ptr)
125 state_ptr->yl = 34816;
130 for (cnta = 0; cnta < 2; cnta++) {
131 state_ptr->a[cnta] = 0;
132 state_ptr->pk[cnta] = 0;
134 state_ptr->sr[cnta] = 1;
136 state_ptr->sr[cnta] = 32;
139 for (cnta = 0; cnta < 6; cnta++) {
140 state_ptr->b[cnta] = 0;
142 state_ptr->dq[cnta] = 1;
144 state_ptr->dq[cnta] = 32;
153 * quantizes the input val against the table of integers.
154 * It returns i if table[i - 1] <= val < table[i].
156 * Using linear search for simple coding.
158 static int quan(int val, int *table, int size)
162 for (i = 0; i < size && val >= *table; ++i, ++table)
167 #ifdef NOT_BLI /* faster non-identical version */
172 * computes the estimated signal from 6-zero predictor.
175 static int predictor_zero(struct g726_state *state_ptr)
176 { /* divide by 2 is necessary here to handle negative numbers correctly */
179 for (sezi = 0, i = 0; i < 6; i++) /* ACCUM */
180 sezi += (sint64)state_ptr->b[i] * state_ptr->dq[i];
181 return (int)(sezi >> 13) / 2 /* 2^14 */;
187 * computes the estimated signal from 2-pole predictor.
190 static int predictor_pole(struct g726_state *state_ptr)
191 { /* divide by 2 is necessary here to handle negative numbers correctly */
192 return (int)(((sint64)state_ptr->a[1] * state_ptr->sr[1] +
193 (sint64)state_ptr->a[0] * state_ptr->sr[0]) >> 13) / 2 /* 2^14 */;
196 #else /* NOT_BLI - identical version */
200 * returns the integer product of the fixed-point number "an" (1==2^12) and
201 * "floating point" representation (4-bit exponent, 6-bit mantessa) "srn".
203 static int fmult(int an, int srn)
205 int anmag, anexp, anmant;
209 anmag = (an > 0) ? an : ((-an) & 0x1FFF);
210 anexp = ilog2(anmag) - 5;
211 anmant = (anmag == 0) ? 32 :
212 (anexp >= 0) ? anmag >> anexp : anmag << -anexp;
213 wanexp = anexp + ((srn >> 6) & 0xF) - 13;
215 wanmant = (anmant * (srn & 077) + 0x30) >> 4;
216 retval = (wanexp >= 0) ? ((wanmant << wanexp) & 0x7FFF) :
217 (wanmant >> -wanexp);
219 return (((an ^ srn) < 0) ? -retval : retval);
222 static int predictor_zero(struct g726_state *state_ptr)
226 for (sezi = 0, i = 0; i < 6; i++) /* ACCUM */
227 sezi += fmult(state_ptr->b[i] >> 2, state_ptr->dq[i]);
231 static int predictor_pole(struct g726_state *state_ptr)
233 return (fmult(state_ptr->a[1] >> 2, state_ptr->sr[1]) +
234 fmult(state_ptr->a[0] >> 2, state_ptr->sr[0]));
242 * computes the quantization step size of the adaptive quantizer.
245 static int step_size(struct g726_state *state_ptr)
251 if (state_ptr->ap >= 256)
252 return (state_ptr->yu);
254 y = state_ptr->yl >> 6;
255 dif = state_ptr->yu - y;
256 al = state_ptr->ap >> 2;
258 y += (dif * al) >> 6;
260 y += (dif * al + 0x3F) >> 6;
268 * Given a raw sample, 'd', of the difference signal and a
269 * quantization step size scale factor, 'y', this routine returns the
270 * ADPCM codeword to which that sample gets quantized. The step
271 * size scale factor division operation is done in the log base 2 domain
275 int d, /* Raw difference signal sample */
276 int y, /* Step size multiplier */
277 int *table, /* quantization table */
278 int size) /* table size of integers */
280 int dqm; /* Magnitude of 'd' */
281 int exp; /* Integer part of base 2 log of 'd' */
282 int mant; /* Fractional part of base 2 log */
283 int dl; /* Log of magnitude of 'd' */
284 int dln; /* Step size scale factor normalized log */
290 * Compute base 2 log of 'd', and store in 'dl'.
296 mant = ((dqm << 7) >> exp) & 0x7F; /* Fractional portion. */
297 dl = (exp << 7) | mant;
302 * "Divide" by step size multiplier.
309 * Obtain codword i for 'd'.
311 i = quan(dln, table, size);
312 if (d < 0) /* take 1's complement of i */
313 return ((size << 1) + 1 - i);
314 else if (i == 0) /* take 1's complement of 0 */
315 return ((size << 1) + 1); /* new in 1988 */
323 * Returns reconstructed difference signal 'dq' obtained from
324 * codeword 'i' and quantization step size scale factor 'y'.
325 * Multiplication is performed in log base 2 domain as addition.
327 static int reconstruct(
328 int sign, /* 0 for non-negative value */
329 int dqln, /* G.72x codeword */
330 int y) /* Step size multiplier */
332 int dql; /* Log of 'dq' magnitude */
333 int dex; /* Integer part of log */
335 int dq; /* Reconstructed difference signal sample */
337 dql = dqln + (y >> 2); /* ADDA */
341 return (sign) ? -1 : 1;
343 return (sign) ? -0x8000 : 0;
345 } else { /* ANTILOG */
346 dex = (dql >> 7) & 15;
347 dqt = 128 + (dql & 127);
349 dq = ((dqt << 19) >> (14 - dex));
350 return (sign) ? -dq : dq;
352 dq = (dqt << 7) >> (14 - dex);
353 return (sign) ? (dq - 0x8000) : dq;
361 * updates the state variables for each output code
364 int code_size, /* distinguish 723_40 with others */
365 int y, /* quantizer step size */
366 int wi, /* scale factor multiplier */
367 int fi, /* for long/short term energies */
368 int dq, /* quantized prediction difference */
369 int sr, /* reconstructed signal */
370 int dqsez, /* difference from 2-pole predictor */
371 struct g726_state *state_ptr) /* coder state pointer */
374 int mag; /* Adaptive predictor, FLOAT A */
378 int a2p=0; /* LIMC */
382 int tr; /* tone/transition detector */
383 int ylint, thr2, dqthr;
387 pk0 = (dqsez < 0) ? 1 : 0; /* needed in updating predictor poles */
390 mag = abs(dq / 0x1000); /* prediction difference magnitude */
392 mag = dq & 0x7FFF; /* prediction difference magnitude */
395 ylint = state_ptr->yl >> 15; /* exponent part of yl */
396 ylfrac = (state_ptr->yl >> 10) & 0x1F; /* fractional part of yl */
397 thr1 = (32 + ylfrac) << ylint; /* threshold */
398 thr2 = (ylint > 9) ? 31 << 10 : thr1; /* limit thr2 to 31 << 10 */
399 dqthr = (thr2 + (thr2 >> 1)) >> 1; /* dqthr = 0.75 * thr2 */
400 if (state_ptr->td == 0) /* signal supposed voice */
402 else if (mag <= dqthr) /* supposed data, but small mag */
403 tr = 0; /* treated as voice */
404 else /* signal is data (modem) */
408 * Quantizer scale factor adaptation.
411 /* FUNCTW & FILTD & DELAY */
412 /* update non-steady state step size multiplier */
413 state_ptr->yu = y + ((wi - y) >> 5);
416 if (state_ptr->yu < 544) /* 544 <= yu <= 5120 */
418 else if (state_ptr->yu > 5120)
419 state_ptr->yu = 5120;
422 /* update steady state step size multiplier */
423 state_ptr->yl += state_ptr->yu + ((-state_ptr->yl) >> 6);
426 * Adaptive predictor coefficients.
428 if (tr == 1) { /* reset a's and b's for modem signal */
437 } else { /* update a's and b's */
438 pks1 = pk0 ^ state_ptr->pk[0]; /* UPA2 */
440 /* update predictor pole a[1] */
441 a2p = state_ptr->a[1] - (state_ptr->a[1] >> 7);
443 fa1 = (pks1) ? state_ptr->a[0] : -state_ptr->a[0];
444 if (fa1 < -8191) /* a2p = function of fa1 */
451 if (pk0 ^ state_ptr->pk[1])
455 else if (a2p >= 12416)
459 else if (a2p <= -12416)
461 else if (a2p >= 12160)
468 state_ptr->a[1] = a2p;
471 /* update predictor pole a[0] */
472 state_ptr->a[0] -= state_ptr->a[0] >> 8;
475 state_ptr->a[0] += 192;
477 state_ptr->a[0] -= 192;
481 if (state_ptr->a[0] < -a1ul)
482 state_ptr->a[0] = -a1ul;
483 else if (state_ptr->a[0] > a1ul)
484 state_ptr->a[0] = a1ul;
486 /* UPB : update predictor zeros b[6] */
487 for (cnt = 0; cnt < 6; cnt++) {
488 if (code_size == 5) /* for 40Kbps G.723 */
489 state_ptr->b[cnt] -= state_ptr->b[cnt] >> 9;
490 else /* for G.721 and 24Kbps G.723 */
491 state_ptr->b[cnt] -= state_ptr->b[cnt] >> 8;
494 if ((dq ^ state_ptr->dq[cnt]) >= 0)
495 state_ptr->b[cnt] += 128;
497 state_ptr->b[cnt] -= 128;
502 for (cnt = 5; cnt > 0; cnt--)
503 state_ptr->dq[cnt] = state_ptr->dq[cnt-1];
505 state_ptr->dq[0] = dq;
507 /* FLOAT A : convert dq[0] to 4-bit exp, 6-bit mantissa f.p. */
509 state_ptr->dq[0] = (dq >= 0) ? 0x20 : 0x20 - 0x400;
511 exp = ilog2(mag) + 1;
512 state_ptr->dq[0] = (dq >= 0) ?
513 (exp << 6) + ((mag << 6) >> exp) :
514 (exp << 6) + ((mag << 6) >> exp) - 0x400;
518 state_ptr->sr[1] = state_ptr->sr[0];
520 state_ptr->sr[0] = sr;
522 /* FLOAT B : convert sr to 4-bit exp., 6-bit mantissa f.p. */
524 state_ptr->sr[0] = 0x20;
527 state_ptr->sr[0] = (exp << 6) + ((sr << 6) >> exp);
528 } else if (sr > -0x8000) {
530 exp = ilog2(mag) + 1;
531 state_ptr->sr[0] = (exp << 6) + ((mag << 6) >> exp) - 0x400;
533 state_ptr->sr[0] = 0x20 - 0x400;
537 state_ptr->pk[1] = state_ptr->pk[0];
538 state_ptr->pk[0] = pk0;
541 if (tr == 1) /* this sample has been treated as data */
542 state_ptr->td = 0; /* next one will be treated as voice */
543 else if (a2p < -11776) /* small sample-to-sample correlation */
544 state_ptr->td = 1; /* signal may be data */
545 else /* signal is voice */
549 * Adaptation speed control.
551 state_ptr->dms += (fi - state_ptr->dms) >> 5; /* FILTA */
552 state_ptr->dml += (((fi << 2) - state_ptr->dml) >> 7); /* FILTB */
556 else if (y < 1536) /* SUBTC */
557 state_ptr->ap += (0x200 - state_ptr->ap) >> 4;
558 else if (state_ptr->td == 1)
559 state_ptr->ap += (0x200 - state_ptr->ap) >> 4;
560 else if (abs((state_ptr->dms << 2) - state_ptr->dml) >=
561 (state_ptr->dml >> 3))
562 state_ptr->ap += (0x200 - state_ptr->ap) >> 4;
564 state_ptr->ap += (-state_ptr->ap) >> 4;
572 * Decodes a 4-bit code of G.726-32 encoded data of i and
573 * returns the resulting linear PCM, A-law or u-law value.
574 * return -1 for unknown out_coding value.
576 static int g726_decode(int i, struct g726_state *state_ptr)
578 int sezi, sez, se; /* ACCUM */
584 i &= 0x0f; /* mask to get proper bits */
586 sezi = predictor_zero(state_ptr);
588 se = sezi + predictor_pole(state_ptr); /* estimated signal */
590 sezi = predictor_zero(state_ptr);
592 se = (sezi + predictor_pole(state_ptr)) >> 1; /* estimated signal */
595 y = step_size(state_ptr); /* dynamic quantizer step size */
597 dq = reconstruct(i & 8, _dqlntab[i], y); /* quantized diff. */
600 sr = se + dq; /* reconst. signal */
601 dqsez = dq + sez; /* pole prediction diff. */
603 sr = (dq < 0) ? se - (dq & 0x3FFF) : se + dq; /* reconst. signal */
604 dqsez = sr - se + sez; /* pole prediction diff. */
607 update(4, y, _witab[i] << 5, _fitab[i], dq, sr, dqsez, state_ptr);
610 return (sr >> 10); /* sr was 26-bit dynamic range */
612 return (sr << 2); /* sr was 14-bit dynamic range */
619 * Encodes the input vale of linear PCM, A-law or u-law data sl and returns
620 * the resulting code. -1 is returned for unknown input coding value.
622 static int g726_encode(int sl, struct g726_state *state_ptr)
624 int sezi, se, sez; /* ACCUM */
628 int dqsez; /* ADDC */
632 sl <<= 10; /* 26-bit dynamic range */
634 sezi = predictor_zero(state_ptr);
636 se = sezi + predictor_pole(state_ptr); /* estimated signal */
638 sl >>= 2; /* 14-bit dynamic range */
640 sezi = predictor_zero(state_ptr);
642 se = (sezi + predictor_pole(state_ptr)) >> 1; /* estimated signal */
645 d = sl - se; /* estimation difference */
647 /* quantize the prediction difference */
648 y = step_size(state_ptr); /* quantizer step size */
652 i = quantize(d, y, qtab_721, 7); /* i = G726 code */
654 dq = reconstruct(i & 8, _dqlntab[i], y); /* quantized est diff */
657 sr = se + dq; /* reconst. signal */
658 dqsez = dq + sez; /* pole prediction diff. */
660 sr = (dq < 0) ? se - (dq & 0x3FFF) : se + dq; /* reconst. signal */
661 dqsez = sr - se + sez; /* pole prediction diff. */
664 update(4, y, _witab[i] << 5, _fitab[i], dq, sr, dqsez, state_ptr);
670 * Private workspace for translating signed linear signals to G726.
671 * Don't bother to define two distinct structs.
674 struct g726_coder_pvt {
675 /* buffer any odd byte in input - 0x80 + (value & 0xf) if present */
676 unsigned char next_flag;
677 struct g726_state g726;
680 /*! \brief init a new instance of g726_coder_pvt. */
681 static int lintog726_new(struct ast_trans_pvt *pvt)
683 struct g726_coder_pvt *tmp = pvt->pvt;
685 g726_init_state(&tmp->g726);
690 /*! \brief decode packed 4-bit G726 values (AAL2 packing) and store in buffer. */
691 static int g726aal2tolin_framein (struct ast_trans_pvt *pvt, struct ast_frame *f)
693 struct g726_coder_pvt *tmp = pvt->pvt;
694 unsigned char *src = f->data.ptr;
695 int16_t *dst = pvt->outbuf.i16 + pvt->samples;
698 for (i = 0; i < f->datalen; i++) {
699 *dst++ = g726_decode((src[i] >> 4) & 0xf, &tmp->g726);
700 *dst++ = g726_decode(src[i] & 0x0f, &tmp->g726);
703 pvt->samples += f->samples;
704 pvt->datalen += 2 * f->samples; /* 2 bytes/sample */
709 /*! \brief compress and store data (4-bit G726 samples, AAL2 packing) in outbuf */
710 static int lintog726aal2_framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
712 struct g726_coder_pvt *tmp = pvt->pvt;
713 int16_t *src = f->data.ptr;
716 for (i = 0; i < f->samples; i++) {
717 unsigned char d = g726_encode(src[i], &tmp->g726); /* this sample */
719 if (tmp->next_flag & 0x80) { /* merge with leftover sample */
720 pvt->outbuf.c[pvt->datalen++] = ((tmp->next_flag & 0xf)<< 4) | d;
721 pvt->samples += 2; /* 2 samples per byte */
724 tmp->next_flag = 0x80 | d;
731 /*! \brief decode packed 4-bit G726 values (RFC3551 packing) and store in buffer. */
732 static int g726tolin_framein (struct ast_trans_pvt *pvt, struct ast_frame *f)
734 struct g726_coder_pvt *tmp = pvt->pvt;
735 unsigned char *src = f->data.ptr;
736 int16_t *dst = pvt->outbuf.i16 + pvt->samples;
739 for (i = 0; i < f->datalen; i++) {
740 *dst++ = g726_decode(src[i] & 0x0f, &tmp->g726);
741 *dst++ = g726_decode((src[i] >> 4) & 0xf, &tmp->g726);
744 pvt->samples += f->samples;
745 pvt->datalen += 2 * f->samples; /* 2 bytes/sample */
750 /*! \brief compress and store data (4-bit G726 samples, RFC3551 packing) in outbuf */
751 static int lintog726_framein(struct ast_trans_pvt *pvt, struct ast_frame *f)
753 struct g726_coder_pvt *tmp = pvt->pvt;
754 int16_t *src = f->data.ptr;
757 for (i = 0; i < f->samples; i++) {
758 unsigned char d = g726_encode(src[i], &tmp->g726); /* this sample */
760 if (tmp->next_flag & 0x80) { /* merge with leftover sample */
761 pvt->outbuf.c[pvt->datalen++] = (d << 4) | (tmp->next_flag & 0xf);
762 pvt->samples += 2; /* 2 samples per byte */
765 tmp->next_flag = 0x80 | d;
772 static struct ast_translator g726tolin = {
774 .srcfmt = AST_FORMAT_G726,
775 .dstfmt = AST_FORMAT_SLINEAR,
776 .newpvt = lintog726_new, /* same for both directions */
777 .framein = g726tolin_framein,
778 .sample = g726_sample,
779 .desc_size = sizeof(struct g726_coder_pvt),
780 .buffer_samples = BUFFER_SAMPLES,
781 .buf_size = BUFFER_SAMPLES * 2,
784 static struct ast_translator lintog726 = {
786 .srcfmt = AST_FORMAT_SLINEAR,
787 .dstfmt = AST_FORMAT_G726,
788 .newpvt = lintog726_new, /* same for both directions */
789 .framein = lintog726_framein,
790 .sample = slin8_sample,
791 .desc_size = sizeof(struct g726_coder_pvt),
792 .buffer_samples = BUFFER_SAMPLES,
793 .buf_size = BUFFER_SAMPLES/2,
796 static struct ast_translator g726aal2tolin = {
797 .name = "g726aal2tolin",
798 .srcfmt = AST_FORMAT_G726_AAL2,
799 .dstfmt = AST_FORMAT_SLINEAR,
800 .newpvt = lintog726_new, /* same for both directions */
801 .framein = g726aal2tolin_framein,
802 .sample = g726_sample,
803 .desc_size = sizeof(struct g726_coder_pvt),
804 .buffer_samples = BUFFER_SAMPLES,
805 .buf_size = BUFFER_SAMPLES * 2,
808 static struct ast_translator lintog726aal2 = {
809 .name = "lintog726aal2",
810 .srcfmt = AST_FORMAT_SLINEAR,
811 .dstfmt = AST_FORMAT_G726_AAL2,
812 .newpvt = lintog726_new, /* same for both directions */
813 .framein = lintog726aal2_framein,
814 .sample = slin8_sample,
815 .desc_size = sizeof(struct g726_coder_pvt),
816 .buffer_samples = BUFFER_SAMPLES,
817 .buf_size = BUFFER_SAMPLES / 2,
820 static int reload(void)
822 return AST_MODULE_LOAD_SUCCESS;
825 static int unload_module(void)
829 res |= ast_unregister_translator(&g726tolin);
830 res |= ast_unregister_translator(&lintog726);
832 res |= ast_unregister_translator(&g726aal2tolin);
833 res |= ast_unregister_translator(&lintog726aal2);
838 static int load_module(void)
842 res |= ast_register_translator(&g726tolin);
843 res |= ast_register_translator(&lintog726);
845 res |= ast_register_translator(&g726aal2tolin);
846 res |= ast_register_translator(&lintog726aal2);
850 return AST_MODULE_LOAD_FAILURE;
853 return AST_MODULE_LOAD_SUCCESS;
856 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "ITU G.726-32kbps G726 Transcoder",
858 .unload = unload_module,