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.

623 lines
20KB

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