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.

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