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.

397 lines
14KB

  1. /*
  2. * Copyright (c) CMU 1993 Computer Science, Speech Group
  3. * Chengxiang Lu and Alex Hauptmann
  4. * Copyright (c) 2005 Steve Underwood <steveu at coppice.org>
  5. * Copyright (c) 2009 Kenan Gillet
  6. * Copyright (c) 2010 Martin Storsjo
  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. /**
  25. * @file
  26. * G.722 ADPCM audio encoder
  27. */
  28. #include "avcodec.h"
  29. #include "internal.h"
  30. #include "g722.h"
  31. #include "libavutil/common.h"
  32. #define FREEZE_INTERVAL 128
  33. /* This is an arbitrary value. Allowing insanely large values leads to strange
  34. problems, so we limit it to a reasonable value */
  35. #define MAX_FRAME_SIZE 32768
  36. /* We clip the value of avctx->trellis to prevent data type overflows and
  37. undefined behavior. Using larger values is insanely slow anyway. */
  38. #define MIN_TRELLIS 0
  39. #define MAX_TRELLIS 16
  40. static av_cold int g722_encode_close(AVCodecContext *avctx)
  41. {
  42. G722Context *c = avctx->priv_data;
  43. int i;
  44. for (i = 0; i < 2; i++) {
  45. av_freep(&c->paths[i]);
  46. av_freep(&c->node_buf[i]);
  47. av_freep(&c->nodep_buf[i]);
  48. }
  49. return 0;
  50. }
  51. static av_cold int g722_encode_init(AVCodecContext * avctx)
  52. {
  53. G722Context *c = avctx->priv_data;
  54. int ret;
  55. if (avctx->channels != 1) {
  56. av_log(avctx, AV_LOG_ERROR, "Only mono tracks are allowed.\n");
  57. return AVERROR_INVALIDDATA;
  58. }
  59. c->band[0].scale_factor = 8;
  60. c->band[1].scale_factor = 2;
  61. c->prev_samples_pos = 22;
  62. if (avctx->trellis) {
  63. int frontier = 1 << avctx->trellis;
  64. int max_paths = frontier * FREEZE_INTERVAL;
  65. int i;
  66. for (i = 0; i < 2; i++) {
  67. c->paths[i] = av_mallocz(max_paths * sizeof(**c->paths));
  68. c->node_buf[i] = av_mallocz(2 * frontier * sizeof(**c->node_buf));
  69. c->nodep_buf[i] = av_mallocz(2 * frontier * sizeof(**c->nodep_buf));
  70. if (!c->paths[i] || !c->node_buf[i] || !c->nodep_buf[i]) {
  71. ret = AVERROR(ENOMEM);
  72. goto error;
  73. }
  74. }
  75. }
  76. if (avctx->frame_size) {
  77. /* validate frame size */
  78. if (avctx->frame_size & 1 || avctx->frame_size > MAX_FRAME_SIZE) {
  79. int new_frame_size;
  80. if (avctx->frame_size == 1)
  81. new_frame_size = 2;
  82. else if (avctx->frame_size > MAX_FRAME_SIZE)
  83. new_frame_size = MAX_FRAME_SIZE;
  84. else
  85. new_frame_size = avctx->frame_size - 1;
  86. av_log(avctx, AV_LOG_WARNING, "Requested frame size is not "
  87. "allowed. Using %d instead of %d\n", new_frame_size,
  88. avctx->frame_size);
  89. avctx->frame_size = new_frame_size;
  90. }
  91. } else {
  92. /* This is arbitrary. We use 320 because it's 20ms @ 16kHz, which is
  93. a common packet size for VoIP applications */
  94. avctx->frame_size = 320;
  95. }
  96. avctx->initial_padding = 22;
  97. if (avctx->trellis) {
  98. /* validate trellis */
  99. if (avctx->trellis < MIN_TRELLIS || avctx->trellis > MAX_TRELLIS) {
  100. int new_trellis = av_clip(avctx->trellis, MIN_TRELLIS, MAX_TRELLIS);
  101. av_log(avctx, AV_LOG_WARNING, "Requested trellis value is not "
  102. "allowed. Using %d instead of %d\n", new_trellis,
  103. avctx->trellis);
  104. avctx->trellis = new_trellis;
  105. }
  106. }
  107. ff_g722dsp_init(&c->dsp);
  108. return 0;
  109. error:
  110. g722_encode_close(avctx);
  111. return ret;
  112. }
  113. static const int16_t low_quant[33] = {
  114. 35, 72, 110, 150, 190, 233, 276, 323,
  115. 370, 422, 473, 530, 587, 650, 714, 786,
  116. 858, 940, 1023, 1121, 1219, 1339, 1458, 1612,
  117. 1765, 1980, 2195, 2557, 2919
  118. };
  119. static inline void filter_samples(G722Context *c, const int16_t *samples,
  120. int *xlow, int *xhigh)
  121. {
  122. int xout[2];
  123. c->prev_samples[c->prev_samples_pos++] = samples[0];
  124. c->prev_samples[c->prev_samples_pos++] = samples[1];
  125. c->dsp.apply_qmf(c->prev_samples + c->prev_samples_pos - 24, xout);
  126. *xlow = xout[0] + xout[1] >> 14;
  127. *xhigh = xout[0] - xout[1] >> 14;
  128. if (c->prev_samples_pos >= PREV_SAMPLES_BUF_SIZE) {
  129. memmove(c->prev_samples,
  130. c->prev_samples + c->prev_samples_pos - 22,
  131. 22 * sizeof(c->prev_samples[0]));
  132. c->prev_samples_pos = 22;
  133. }
  134. }
  135. static inline int encode_high(const struct G722Band *state, int xhigh)
  136. {
  137. int diff = av_clip_int16(xhigh - state->s_predictor);
  138. int pred = 141 * state->scale_factor >> 8;
  139. /* = diff >= 0 ? (diff < pred) + 2 : diff >= -pred */
  140. return ((diff ^ (diff >> (sizeof(diff)*8-1))) < pred) + 2*(diff >= 0);
  141. }
  142. static inline int encode_low(const struct G722Band* state, int xlow)
  143. {
  144. int diff = av_clip_int16(xlow - state->s_predictor);
  145. /* = diff >= 0 ? diff : -(diff + 1) */
  146. int limit = diff ^ (diff >> (sizeof(diff)*8-1));
  147. int i = 0;
  148. limit = limit + 1 << 10;
  149. if (limit > low_quant[8] * state->scale_factor)
  150. i = 9;
  151. while (i < 29 && limit > low_quant[i] * state->scale_factor)
  152. i++;
  153. return (diff < 0 ? (i < 2 ? 63 : 33) : 61) - i;
  154. }
  155. static void g722_encode_trellis(G722Context *c, int trellis,
  156. uint8_t *dst, int nb_samples,
  157. const int16_t *samples)
  158. {
  159. int i, j, k;
  160. int frontier = 1 << trellis;
  161. struct TrellisNode **nodes[2];
  162. struct TrellisNode **nodes_next[2];
  163. int pathn[2] = {0, 0}, froze = -1;
  164. struct TrellisPath *p[2];
  165. for (i = 0; i < 2; i++) {
  166. nodes[i] = c->nodep_buf[i];
  167. nodes_next[i] = c->nodep_buf[i] + frontier;
  168. memset(c->nodep_buf[i], 0, 2 * frontier * sizeof(*c->nodep_buf[i]));
  169. nodes[i][0] = c->node_buf[i] + frontier;
  170. nodes[i][0]->ssd = 0;
  171. nodes[i][0]->path = 0;
  172. nodes[i][0]->state = c->band[i];
  173. }
  174. for (i = 0; i < nb_samples >> 1; i++) {
  175. int xlow, xhigh;
  176. struct TrellisNode *next[2];
  177. int heap_pos[2] = {0, 0};
  178. for (j = 0; j < 2; j++) {
  179. next[j] = c->node_buf[j] + frontier*(i & 1);
  180. memset(nodes_next[j], 0, frontier * sizeof(**nodes_next));
  181. }
  182. filter_samples(c, &samples[2*i], &xlow, &xhigh);
  183. for (j = 0; j < frontier && nodes[0][j]; j++) {
  184. /* Only k >> 2 affects the future adaptive state, therefore testing
  185. * small steps that don't change k >> 2 is useless, the original
  186. * value from encode_low is better than them. Since we step k
  187. * in steps of 4, make sure range is a multiple of 4, so that
  188. * we don't miss the original value from encode_low. */
  189. int range = j < frontier/2 ? 4 : 0;
  190. struct TrellisNode *cur_node = nodes[0][j];
  191. int ilow = encode_low(&cur_node->state, xlow);
  192. for (k = ilow - range; k <= ilow + range && k <= 63; k += 4) {
  193. int decoded, dec_diff, pos;
  194. uint32_t ssd;
  195. struct TrellisNode* node;
  196. if (k < 0)
  197. continue;
  198. decoded = av_clip_intp2((cur_node->state.scale_factor *
  199. ff_g722_low_inv_quant6[k] >> 10)
  200. + cur_node->state.s_predictor, 14);
  201. dec_diff = xlow - decoded;
  202. #define STORE_NODE(index, UPDATE, VALUE)\
  203. ssd = cur_node->ssd + dec_diff*dec_diff;\
  204. /* Check for wraparound. Using 64 bit ssd counters would \
  205. * be simpler, but is slower on x86 32 bit. */\
  206. if (ssd < cur_node->ssd)\
  207. continue;\
  208. if (heap_pos[index] < frontier) {\
  209. pos = heap_pos[index]++;\
  210. assert(pathn[index] < FREEZE_INTERVAL * frontier);\
  211. node = nodes_next[index][pos] = next[index]++;\
  212. node->path = pathn[index]++;\
  213. } else {\
  214. /* Try to replace one of the leaf nodes with the new \
  215. * one, but not always testing the same leaf position */\
  216. pos = (frontier>>1) + (heap_pos[index] & ((frontier>>1) - 1));\
  217. if (ssd >= nodes_next[index][pos]->ssd)\
  218. continue;\
  219. heap_pos[index]++;\
  220. node = nodes_next[index][pos];\
  221. }\
  222. node->ssd = ssd;\
  223. node->state = cur_node->state;\
  224. UPDATE;\
  225. c->paths[index][node->path].value = VALUE;\
  226. c->paths[index][node->path].prev = cur_node->path;\
  227. /* Sift the newly inserted node up in the heap to restore \
  228. * the heap property */\
  229. while (pos > 0) {\
  230. int parent = (pos - 1) >> 1;\
  231. if (nodes_next[index][parent]->ssd <= ssd)\
  232. break;\
  233. FFSWAP(struct TrellisNode*, nodes_next[index][parent],\
  234. nodes_next[index][pos]);\
  235. pos = parent;\
  236. }
  237. STORE_NODE(0, ff_g722_update_low_predictor(&node->state, k >> 2), k);
  238. }
  239. }
  240. for (j = 0; j < frontier && nodes[1][j]; j++) {
  241. int ihigh;
  242. struct TrellisNode *cur_node = nodes[1][j];
  243. /* We don't try to get any initial guess for ihigh via
  244. * encode_high - since there's only 4 possible values, test
  245. * them all. Testing all of these gives a much, much larger
  246. * gain than testing a larger range around ilow. */
  247. for (ihigh = 0; ihigh < 4; ihigh++) {
  248. int dhigh, decoded, dec_diff, pos;
  249. uint32_t ssd;
  250. struct TrellisNode* node;
  251. dhigh = cur_node->state.scale_factor *
  252. ff_g722_high_inv_quant[ihigh] >> 10;
  253. decoded = av_clip_intp2(dhigh + cur_node->state.s_predictor, 14);
  254. dec_diff = xhigh - decoded;
  255. STORE_NODE(1, ff_g722_update_high_predictor(&node->state, dhigh, ihigh), ihigh);
  256. }
  257. }
  258. for (j = 0; j < 2; j++) {
  259. FFSWAP(struct TrellisNode**, nodes[j], nodes_next[j]);
  260. if (nodes[j][0]->ssd > (1 << 16)) {
  261. for (k = 1; k < frontier && nodes[j][k]; k++)
  262. nodes[j][k]->ssd -= nodes[j][0]->ssd;
  263. nodes[j][0]->ssd = 0;
  264. }
  265. }
  266. if (i == froze + FREEZE_INTERVAL) {
  267. p[0] = &c->paths[0][nodes[0][0]->path];
  268. p[1] = &c->paths[1][nodes[1][0]->path];
  269. for (j = i; j > froze; j--) {
  270. dst[j] = p[1]->value << 6 | p[0]->value;
  271. p[0] = &c->paths[0][p[0]->prev];
  272. p[1] = &c->paths[1][p[1]->prev];
  273. }
  274. froze = i;
  275. pathn[0] = pathn[1] = 0;
  276. memset(nodes[0] + 1, 0, (frontier - 1)*sizeof(**nodes));
  277. memset(nodes[1] + 1, 0, (frontier - 1)*sizeof(**nodes));
  278. }
  279. }
  280. p[0] = &c->paths[0][nodes[0][0]->path];
  281. p[1] = &c->paths[1][nodes[1][0]->path];
  282. for (j = i; j > froze; j--) {
  283. dst[j] = p[1]->value << 6 | p[0]->value;
  284. p[0] = &c->paths[0][p[0]->prev];
  285. p[1] = &c->paths[1][p[1]->prev];
  286. }
  287. c->band[0] = nodes[0][0]->state;
  288. c->band[1] = nodes[1][0]->state;
  289. }
  290. static av_always_inline void encode_byte(G722Context *c, uint8_t *dst,
  291. const int16_t *samples)
  292. {
  293. int xlow, xhigh, ilow, ihigh;
  294. filter_samples(c, samples, &xlow, &xhigh);
  295. ihigh = encode_high(&c->band[1], xhigh);
  296. ilow = encode_low (&c->band[0], xlow);
  297. ff_g722_update_high_predictor(&c->band[1], c->band[1].scale_factor *
  298. ff_g722_high_inv_quant[ihigh] >> 10, ihigh);
  299. ff_g722_update_low_predictor(&c->band[0], ilow >> 2);
  300. *dst = ihigh << 6 | ilow;
  301. }
  302. static void g722_encode_no_trellis(G722Context *c,
  303. uint8_t *dst, int nb_samples,
  304. const int16_t *samples)
  305. {
  306. int i;
  307. for (i = 0; i < nb_samples; i += 2)
  308. encode_byte(c, dst++, &samples[i]);
  309. }
  310. static int g722_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  311. const AVFrame *frame, int *got_packet_ptr)
  312. {
  313. G722Context *c = avctx->priv_data;
  314. const int16_t *samples = (const int16_t *)frame->data[0];
  315. int nb_samples, out_size, ret;
  316. out_size = (frame->nb_samples + 1) / 2;
  317. if ((ret = ff_alloc_packet(avpkt, out_size))) {
  318. av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
  319. return ret;
  320. }
  321. nb_samples = frame->nb_samples - (frame->nb_samples & 1);
  322. if (avctx->trellis)
  323. g722_encode_trellis(c, avctx->trellis, avpkt->data, nb_samples, samples);
  324. else
  325. g722_encode_no_trellis(c, avpkt->data, nb_samples, samples);
  326. /* handle last frame with odd frame_size */
  327. if (nb_samples < frame->nb_samples) {
  328. int16_t last_samples[2] = { samples[nb_samples], samples[nb_samples] };
  329. encode_byte(c, &avpkt->data[nb_samples >> 1], last_samples);
  330. }
  331. if (frame->pts != AV_NOPTS_VALUE)
  332. avpkt->pts = frame->pts - ff_samples_to_time_base(avctx, avctx->initial_padding);
  333. *got_packet_ptr = 1;
  334. return 0;
  335. }
  336. AVCodec ff_adpcm_g722_encoder = {
  337. .name = "g722",
  338. .long_name = NULL_IF_CONFIG_SMALL("G.722 ADPCM"),
  339. .type = AVMEDIA_TYPE_AUDIO,
  340. .id = AV_CODEC_ID_ADPCM_G722,
  341. .priv_data_size = sizeof(G722Context),
  342. .init = g722_encode_init,
  343. .close = g722_encode_close,
  344. .encode2 = g722_encode_frame,
  345. .capabilities = AV_CODEC_CAP_SMALL_LAST_FRAME,
  346. .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
  347. AV_SAMPLE_FMT_NONE },
  348. };