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.

616 lines
19KB

  1. /*
  2. * ALAC (Apple Lossless Audio Codec) decoder
  3. * Copyright (c) 2005 David Hammerton
  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. /**
  22. * @file
  23. * ALAC (Apple Lossless Audio Codec) decoder
  24. * @author 2005 David Hammerton
  25. * @see http://crazney.net/programs/itunes/alac.html
  26. *
  27. * Note: This decoder expects a 36-byte QuickTime atom to be
  28. * passed through the extradata[_size] fields. This atom is tacked onto
  29. * the end of an 'alac' stsd atom and has the following format:
  30. *
  31. * 32bit atom size
  32. * 32bit tag ("alac")
  33. * 32bit tag version (0)
  34. * 32bit samples per frame (used when not set explicitly in the frames)
  35. * 8bit compatible version (0)
  36. * 8bit sample size
  37. * 8bit history mult (40)
  38. * 8bit initial history (14)
  39. * 8bit rice param limit (10)
  40. * 8bit channels
  41. * 16bit maxRun (255)
  42. * 32bit max coded frame size (0 means unknown)
  43. * 32bit average bitrate (0 means unknown)
  44. * 32bit samplerate
  45. */
  46. #include "libavutil/audioconvert.h"
  47. #include "avcodec.h"
  48. #include "get_bits.h"
  49. #include "bytestream.h"
  50. #include "unary.h"
  51. #include "mathops.h"
  52. #define ALAC_EXTRADATA_SIZE 36
  53. #define MAX_CHANNELS 8
  54. typedef struct {
  55. AVCodecContext *avctx;
  56. AVFrame frame;
  57. GetBitContext gb;
  58. int channels;
  59. int32_t *predict_error_buffer[2];
  60. int32_t *output_samples_buffer[2];
  61. int32_t *extra_bits_buffer[2];
  62. uint32_t max_samples_per_frame;
  63. uint8_t sample_size;
  64. uint8_t rice_history_mult;
  65. uint8_t rice_initial_history;
  66. uint8_t rice_limit;
  67. int extra_bits; /**< number of extra bits beyond 16-bit */
  68. int nb_samples; /**< number of samples in the current frame */
  69. } ALACContext;
  70. enum RawDataBlockType {
  71. /* At the moment, only SCE, CPE, LFE, and END are recognized. */
  72. TYPE_SCE,
  73. TYPE_CPE,
  74. TYPE_CCE,
  75. TYPE_LFE,
  76. TYPE_DSE,
  77. TYPE_PCE,
  78. TYPE_FIL,
  79. TYPE_END
  80. };
  81. static const uint8_t alac_channel_layout_offsets[8][8] = {
  82. { 0 },
  83. { 0, 1 },
  84. { 2, 0, 1 },
  85. { 2, 0, 1, 3 },
  86. { 2, 0, 1, 3, 4 },
  87. { 2, 0, 1, 4, 5, 3 },
  88. { 2, 0, 1, 4, 5, 6, 3 },
  89. { 2, 6, 7, 0, 1, 4, 5, 3 }
  90. };
  91. static const uint16_t alac_channel_layouts[8] = {
  92. AV_CH_LAYOUT_MONO,
  93. AV_CH_LAYOUT_STEREO,
  94. AV_CH_LAYOUT_SURROUND,
  95. AV_CH_LAYOUT_4POINT0,
  96. AV_CH_LAYOUT_5POINT0_BACK,
  97. AV_CH_LAYOUT_5POINT1_BACK,
  98. AV_CH_LAYOUT_6POINT1_BACK,
  99. AV_CH_LAYOUT_7POINT1_WIDE_BACK
  100. };
  101. static inline unsigned int decode_scalar(GetBitContext *gb, int k, int bps)
  102. {
  103. unsigned int x = get_unary_0_9(gb);
  104. if (x > 8) { /* RICE THRESHOLD */
  105. /* use alternative encoding */
  106. x = get_bits_long(gb, bps);
  107. } else if (k != 1) {
  108. int extrabits = show_bits(gb, k);
  109. /* multiply x by 2^k - 1, as part of their strange algorithm */
  110. x = (x << k) - x;
  111. if (extrabits > 1) {
  112. x += extrabits - 1;
  113. skip_bits(gb, k);
  114. } else
  115. skip_bits(gb, k - 1);
  116. }
  117. return x;
  118. }
  119. static void rice_decompress(ALACContext *alac, int32_t *output_buffer,
  120. int nb_samples, int bps, int rice_history_mult)
  121. {
  122. int i;
  123. unsigned int history = alac->rice_initial_history;
  124. int sign_modifier = 0;
  125. for (i = 0; i < nb_samples; i++) {
  126. int k;
  127. unsigned int x;
  128. /* calculate rice param and decode next value */
  129. k = av_log2((history >> 9) + 3);
  130. k = FFMIN(k, alac->rice_limit);
  131. x = decode_scalar(&alac->gb, k, bps);
  132. x += sign_modifier;
  133. sign_modifier = 0;
  134. output_buffer[i] = (x >> 1) ^ -(x & 1);
  135. /* update the history */
  136. if (x > 0xffff)
  137. history = 0xffff;
  138. else
  139. history += x * rice_history_mult -
  140. ((history * rice_history_mult) >> 9);
  141. /* special case: there may be compressed blocks of 0 */
  142. if ((history < 128) && (i + 1 < nb_samples)) {
  143. int block_size;
  144. /* calculate rice param and decode block size */
  145. k = 7 - av_log2(history) + ((history + 16) >> 6);
  146. k = FFMIN(k, alac->rice_limit);
  147. block_size = decode_scalar(&alac->gb, k, 16);
  148. if (block_size > 0) {
  149. if (block_size >= nb_samples - i) {
  150. av_log(alac->avctx, AV_LOG_ERROR,
  151. "invalid zero block size of %d %d %d\n", block_size,
  152. nb_samples, i);
  153. block_size = nb_samples - i - 1;
  154. }
  155. memset(&output_buffer[i + 1], 0,
  156. block_size * sizeof(*output_buffer));
  157. i += block_size;
  158. }
  159. if (block_size <= 0xffff)
  160. sign_modifier = 1;
  161. history = 0;
  162. }
  163. }
  164. }
  165. static inline int sign_only(int v)
  166. {
  167. return v ? FFSIGN(v) : 0;
  168. }
  169. static void lpc_prediction(int32_t *error_buffer, int32_t *buffer_out,
  170. int nb_samples, int bps, int16_t *lpc_coefs,
  171. int lpc_order, int lpc_quant)
  172. {
  173. int i;
  174. int32_t *pred = buffer_out;
  175. /* first sample always copies */
  176. *buffer_out = *error_buffer;
  177. if (nb_samples <= 1)
  178. return;
  179. if (!lpc_order) {
  180. memcpy(&buffer_out[1], &error_buffer[1],
  181. (nb_samples - 1) * sizeof(*buffer_out));
  182. return;
  183. }
  184. if (lpc_order == 31) {
  185. /* simple 1st-order prediction */
  186. for (i = 1; i < nb_samples; i++) {
  187. buffer_out[i] = sign_extend(buffer_out[i - 1] + error_buffer[i],
  188. bps);
  189. }
  190. return;
  191. }
  192. /* read warm-up samples */
  193. for (i = 1; i <= lpc_order; i++)
  194. buffer_out[i] = sign_extend(buffer_out[i - 1] + error_buffer[i], bps);
  195. /* NOTE: 4 and 8 are very common cases that could be optimized. */
  196. for (; i < nb_samples; i++) {
  197. int j;
  198. int val = 0;
  199. int error_val = error_buffer[i];
  200. int error_sign;
  201. int d = *pred++;
  202. /* LPC prediction */
  203. for (j = 0; j < lpc_order; j++)
  204. val += (pred[j] - d) * lpc_coefs[j];
  205. val = (val + (1 << (lpc_quant - 1))) >> lpc_quant;
  206. val += d + error_val;
  207. buffer_out[i] = sign_extend(val, bps);
  208. /* adapt LPC coefficients */
  209. error_sign = sign_only(error_val);
  210. if (error_sign) {
  211. for (j = 0; j < lpc_order && error_val * error_sign > 0; j++) {
  212. int sign;
  213. val = d - pred[j];
  214. sign = sign_only(val) * error_sign;
  215. lpc_coefs[j] -= sign;
  216. val *= sign;
  217. error_val -= (val >> lpc_quant) * (j + 1);
  218. }
  219. }
  220. }
  221. }
  222. static void decorrelate_stereo(int32_t *buffer[2], int nb_samples,
  223. int decorr_shift, int decorr_left_weight)
  224. {
  225. int i;
  226. for (i = 0; i < nb_samples; i++) {
  227. int32_t a, b;
  228. a = buffer[0][i];
  229. b = buffer[1][i];
  230. a -= (b * decorr_left_weight) >> decorr_shift;
  231. b += a;
  232. buffer[0][i] = b;
  233. buffer[1][i] = a;
  234. }
  235. }
  236. static void append_extra_bits(int32_t *buffer[2], int32_t *extra_bits_buffer[2],
  237. int extra_bits, int channels, int nb_samples)
  238. {
  239. int i, ch;
  240. for (ch = 0; ch < channels; ch++)
  241. for (i = 0; i < nb_samples; i++)
  242. buffer[ch][i] = (buffer[ch][i] << extra_bits) | extra_bits_buffer[ch][i];
  243. }
  244. static int decode_element(AVCodecContext *avctx, void *data, int ch_index,
  245. int channels)
  246. {
  247. ALACContext *alac = avctx->priv_data;
  248. int has_size, bps, is_compressed, decorr_shift, decorr_left_weight, ret;
  249. uint32_t output_samples;
  250. int i, ch;
  251. skip_bits(&alac->gb, 4); /* element instance tag */
  252. skip_bits(&alac->gb, 12); /* unused header bits */
  253. /* the number of output samples is stored in the frame */
  254. has_size = get_bits1(&alac->gb);
  255. alac->extra_bits = get_bits(&alac->gb, 2) << 3;
  256. bps = alac->sample_size - alac->extra_bits + channels - 1;
  257. if (bps > 32) {
  258. av_log(avctx, AV_LOG_ERROR, "bps is unsupported: %d\n", bps);
  259. return AVERROR_PATCHWELCOME;
  260. }
  261. /* whether the frame is compressed */
  262. is_compressed = !get_bits1(&alac->gb);
  263. if (has_size)
  264. output_samples = get_bits_long(&alac->gb, 32);
  265. else
  266. output_samples = alac->max_samples_per_frame;
  267. if (!output_samples || output_samples > alac->max_samples_per_frame) {
  268. av_log(avctx, AV_LOG_ERROR, "invalid samples per frame: %d\n",
  269. output_samples);
  270. return AVERROR_INVALIDDATA;
  271. }
  272. if (!alac->nb_samples) {
  273. /* get output buffer */
  274. alac->frame.nb_samples = output_samples;
  275. if ((ret = avctx->get_buffer(avctx, &alac->frame)) < 0) {
  276. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  277. return ret;
  278. }
  279. } else if (output_samples != alac->nb_samples) {
  280. av_log(avctx, AV_LOG_ERROR, "sample count mismatch: %u != %d\n",
  281. output_samples, alac->nb_samples);
  282. return AVERROR_INVALIDDATA;
  283. }
  284. alac->nb_samples = output_samples;
  285. if (alac->sample_size > 16) {
  286. for (ch = 0; ch < channels; ch++)
  287. alac->output_samples_buffer[ch] = (int32_t *)alac->frame.extended_data[ch_index + ch];
  288. }
  289. if (is_compressed) {
  290. int16_t lpc_coefs[2][32];
  291. int lpc_order[2];
  292. int prediction_type[2];
  293. int lpc_quant[2];
  294. int rice_history_mult[2];
  295. decorr_shift = get_bits(&alac->gb, 8);
  296. decorr_left_weight = get_bits(&alac->gb, 8);
  297. for (ch = 0; ch < channels; ch++) {
  298. prediction_type[ch] = get_bits(&alac->gb, 4);
  299. lpc_quant[ch] = get_bits(&alac->gb, 4);
  300. rice_history_mult[ch] = get_bits(&alac->gb, 3);
  301. lpc_order[ch] = get_bits(&alac->gb, 5);
  302. /* read the predictor table */
  303. for (i = lpc_order[ch] - 1; i >= 0; i--)
  304. lpc_coefs[ch][i] = get_sbits(&alac->gb, 16);
  305. }
  306. if (alac->extra_bits) {
  307. for (i = 0; i < alac->nb_samples; i++) {
  308. for (ch = 0; ch < channels; ch++)
  309. alac->extra_bits_buffer[ch][i] = get_bits(&alac->gb, alac->extra_bits);
  310. }
  311. }
  312. for (ch = 0; ch < channels; ch++) {
  313. rice_decompress(alac, alac->predict_error_buffer[ch],
  314. alac->nb_samples, bps,
  315. rice_history_mult[ch] * alac->rice_history_mult / 4);
  316. /* adaptive FIR filter */
  317. if (prediction_type[ch] == 15) {
  318. /* Prediction type 15 runs the adaptive FIR twice.
  319. * The first pass uses the special-case coef_num = 31, while
  320. * the second pass uses the coefs from the bitstream.
  321. *
  322. * However, this prediction type is not currently used by the
  323. * reference encoder.
  324. */
  325. lpc_prediction(alac->predict_error_buffer[ch],
  326. alac->predict_error_buffer[ch],
  327. alac->nb_samples, bps, NULL, 31, 0);
  328. } else if (prediction_type[ch] > 0) {
  329. av_log(avctx, AV_LOG_WARNING, "unknown prediction type: %i\n",
  330. prediction_type[ch]);
  331. }
  332. lpc_prediction(alac->predict_error_buffer[ch],
  333. alac->output_samples_buffer[ch], alac->nb_samples,
  334. bps, lpc_coefs[ch], lpc_order[ch], lpc_quant[ch]);
  335. }
  336. } else {
  337. /* not compressed, easy case */
  338. for (i = 0; i < alac->nb_samples; i++) {
  339. for (ch = 0; ch < channels; ch++) {
  340. alac->output_samples_buffer[ch][i] =
  341. get_sbits_long(&alac->gb, alac->sample_size);
  342. }
  343. }
  344. alac->extra_bits = 0;
  345. decorr_shift = 0;
  346. decorr_left_weight = 0;
  347. }
  348. if (channels == 2 && decorr_left_weight) {
  349. decorrelate_stereo(alac->output_samples_buffer, alac->nb_samples,
  350. decorr_shift, decorr_left_weight);
  351. }
  352. if (alac->extra_bits) {
  353. append_extra_bits(alac->output_samples_buffer, alac->extra_bits_buffer,
  354. alac->extra_bits, channels, alac->nb_samples);
  355. }
  356. switch(alac->sample_size) {
  357. case 16: {
  358. for (ch = 0; ch < channels; ch++) {
  359. int16_t *outbuffer = (int16_t *)alac->frame.extended_data[ch_index + ch];
  360. for (i = 0; i < alac->nb_samples; i++)
  361. *outbuffer++ = alac->output_samples_buffer[ch][i];
  362. }}
  363. break;
  364. case 24: {
  365. for (ch = 0; ch < channels; ch++) {
  366. for (i = 0; i < alac->nb_samples; i++)
  367. alac->output_samples_buffer[ch][i] <<= 8;
  368. }}
  369. break;
  370. }
  371. return 0;
  372. }
  373. static int alac_decode_frame(AVCodecContext *avctx, void *data,
  374. int *got_frame_ptr, AVPacket *avpkt)
  375. {
  376. ALACContext *alac = avctx->priv_data;
  377. enum RawDataBlockType element;
  378. int channels;
  379. int ch, ret, got_end;
  380. init_get_bits(&alac->gb, avpkt->data, avpkt->size * 8);
  381. got_end = 0;
  382. alac->nb_samples = 0;
  383. ch = 0;
  384. while (get_bits_left(&alac->gb) >= 3) {
  385. element = get_bits(&alac->gb, 3);
  386. if (element == TYPE_END) {
  387. got_end = 1;
  388. break;
  389. }
  390. if (element > TYPE_CPE && element != TYPE_LFE) {
  391. av_log(avctx, AV_LOG_ERROR, "syntax element unsupported: %d", element);
  392. return AVERROR_PATCHWELCOME;
  393. }
  394. channels = (element == TYPE_CPE) ? 2 : 1;
  395. if (ch + channels > alac->channels) {
  396. av_log(avctx, AV_LOG_ERROR, "invalid element channel count\n");
  397. return AVERROR_INVALIDDATA;
  398. }
  399. ret = decode_element(avctx, data,
  400. alac_channel_layout_offsets[alac->channels - 1][ch],
  401. channels);
  402. if (ret < 0 && get_bits_left(&alac->gb))
  403. return ret;
  404. ch += channels;
  405. }
  406. if (!got_end) {
  407. av_log(avctx, AV_LOG_ERROR, "no end tag found. incomplete packet.\n");
  408. return AVERROR_INVALIDDATA;
  409. }
  410. if (avpkt->size * 8 - get_bits_count(&alac->gb) > 8) {
  411. av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n",
  412. avpkt->size * 8 - get_bits_count(&alac->gb));
  413. }
  414. *got_frame_ptr = 1;
  415. *(AVFrame *)data = alac->frame;
  416. return avpkt->size;
  417. }
  418. static av_cold int alac_decode_close(AVCodecContext *avctx)
  419. {
  420. ALACContext *alac = avctx->priv_data;
  421. int ch;
  422. for (ch = 0; ch < FFMIN(alac->channels, 2); ch++) {
  423. av_freep(&alac->predict_error_buffer[ch]);
  424. if (alac->sample_size == 16)
  425. av_freep(&alac->output_samples_buffer[ch]);
  426. av_freep(&alac->extra_bits_buffer[ch]);
  427. }
  428. return 0;
  429. }
  430. static int allocate_buffers(ALACContext *alac)
  431. {
  432. int ch;
  433. int buf_size = alac->max_samples_per_frame * sizeof(int32_t);
  434. for (ch = 0; ch < FFMIN(alac->channels, 2); ch++) {
  435. FF_ALLOC_OR_GOTO(alac->avctx, alac->predict_error_buffer[ch],
  436. buf_size, buf_alloc_fail);
  437. if (alac->sample_size == 16) {
  438. FF_ALLOC_OR_GOTO(alac->avctx, alac->output_samples_buffer[ch],
  439. buf_size, buf_alloc_fail);
  440. }
  441. FF_ALLOC_OR_GOTO(alac->avctx, alac->extra_bits_buffer[ch],
  442. buf_size, buf_alloc_fail);
  443. }
  444. return 0;
  445. buf_alloc_fail:
  446. alac_decode_close(alac->avctx);
  447. return AVERROR(ENOMEM);
  448. }
  449. static int alac_set_info(ALACContext *alac)
  450. {
  451. GetByteContext gb;
  452. bytestream2_init(&gb, alac->avctx->extradata,
  453. alac->avctx->extradata_size);
  454. bytestream2_skipu(&gb, 12); // size:4, alac:4, version:4
  455. alac->max_samples_per_frame = bytestream2_get_be32u(&gb);
  456. if (!alac->max_samples_per_frame || alac->max_samples_per_frame > INT_MAX) {
  457. av_log(alac->avctx, AV_LOG_ERROR, "max samples per frame invalid: %u\n",
  458. alac->max_samples_per_frame);
  459. return AVERROR_INVALIDDATA;
  460. }
  461. bytestream2_skipu(&gb, 1); // compatible version
  462. alac->sample_size = bytestream2_get_byteu(&gb);
  463. alac->rice_history_mult = bytestream2_get_byteu(&gb);
  464. alac->rice_initial_history = bytestream2_get_byteu(&gb);
  465. alac->rice_limit = bytestream2_get_byteu(&gb);
  466. alac->channels = bytestream2_get_byteu(&gb);
  467. bytestream2_get_be16u(&gb); // maxRun
  468. bytestream2_get_be32u(&gb); // max coded frame size
  469. bytestream2_get_be32u(&gb); // average bitrate
  470. bytestream2_get_be32u(&gb); // samplerate
  471. return 0;
  472. }
  473. static av_cold int alac_decode_init(AVCodecContext * avctx)
  474. {
  475. int ret;
  476. ALACContext *alac = avctx->priv_data;
  477. alac->avctx = avctx;
  478. /* initialize from the extradata */
  479. if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
  480. av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
  481. ALAC_EXTRADATA_SIZE);
  482. return -1;
  483. }
  484. if (alac_set_info(alac)) {
  485. av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
  486. return -1;
  487. }
  488. switch (alac->sample_size) {
  489. case 16: avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
  490. break;
  491. case 24:
  492. case 32: avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
  493. break;
  494. default: av_log_ask_for_sample(avctx, "Sample depth %d is not supported.\n",
  495. alac->sample_size);
  496. return AVERROR_PATCHWELCOME;
  497. }
  498. if (alac->channels < 1) {
  499. av_log(avctx, AV_LOG_WARNING, "Invalid channel count\n");
  500. alac->channels = avctx->channels;
  501. } else {
  502. if (alac->channels > MAX_CHANNELS)
  503. alac->channels = avctx->channels;
  504. else
  505. avctx->channels = alac->channels;
  506. }
  507. if (avctx->channels > MAX_CHANNELS) {
  508. av_log(avctx, AV_LOG_ERROR, "Unsupported channel count: %d\n",
  509. avctx->channels);
  510. return AVERROR_PATCHWELCOME;
  511. }
  512. avctx->channel_layout = alac_channel_layouts[alac->channels - 1];
  513. if ((ret = allocate_buffers(alac)) < 0) {
  514. av_log(avctx, AV_LOG_ERROR, "Error allocating buffers\n");
  515. return ret;
  516. }
  517. avcodec_get_frame_defaults(&alac->frame);
  518. avctx->coded_frame = &alac->frame;
  519. return 0;
  520. }
  521. AVCodec ff_alac_decoder = {
  522. .name = "alac",
  523. .type = AVMEDIA_TYPE_AUDIO,
  524. .id = AV_CODEC_ID_ALAC,
  525. .priv_data_size = sizeof(ALACContext),
  526. .init = alac_decode_init,
  527. .close = alac_decode_close,
  528. .decode = alac_decode_frame,
  529. .capabilities = CODEC_CAP_DR1,
  530. .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
  531. };