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.

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