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.

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