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.

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