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.

407 lines
15KB

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