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