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.

633 lines
21KB

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