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.

567 lines
19KB

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