You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

495 lines
15KB

  1. /*
  2. * G.726 ADPCM audio codec
  3. * Copyright (c) 2004 Roman Shaposhnik
  4. *
  5. * This is a very straightforward rendition of the G.726
  6. * Section 4 "Computational Details".
  7. *
  8. * This file is part of Libav.
  9. *
  10. * Libav is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU Lesser General Public
  12. * License as published by the Free Software Foundation; either
  13. * version 2.1 of the License, or (at your option) any later version.
  14. *
  15. * Libav is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. * Lesser General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public
  21. * License along with Libav; if not, write to the Free Software
  22. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  23. */
  24. #include <limits.h>
  25. #include "libavutil/avassert.h"
  26. #include "libavutil/channel_layout.h"
  27. #include "libavutil/opt.h"
  28. #include "avcodec.h"
  29. #include "internal.h"
  30. #include "get_bits.h"
  31. #include "put_bits.h"
  32. /**
  33. * G.726 11bit float.
  34. * G.726 Standard uses rather odd 11bit floating point arithmentic for
  35. * numerous occasions. It's a mistery to me why they did it this way
  36. * instead of simply using 32bit integer arithmetic.
  37. */
  38. typedef struct Float11 {
  39. uint8_t sign; /**< 1bit sign */
  40. uint8_t exp; /**< 4bit exponent */
  41. uint8_t mant; /**< 6bit mantissa */
  42. } Float11;
  43. static inline Float11* i2f(int i, Float11* f)
  44. {
  45. f->sign = (i < 0);
  46. if (f->sign)
  47. i = -i;
  48. f->exp = av_log2_16bit(i) + !!i;
  49. f->mant = i? (i<<6) >> f->exp : 1<<5;
  50. return f;
  51. }
  52. static inline int16_t mult(Float11* f1, Float11* f2)
  53. {
  54. int res, exp;
  55. exp = f1->exp + f2->exp;
  56. res = (((f1->mant * f2->mant) + 0x30) >> 4);
  57. res = exp > 19 ? res << (exp - 19) : res >> (19 - exp);
  58. return (f1->sign ^ f2->sign) ? -res : res;
  59. }
  60. static inline int sgn(int value)
  61. {
  62. return (value < 0) ? -1 : 1;
  63. }
  64. typedef struct G726Tables {
  65. const int* quant; /**< quantization table */
  66. const int16_t* iquant; /**< inverse quantization table */
  67. const int16_t* W; /**< special table #1 ;-) */
  68. const uint8_t* F; /**< special table #2 */
  69. } G726Tables;
  70. typedef struct G726Context {
  71. AVClass *class;
  72. AVFrame frame;
  73. G726Tables tbls; /**< static tables needed for computation */
  74. Float11 sr[2]; /**< prev. reconstructed samples */
  75. Float11 dq[6]; /**< prev. difference */
  76. int a[2]; /**< second order predictor coeffs */
  77. int b[6]; /**< sixth order predictor coeffs */
  78. int pk[2]; /**< signs of prev. 2 sez + dq */
  79. int ap; /**< scale factor control */
  80. int yu; /**< fast scale factor */
  81. int yl; /**< slow scale factor */
  82. int dms; /**< short average magnitude of F[i] */
  83. int dml; /**< long average magnitude of F[i] */
  84. int td; /**< tone detect */
  85. int se; /**< estimated signal for the next iteration */
  86. int sez; /**< estimated second order prediction */
  87. int y; /**< quantizer scaling factor for the next iteration */
  88. int code_size;
  89. } G726Context;
  90. static const int quant_tbl16[] = /**< 16kbit/s 2bits per sample */
  91. { 260, INT_MAX };
  92. static const int16_t iquant_tbl16[] =
  93. { 116, 365, 365, 116 };
  94. static const int16_t W_tbl16[] =
  95. { -22, 439, 439, -22 };
  96. static const uint8_t F_tbl16[] =
  97. { 0, 7, 7, 0 };
  98. static const int quant_tbl24[] = /**< 24kbit/s 3bits per sample */
  99. { 7, 217, 330, INT_MAX };
  100. static const int16_t iquant_tbl24[] =
  101. { INT16_MIN, 135, 273, 373, 373, 273, 135, INT16_MIN };
  102. static const int16_t W_tbl24[] =
  103. { -4, 30, 137, 582, 582, 137, 30, -4 };
  104. static const uint8_t F_tbl24[] =
  105. { 0, 1, 2, 7, 7, 2, 1, 0 };
  106. static const int quant_tbl32[] = /**< 32kbit/s 4bits per sample */
  107. { -125, 79, 177, 245, 299, 348, 399, INT_MAX };
  108. static const int16_t iquant_tbl32[] =
  109. { INT16_MIN, 4, 135, 213, 273, 323, 373, 425,
  110. 425, 373, 323, 273, 213, 135, 4, INT16_MIN };
  111. static const int16_t W_tbl32[] =
  112. { -12, 18, 41, 64, 112, 198, 355, 1122,
  113. 1122, 355, 198, 112, 64, 41, 18, -12};
  114. static const uint8_t F_tbl32[] =
  115. { 0, 0, 0, 1, 1, 1, 3, 7, 7, 3, 1, 1, 1, 0, 0, 0 };
  116. static const int quant_tbl40[] = /**< 40kbit/s 5bits per sample */
  117. { -122, -16, 67, 138, 197, 249, 297, 338,
  118. 377, 412, 444, 474, 501, 527, 552, INT_MAX };
  119. static const int16_t iquant_tbl40[] =
  120. { INT16_MIN, -66, 28, 104, 169, 224, 274, 318,
  121. 358, 395, 429, 459, 488, 514, 539, 566,
  122. 566, 539, 514, 488, 459, 429, 395, 358,
  123. 318, 274, 224, 169, 104, 28, -66, INT16_MIN };
  124. static const int16_t W_tbl40[] =
  125. { 14, 14, 24, 39, 40, 41, 58, 100,
  126. 141, 179, 219, 280, 358, 440, 529, 696,
  127. 696, 529, 440, 358, 280, 219, 179, 141,
  128. 100, 58, 41, 40, 39, 24, 14, 14 };
  129. static const uint8_t F_tbl40[] =
  130. { 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 6,
  131. 6, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  132. static const G726Tables G726Tables_pool[] =
  133. {{ quant_tbl16, iquant_tbl16, W_tbl16, F_tbl16 },
  134. { quant_tbl24, iquant_tbl24, W_tbl24, F_tbl24 },
  135. { quant_tbl32, iquant_tbl32, W_tbl32, F_tbl32 },
  136. { quant_tbl40, iquant_tbl40, W_tbl40, F_tbl40 }};
  137. /**
  138. * Para 4.2.2 page 18: Adaptive quantizer.
  139. */
  140. static inline uint8_t quant(G726Context* c, int d)
  141. {
  142. int sign, exp, i, dln;
  143. sign = i = 0;
  144. if (d < 0) {
  145. sign = 1;
  146. d = -d;
  147. }
  148. exp = av_log2_16bit(d);
  149. dln = ((exp<<7) + (((d<<7)>>exp)&0x7f)) - (c->y>>2);
  150. while (c->tbls.quant[i] < INT_MAX && c->tbls.quant[i] < dln)
  151. ++i;
  152. if (sign)
  153. i = ~i;
  154. if (c->code_size != 2 && i == 0) /* I'm not sure this is a good idea */
  155. i = 0xff;
  156. return i;
  157. }
  158. /**
  159. * Para 4.2.3 page 22: Inverse adaptive quantizer.
  160. */
  161. static inline int16_t inverse_quant(G726Context* c, int i)
  162. {
  163. int dql, dex, dqt;
  164. dql = c->tbls.iquant[i] + (c->y >> 2);
  165. dex = (dql>>7) & 0xf; /* 4bit exponent */
  166. dqt = (1<<7) + (dql & 0x7f); /* log2 -> linear */
  167. return (dql < 0) ? 0 : ((dqt<<dex) >> 7);
  168. }
  169. static int16_t g726_decode(G726Context* c, int I)
  170. {
  171. int dq, re_signal, pk0, fa1, i, tr, ylint, ylfrac, thr2, al, dq0;
  172. Float11 f;
  173. int I_sig= I >> (c->code_size - 1);
  174. dq = inverse_quant(c, I);
  175. /* Transition detect */
  176. ylint = (c->yl >> 15);
  177. ylfrac = (c->yl >> 10) & 0x1f;
  178. thr2 = (ylint > 9) ? 0x1f << 10 : (0x20 + ylfrac) << ylint;
  179. tr= (c->td == 1 && dq > ((3*thr2)>>2));
  180. if (I_sig) /* get the sign */
  181. dq = -dq;
  182. re_signal = c->se + dq;
  183. /* Update second order predictor coefficient A2 and A1 */
  184. pk0 = (c->sez + dq) ? sgn(c->sez + dq) : 0;
  185. dq0 = dq ? sgn(dq) : 0;
  186. if (tr) {
  187. c->a[0] = 0;
  188. c->a[1] = 0;
  189. for (i=0; i<6; i++)
  190. c->b[i] = 0;
  191. } else {
  192. /* This is a bit crazy, but it really is +255 not +256 */
  193. fa1 = av_clip((-c->a[0]*c->pk[0]*pk0)>>5, -256, 255);
  194. c->a[1] += 128*pk0*c->pk[1] + fa1 - (c->a[1]>>7);
  195. c->a[1] = av_clip(c->a[1], -12288, 12288);
  196. c->a[0] += 64*3*pk0*c->pk[0] - (c->a[0] >> 8);
  197. c->a[0] = av_clip(c->a[0], -(15360 - c->a[1]), 15360 - c->a[1]);
  198. for (i=0; i<6; i++)
  199. c->b[i] += 128*dq0*sgn(-c->dq[i].sign) - (c->b[i]>>8);
  200. }
  201. /* Update Dq and Sr and Pk */
  202. c->pk[1] = c->pk[0];
  203. c->pk[0] = pk0 ? pk0 : 1;
  204. c->sr[1] = c->sr[0];
  205. i2f(re_signal, &c->sr[0]);
  206. for (i=5; i>0; i--)
  207. c->dq[i] = c->dq[i-1];
  208. i2f(dq, &c->dq[0]);
  209. c->dq[0].sign = I_sig; /* Isn't it crazy ?!?! */
  210. c->td = c->a[1] < -11776;
  211. /* Update Ap */
  212. c->dms += (c->tbls.F[I]<<4) + ((- c->dms) >> 5);
  213. c->dml += (c->tbls.F[I]<<4) + ((- c->dml) >> 7);
  214. if (tr)
  215. c->ap = 256;
  216. else {
  217. c->ap += (-c->ap) >> 4;
  218. if (c->y <= 1535 || c->td || abs((c->dms << 2) - c->dml) >= (c->dml >> 3))
  219. c->ap += 0x20;
  220. }
  221. /* Update Yu and Yl */
  222. c->yu = av_clip(c->y + c->tbls.W[I] + ((-c->y)>>5), 544, 5120);
  223. c->yl += c->yu + ((-c->yl)>>6);
  224. /* Next iteration for Y */
  225. al = (c->ap >= 256) ? 1<<6 : c->ap >> 2;
  226. c->y = (c->yl + (c->yu - (c->yl>>6))*al) >> 6;
  227. /* Next iteration for SE and SEZ */
  228. c->se = 0;
  229. for (i=0; i<6; i++)
  230. c->se += mult(i2f(c->b[i] >> 2, &f), &c->dq[i]);
  231. c->sez = c->se >> 1;
  232. for (i=0; i<2; i++)
  233. c->se += mult(i2f(c->a[i] >> 2, &f), &c->sr[i]);
  234. c->se >>= 1;
  235. return av_clip(re_signal << 2, -0xffff, 0xffff);
  236. }
  237. static av_cold int g726_reset(G726Context *c)
  238. {
  239. int i;
  240. c->tbls = G726Tables_pool[c->code_size - 2];
  241. for (i=0; i<2; i++) {
  242. c->sr[i].mant = 1<<5;
  243. c->pk[i] = 1;
  244. }
  245. for (i=0; i<6; i++) {
  246. c->dq[i].mant = 1<<5;
  247. }
  248. c->yu = 544;
  249. c->yl = 34816;
  250. c->y = 544;
  251. return 0;
  252. }
  253. #if CONFIG_ADPCM_G726_ENCODER
  254. static int16_t g726_encode(G726Context* c, int16_t sig)
  255. {
  256. uint8_t i;
  257. i = quant(c, sig/4 - c->se) & ((1<<c->code_size) - 1);
  258. g726_decode(c, i);
  259. return i;
  260. }
  261. /* Interfacing to the libavcodec */
  262. static av_cold int g726_encode_init(AVCodecContext *avctx)
  263. {
  264. G726Context* c = avctx->priv_data;
  265. if (avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL &&
  266. avctx->sample_rate != 8000) {
  267. av_log(avctx, AV_LOG_ERROR, "Sample rates other than 8kHz are not "
  268. "allowed when the compliance level is higher than unofficial. "
  269. "Resample or reduce the compliance level.\n");
  270. return AVERROR(EINVAL);
  271. }
  272. av_assert0(avctx->sample_rate > 0);
  273. if(avctx->channels != 1){
  274. av_log(avctx, AV_LOG_ERROR, "Only mono is supported\n");
  275. return AVERROR(EINVAL);
  276. }
  277. if (avctx->bit_rate)
  278. c->code_size = (avctx->bit_rate + avctx->sample_rate/2) / avctx->sample_rate;
  279. c->code_size = av_clip(c->code_size, 2, 5);
  280. avctx->bit_rate = c->code_size * avctx->sample_rate;
  281. avctx->bits_per_coded_sample = c->code_size;
  282. g726_reset(c);
  283. #if FF_API_OLD_ENCODE_AUDIO
  284. avctx->coded_frame = avcodec_alloc_frame();
  285. if (!avctx->coded_frame)
  286. return AVERROR(ENOMEM);
  287. avctx->coded_frame->key_frame = 1;
  288. #endif
  289. /* select a frame size that will end on a byte boundary and have a size of
  290. approximately 1024 bytes */
  291. avctx->frame_size = ((int[]){ 4096, 2736, 2048, 1640 })[c->code_size - 2];
  292. return 0;
  293. }
  294. #if FF_API_OLD_ENCODE_AUDIO
  295. static av_cold int g726_encode_close(AVCodecContext *avctx)
  296. {
  297. av_freep(&avctx->coded_frame);
  298. return 0;
  299. }
  300. #endif
  301. static int g726_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  302. const AVFrame *frame, int *got_packet_ptr)
  303. {
  304. G726Context *c = avctx->priv_data;
  305. const int16_t *samples = (const int16_t *)frame->data[0];
  306. PutBitContext pb;
  307. int i, ret, out_size;
  308. out_size = (frame->nb_samples * c->code_size + 7) / 8;
  309. if ((ret = ff_alloc_packet(avpkt, out_size))) {
  310. av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
  311. return ret;
  312. }
  313. init_put_bits(&pb, avpkt->data, avpkt->size);
  314. for (i = 0; i < frame->nb_samples; i++)
  315. put_bits(&pb, c->code_size, g726_encode(c, *samples++));
  316. flush_put_bits(&pb);
  317. avpkt->size = out_size;
  318. *got_packet_ptr = 1;
  319. return 0;
  320. }
  321. #define OFFSET(x) offsetof(G726Context, x)
  322. #define AE AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  323. static const AVOption options[] = {
  324. { "code_size", "Bits per code", OFFSET(code_size), AV_OPT_TYPE_INT, { .i64 = 4 }, 2, 5, AE },
  325. { NULL },
  326. };
  327. static const AVClass class = {
  328. .class_name = "g726",
  329. .item_name = av_default_item_name,
  330. .option = options,
  331. .version = LIBAVUTIL_VERSION_INT,
  332. };
  333. static const AVCodecDefault defaults[] = {
  334. { "b", "0" },
  335. { NULL },
  336. };
  337. AVCodec ff_adpcm_g726_encoder = {
  338. .name = "g726",
  339. .type = AVMEDIA_TYPE_AUDIO,
  340. .id = AV_CODEC_ID_ADPCM_G726,
  341. .priv_data_size = sizeof(G726Context),
  342. .init = g726_encode_init,
  343. .encode2 = g726_encode_frame,
  344. #if FF_API_OLD_ENCODE_AUDIO
  345. .close = g726_encode_close,
  346. #endif
  347. .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
  348. .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
  349. AV_SAMPLE_FMT_NONE },
  350. .long_name = NULL_IF_CONFIG_SMALL("G.726 ADPCM"),
  351. .priv_class = &class,
  352. .defaults = defaults,
  353. };
  354. #endif
  355. #if CONFIG_ADPCM_G726_DECODER
  356. static av_cold int g726_decode_init(AVCodecContext *avctx)
  357. {
  358. G726Context* c = avctx->priv_data;
  359. avctx->channels = 1;
  360. avctx->channel_layout = AV_CH_LAYOUT_MONO;
  361. c->code_size = avctx->bits_per_coded_sample;
  362. if (c->code_size < 2 || c->code_size > 5) {
  363. av_log(avctx, AV_LOG_ERROR, "Invalid number of bits %d\n", c->code_size);
  364. return AVERROR(EINVAL);
  365. }
  366. g726_reset(c);
  367. avctx->sample_fmt = AV_SAMPLE_FMT_S16;
  368. avcodec_get_frame_defaults(&c->frame);
  369. avctx->coded_frame = &c->frame;
  370. return 0;
  371. }
  372. static int g726_decode_frame(AVCodecContext *avctx, void *data,
  373. int *got_frame_ptr, AVPacket *avpkt)
  374. {
  375. const uint8_t *buf = avpkt->data;
  376. int buf_size = avpkt->size;
  377. G726Context *c = avctx->priv_data;
  378. int16_t *samples;
  379. GetBitContext gb;
  380. int out_samples, ret;
  381. out_samples = buf_size * 8 / c->code_size;
  382. /* get output buffer */
  383. c->frame.nb_samples = out_samples;
  384. if ((ret = avctx->get_buffer(avctx, &c->frame)) < 0) {
  385. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  386. return ret;
  387. }
  388. samples = (int16_t *)c->frame.data[0];
  389. init_get_bits(&gb, buf, buf_size * 8);
  390. while (out_samples--)
  391. *samples++ = g726_decode(c, get_bits(&gb, c->code_size));
  392. if (get_bits_left(&gb) > 0)
  393. av_log(avctx, AV_LOG_ERROR, "Frame invalidly split, missing parser?\n");
  394. *got_frame_ptr = 1;
  395. *(AVFrame *)data = c->frame;
  396. return buf_size;
  397. }
  398. static void g726_decode_flush(AVCodecContext *avctx)
  399. {
  400. G726Context *c = avctx->priv_data;
  401. g726_reset(c);
  402. }
  403. AVCodec ff_adpcm_g726_decoder = {
  404. .name = "g726",
  405. .type = AVMEDIA_TYPE_AUDIO,
  406. .id = AV_CODEC_ID_ADPCM_G726,
  407. .priv_data_size = sizeof(G726Context),
  408. .init = g726_decode_init,
  409. .decode = g726_decode_frame,
  410. .flush = g726_decode_flush,
  411. .capabilities = CODEC_CAP_DR1,
  412. .long_name = NULL_IF_CONFIG_SMALL("G.726 ADPCM"),
  413. };
  414. #endif