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.

629 lines
20KB

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