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.

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