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.

583 lines
18KB

  1. /*
  2. * ALAC audio encoder
  3. * Copyright (c) 2008 Jaikrishnan Menon <realityman@gmx.net>
  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. #include "avcodec.h"
  22. #include "put_bits.h"
  23. #include "dsputil.h"
  24. #include "internal.h"
  25. #include "lpc.h"
  26. #include "mathops.h"
  27. #define DEFAULT_FRAME_SIZE 4096
  28. #define DEFAULT_SAMPLE_SIZE 16
  29. #define MAX_CHANNELS 8
  30. #define ALAC_EXTRADATA_SIZE 36
  31. #define ALAC_FRAME_HEADER_SIZE 55
  32. #define ALAC_FRAME_FOOTER_SIZE 3
  33. #define ALAC_ESCAPE_CODE 0x1FF
  34. #define ALAC_MAX_LPC_ORDER 30
  35. #define DEFAULT_MAX_PRED_ORDER 6
  36. #define DEFAULT_MIN_PRED_ORDER 4
  37. #define ALAC_MAX_LPC_PRECISION 9
  38. #define ALAC_MAX_LPC_SHIFT 9
  39. #define ALAC_CHMODE_LEFT_RIGHT 0
  40. #define ALAC_CHMODE_LEFT_SIDE 1
  41. #define ALAC_CHMODE_RIGHT_SIDE 2
  42. #define ALAC_CHMODE_MID_SIDE 3
  43. typedef struct RiceContext {
  44. int history_mult;
  45. int initial_history;
  46. int k_modifier;
  47. int rice_modifier;
  48. } RiceContext;
  49. typedef struct AlacLPCContext {
  50. int lpc_order;
  51. int lpc_coeff[ALAC_MAX_LPC_ORDER+1];
  52. int lpc_quant;
  53. } AlacLPCContext;
  54. typedef struct AlacEncodeContext {
  55. int frame_size; /**< current frame size */
  56. int verbatim; /**< current frame verbatim mode flag */
  57. int compression_level;
  58. int min_prediction_order;
  59. int max_prediction_order;
  60. int max_coded_frame_size;
  61. int write_sample_size;
  62. int32_t sample_buf[MAX_CHANNELS][DEFAULT_FRAME_SIZE];
  63. int32_t predictor_buf[DEFAULT_FRAME_SIZE];
  64. int interlacing_shift;
  65. int interlacing_leftweight;
  66. PutBitContext pbctx;
  67. RiceContext rc;
  68. AlacLPCContext lpc[MAX_CHANNELS];
  69. LPCContext lpc_ctx;
  70. AVCodecContext *avctx;
  71. } AlacEncodeContext;
  72. static void init_sample_buffers(AlacEncodeContext *s, int16_t **input_samples)
  73. {
  74. int ch, i;
  75. for (ch = 0; ch < s->avctx->channels; ch++) {
  76. int32_t *bptr = s->sample_buf[ch];
  77. const int16_t *sptr = input_samples[ch];
  78. for (i = 0; i < s->frame_size; i++)
  79. bptr[i] = sptr[i];
  80. }
  81. }
  82. static void encode_scalar(AlacEncodeContext *s, int x,
  83. int k, int write_sample_size)
  84. {
  85. int divisor, q, r;
  86. k = FFMIN(k, s->rc.k_modifier);
  87. divisor = (1<<k) - 1;
  88. q = x / divisor;
  89. r = x % divisor;
  90. if (q > 8) {
  91. // write escape code and sample value directly
  92. put_bits(&s->pbctx, 9, ALAC_ESCAPE_CODE);
  93. put_bits(&s->pbctx, write_sample_size, x);
  94. } else {
  95. if (q)
  96. put_bits(&s->pbctx, q, (1<<q) - 1);
  97. put_bits(&s->pbctx, 1, 0);
  98. if (k != 1) {
  99. if (r > 0)
  100. put_bits(&s->pbctx, k, r+1);
  101. else
  102. put_bits(&s->pbctx, k-1, 0);
  103. }
  104. }
  105. }
  106. static void write_frame_header(AlacEncodeContext *s)
  107. {
  108. int encode_fs = 0;
  109. if (s->frame_size < DEFAULT_FRAME_SIZE)
  110. encode_fs = 1;
  111. put_bits(&s->pbctx, 3, s->avctx->channels-1); // No. of channels -1
  112. put_bits(&s->pbctx, 16, 0); // Seems to be zero
  113. put_bits(&s->pbctx, 1, encode_fs); // Sample count is in the header
  114. put_bits(&s->pbctx, 2, 0); // FIXME: Wasted bytes field
  115. put_bits(&s->pbctx, 1, s->verbatim); // Audio block is verbatim
  116. if (encode_fs)
  117. put_bits32(&s->pbctx, s->frame_size); // No. of samples in the frame
  118. }
  119. static void calc_predictor_params(AlacEncodeContext *s, int ch)
  120. {
  121. int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
  122. int shift[MAX_LPC_ORDER];
  123. int opt_order;
  124. if (s->compression_level == 1) {
  125. s->lpc[ch].lpc_order = 6;
  126. s->lpc[ch].lpc_quant = 6;
  127. s->lpc[ch].lpc_coeff[0] = 160;
  128. s->lpc[ch].lpc_coeff[1] = -190;
  129. s->lpc[ch].lpc_coeff[2] = 170;
  130. s->lpc[ch].lpc_coeff[3] = -130;
  131. s->lpc[ch].lpc_coeff[4] = 80;
  132. s->lpc[ch].lpc_coeff[5] = -25;
  133. } else {
  134. opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, s->sample_buf[ch],
  135. s->frame_size,
  136. s->min_prediction_order,
  137. s->max_prediction_order,
  138. ALAC_MAX_LPC_PRECISION, coefs, shift,
  139. FF_LPC_TYPE_LEVINSON, 0,
  140. ORDER_METHOD_EST, ALAC_MAX_LPC_SHIFT, 1);
  141. s->lpc[ch].lpc_order = opt_order;
  142. s->lpc[ch].lpc_quant = shift[opt_order-1];
  143. memcpy(s->lpc[ch].lpc_coeff, coefs[opt_order-1], opt_order*sizeof(int));
  144. }
  145. }
  146. static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
  147. {
  148. int i, best;
  149. int32_t lt, rt;
  150. uint64_t sum[4];
  151. uint64_t score[4];
  152. /* calculate sum of 2nd order residual for each channel */
  153. sum[0] = sum[1] = sum[2] = sum[3] = 0;
  154. for (i = 2; i < n; i++) {
  155. lt = left_ch[i] - 2 * left_ch[i - 1] + left_ch[i - 2];
  156. rt = right_ch[i] - 2 * right_ch[i - 1] + right_ch[i - 2];
  157. sum[2] += FFABS((lt + rt) >> 1);
  158. sum[3] += FFABS(lt - rt);
  159. sum[0] += FFABS(lt);
  160. sum[1] += FFABS(rt);
  161. }
  162. /* calculate score for each mode */
  163. score[0] = sum[0] + sum[1];
  164. score[1] = sum[0] + sum[3];
  165. score[2] = sum[1] + sum[3];
  166. score[3] = sum[2] + sum[3];
  167. /* return mode with lowest score */
  168. best = 0;
  169. for (i = 1; i < 4; i++) {
  170. if (score[i] < score[best])
  171. best = i;
  172. }
  173. return best;
  174. }
  175. static void alac_stereo_decorrelation(AlacEncodeContext *s)
  176. {
  177. int32_t *left = s->sample_buf[0], *right = s->sample_buf[1];
  178. int i, mode, n = s->frame_size;
  179. int32_t tmp;
  180. mode = estimate_stereo_mode(left, right, n);
  181. switch (mode) {
  182. case ALAC_CHMODE_LEFT_RIGHT:
  183. s->interlacing_leftweight = 0;
  184. s->interlacing_shift = 0;
  185. break;
  186. case ALAC_CHMODE_LEFT_SIDE:
  187. for (i = 0; i < n; i++)
  188. right[i] = left[i] - right[i];
  189. s->interlacing_leftweight = 1;
  190. s->interlacing_shift = 0;
  191. break;
  192. case ALAC_CHMODE_RIGHT_SIDE:
  193. for (i = 0; i < n; i++) {
  194. tmp = right[i];
  195. right[i] = left[i] - right[i];
  196. left[i] = tmp + (right[i] >> 31);
  197. }
  198. s->interlacing_leftweight = 1;
  199. s->interlacing_shift = 31;
  200. break;
  201. default:
  202. for (i = 0; i < n; i++) {
  203. tmp = left[i];
  204. left[i] = (tmp + right[i]) >> 1;
  205. right[i] = tmp - right[i];
  206. }
  207. s->interlacing_leftweight = 1;
  208. s->interlacing_shift = 1;
  209. break;
  210. }
  211. }
  212. static void alac_linear_predictor(AlacEncodeContext *s, int ch)
  213. {
  214. int i;
  215. AlacLPCContext lpc = s->lpc[ch];
  216. if (lpc.lpc_order == 31) {
  217. s->predictor_buf[0] = s->sample_buf[ch][0];
  218. for (i = 1; i < s->frame_size; i++) {
  219. s->predictor_buf[i] = s->sample_buf[ch][i ] -
  220. s->sample_buf[ch][i - 1];
  221. }
  222. return;
  223. }
  224. // generalised linear predictor
  225. if (lpc.lpc_order > 0) {
  226. int32_t *samples = s->sample_buf[ch];
  227. int32_t *residual = s->predictor_buf;
  228. // generate warm-up samples
  229. residual[0] = samples[0];
  230. for (i = 1; i <= lpc.lpc_order; i++)
  231. residual[i] = samples[i] - samples[i-1];
  232. // perform lpc on remaining samples
  233. for (i = lpc.lpc_order + 1; i < s->frame_size; i++) {
  234. int sum = 1 << (lpc.lpc_quant - 1), res_val, j;
  235. for (j = 0; j < lpc.lpc_order; j++) {
  236. sum += (samples[lpc.lpc_order-j] - samples[0]) *
  237. lpc.lpc_coeff[j];
  238. }
  239. sum >>= lpc.lpc_quant;
  240. sum += samples[0];
  241. residual[i] = sign_extend(samples[lpc.lpc_order+1] - sum,
  242. s->write_sample_size);
  243. res_val = residual[i];
  244. if (res_val) {
  245. int index = lpc.lpc_order - 1;
  246. int neg = (res_val < 0);
  247. while (index >= 0 && (neg ? (res_val < 0) : (res_val > 0))) {
  248. int val = samples[0] - samples[lpc.lpc_order - index];
  249. int sign = (val ? FFSIGN(val) : 0);
  250. if (neg)
  251. sign *= -1;
  252. lpc.lpc_coeff[index] -= sign;
  253. val *= sign;
  254. res_val -= (val >> lpc.lpc_quant) * (lpc.lpc_order - index);
  255. index--;
  256. }
  257. }
  258. samples++;
  259. }
  260. }
  261. }
  262. static void alac_entropy_coder(AlacEncodeContext *s)
  263. {
  264. unsigned int history = s->rc.initial_history;
  265. int sign_modifier = 0, i, k;
  266. int32_t *samples = s->predictor_buf;
  267. for (i = 0; i < s->frame_size;) {
  268. int x;
  269. k = av_log2((history >> 9) + 3);
  270. x = -2 * (*samples) -1;
  271. x ^= x >> 31;
  272. samples++;
  273. i++;
  274. encode_scalar(s, x - sign_modifier, k, s->write_sample_size);
  275. history += x * s->rc.history_mult -
  276. ((history * s->rc.history_mult) >> 9);
  277. sign_modifier = 0;
  278. if (x > 0xFFFF)
  279. history = 0xFFFF;
  280. if (history < 128 && i < s->frame_size) {
  281. unsigned int block_size = 0;
  282. k = 7 - av_log2(history) + ((history + 16) >> 6);
  283. while (*samples == 0 && i < s->frame_size) {
  284. samples++;
  285. i++;
  286. block_size++;
  287. }
  288. encode_scalar(s, block_size, k, 16);
  289. sign_modifier = (block_size <= 0xFFFF);
  290. history = 0;
  291. }
  292. }
  293. }
  294. static int write_frame(AlacEncodeContext *s, AVPacket *avpkt, int16_t **samples)
  295. {
  296. int i, j;
  297. int prediction_type = 0;
  298. PutBitContext *pb = &s->pbctx;
  299. init_put_bits(pb, avpkt->data, avpkt->size);
  300. if (s->verbatim) {
  301. write_frame_header(s);
  302. /* samples are channel-interleaved in verbatim mode */
  303. for (i = 0; i < s->frame_size; i++)
  304. for (j = 0; j < s->avctx->channels; j++)
  305. put_sbits(pb, 16, samples[j][i]);
  306. } else {
  307. init_sample_buffers(s, samples);
  308. write_frame_header(s);
  309. if (s->avctx->channels == 2)
  310. alac_stereo_decorrelation(s);
  311. put_bits(pb, 8, s->interlacing_shift);
  312. put_bits(pb, 8, s->interlacing_leftweight);
  313. for (i = 0; i < s->avctx->channels; i++) {
  314. calc_predictor_params(s, i);
  315. put_bits(pb, 4, prediction_type);
  316. put_bits(pb, 4, s->lpc[i].lpc_quant);
  317. put_bits(pb, 3, s->rc.rice_modifier);
  318. put_bits(pb, 5, s->lpc[i].lpc_order);
  319. // predictor coeff. table
  320. for (j = 0; j < s->lpc[i].lpc_order; j++)
  321. put_sbits(pb, 16, s->lpc[i].lpc_coeff[j]);
  322. }
  323. // apply lpc and entropy coding to audio samples
  324. for (i = 0; i < s->avctx->channels; i++) {
  325. alac_linear_predictor(s, i);
  326. // TODO: determine when this will actually help. for now it's not used.
  327. if (prediction_type == 15) {
  328. // 2nd pass 1st order filter
  329. for (j = s->frame_size - 1; j > 0; j--)
  330. s->predictor_buf[j] -= s->predictor_buf[j - 1];
  331. }
  332. alac_entropy_coder(s);
  333. }
  334. }
  335. put_bits(pb, 3, 7);
  336. flush_put_bits(pb);
  337. return put_bits_count(pb) >> 3;
  338. }
  339. static av_always_inline int get_max_frame_size(int frame_size, int ch, int bps)
  340. {
  341. int header_bits = 23 + 32 * (frame_size < DEFAULT_FRAME_SIZE);
  342. return FFALIGN(header_bits + bps * ch * frame_size + 3, 8) / 8;
  343. }
  344. static av_cold int alac_encode_close(AVCodecContext *avctx)
  345. {
  346. AlacEncodeContext *s = avctx->priv_data;
  347. ff_lpc_end(&s->lpc_ctx);
  348. av_freep(&avctx->extradata);
  349. avctx->extradata_size = 0;
  350. av_freep(&avctx->coded_frame);
  351. return 0;
  352. }
  353. static av_cold int alac_encode_init(AVCodecContext *avctx)
  354. {
  355. AlacEncodeContext *s = avctx->priv_data;
  356. int ret;
  357. uint8_t *alac_extradata;
  358. avctx->frame_size = s->frame_size = DEFAULT_FRAME_SIZE;
  359. /* TODO: Correctly implement multi-channel ALAC.
  360. It is similar to multi-channel AAC, in that it has a series of
  361. single-channel (SCE), channel-pair (CPE), and LFE elements. */
  362. if (avctx->channels > 2) {
  363. av_log(avctx, AV_LOG_ERROR, "only mono or stereo input is currently supported\n");
  364. return AVERROR_PATCHWELCOME;
  365. }
  366. // Set default compression level
  367. if (avctx->compression_level == FF_COMPRESSION_DEFAULT)
  368. s->compression_level = 2;
  369. else
  370. s->compression_level = av_clip(avctx->compression_level, 0, 2);
  371. // Initialize default Rice parameters
  372. s->rc.history_mult = 40;
  373. s->rc.initial_history = 10;
  374. s->rc.k_modifier = 14;
  375. s->rc.rice_modifier = 4;
  376. s->max_coded_frame_size = get_max_frame_size(avctx->frame_size,
  377. avctx->channels,
  378. DEFAULT_SAMPLE_SIZE);
  379. // FIXME: consider wasted_bytes
  380. s->write_sample_size = DEFAULT_SAMPLE_SIZE + avctx->channels - 1;
  381. avctx->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);
  382. if (!avctx->extradata) {
  383. ret = AVERROR(ENOMEM);
  384. goto error;
  385. }
  386. avctx->extradata_size = ALAC_EXTRADATA_SIZE;
  387. alac_extradata = avctx->extradata;
  388. AV_WB32(alac_extradata, ALAC_EXTRADATA_SIZE);
  389. AV_WB32(alac_extradata+4, MKBETAG('a','l','a','c'));
  390. AV_WB32(alac_extradata+12, avctx->frame_size);
  391. AV_WB8 (alac_extradata+17, DEFAULT_SAMPLE_SIZE);
  392. AV_WB8 (alac_extradata+21, avctx->channels);
  393. AV_WB32(alac_extradata+24, s->max_coded_frame_size);
  394. AV_WB32(alac_extradata+28,
  395. avctx->sample_rate * avctx->channels * DEFAULT_SAMPLE_SIZE); // average bitrate
  396. AV_WB32(alac_extradata+32, avctx->sample_rate);
  397. // Set relevant extradata fields
  398. if (s->compression_level > 0) {
  399. AV_WB8(alac_extradata+18, s->rc.history_mult);
  400. AV_WB8(alac_extradata+19, s->rc.initial_history);
  401. AV_WB8(alac_extradata+20, s->rc.k_modifier);
  402. }
  403. s->min_prediction_order = DEFAULT_MIN_PRED_ORDER;
  404. if (avctx->min_prediction_order >= 0) {
  405. if (avctx->min_prediction_order < MIN_LPC_ORDER ||
  406. avctx->min_prediction_order > ALAC_MAX_LPC_ORDER) {
  407. av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
  408. avctx->min_prediction_order);
  409. ret = AVERROR(EINVAL);
  410. goto error;
  411. }
  412. s->min_prediction_order = avctx->min_prediction_order;
  413. }
  414. s->max_prediction_order = DEFAULT_MAX_PRED_ORDER;
  415. if (avctx->max_prediction_order >= 0) {
  416. if (avctx->max_prediction_order < MIN_LPC_ORDER ||
  417. avctx->max_prediction_order > ALAC_MAX_LPC_ORDER) {
  418. av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
  419. avctx->max_prediction_order);
  420. ret = AVERROR(EINVAL);
  421. goto error;
  422. }
  423. s->max_prediction_order = avctx->max_prediction_order;
  424. }
  425. if (s->max_prediction_order < s->min_prediction_order) {
  426. av_log(avctx, AV_LOG_ERROR,
  427. "invalid prediction orders: min=%d max=%d\n",
  428. s->min_prediction_order, s->max_prediction_order);
  429. ret = AVERROR(EINVAL);
  430. goto error;
  431. }
  432. avctx->coded_frame = avcodec_alloc_frame();
  433. if (!avctx->coded_frame) {
  434. ret = AVERROR(ENOMEM);
  435. goto error;
  436. }
  437. s->avctx = avctx;
  438. if ((ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
  439. s->max_prediction_order,
  440. FF_LPC_TYPE_LEVINSON)) < 0) {
  441. goto error;
  442. }
  443. return 0;
  444. error:
  445. alac_encode_close(avctx);
  446. return ret;
  447. }
  448. static int alac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  449. const AVFrame *frame, int *got_packet_ptr)
  450. {
  451. AlacEncodeContext *s = avctx->priv_data;
  452. int out_bytes, max_frame_size, ret;
  453. int16_t **samples = (int16_t **)frame->extended_data;
  454. s->frame_size = frame->nb_samples;
  455. if (frame->nb_samples < DEFAULT_FRAME_SIZE)
  456. max_frame_size = get_max_frame_size(s->frame_size, avctx->channels,
  457. DEFAULT_SAMPLE_SIZE);
  458. else
  459. max_frame_size = s->max_coded_frame_size;
  460. if ((ret = ff_alloc_packet(avpkt, 2 * max_frame_size))) {
  461. av_log(avctx, AV_LOG_ERROR, "Error getting output packet\n");
  462. return ret;
  463. }
  464. /* use verbatim mode for compression_level 0 */
  465. s->verbatim = !s->compression_level;
  466. out_bytes = write_frame(s, avpkt, samples);
  467. if (out_bytes > max_frame_size) {
  468. /* frame too large. use verbatim mode */
  469. s->verbatim = 1;
  470. out_bytes = write_frame(s, avpkt, samples);
  471. }
  472. avpkt->size = out_bytes;
  473. *got_packet_ptr = 1;
  474. return 0;
  475. }
  476. AVCodec ff_alac_encoder = {
  477. .name = "alac",
  478. .type = AVMEDIA_TYPE_AUDIO,
  479. .id = AV_CODEC_ID_ALAC,
  480. .priv_data_size = sizeof(AlacEncodeContext),
  481. .init = alac_encode_init,
  482. .encode2 = alac_encode_frame,
  483. .close = alac_encode_close,
  484. .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
  485. .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16P,
  486. AV_SAMPLE_FMT_NONE },
  487. .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
  488. };