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.

664 lines
22KB

  1. /*
  2. * ALAC (Apple Lossless Audio Codec) decoder
  3. * Copyright (c) 2005 David Hammerton
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg 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. * FFmpeg 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 FFmpeg; 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- (0x24-)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. * bytes 0-3 atom size (0x24), big-endian
  31. * bytes 4-7 atom type ('alac', not the 'alac' tag from start of stsd)
  32. * bytes 8-35 data bytes needed by decoder
  33. *
  34. * Extradata:
  35. * 32bit size
  36. * 32bit tag (=alac)
  37. * 32bit zero?
  38. * 32bit max sample per frame
  39. * 8bit ?? (zero?)
  40. * 8bit sample size
  41. * 8bit history mult
  42. * 8bit initial history
  43. * 8bit kmodifier
  44. * 8bit channels?
  45. * 16bit ??
  46. * 32bit max coded frame size
  47. * 32bit bitrate?
  48. * 32bit samplerate
  49. */
  50. #include "avcodec.h"
  51. #include "get_bits.h"
  52. #include "bytestream.h"
  53. #include "unary.h"
  54. #include "mathops.h"
  55. #define ALAC_EXTRADATA_SIZE 36
  56. #define MAX_CHANNELS 2
  57. typedef struct {
  58. AVCodecContext *avctx;
  59. AVFrame frame;
  60. GetBitContext gb;
  61. int numchannels;
  62. /* buffers */
  63. int32_t *predicterror_buffer[MAX_CHANNELS];
  64. int32_t *outputsamples_buffer[MAX_CHANNELS];
  65. int32_t *extra_bits_buffer[MAX_CHANNELS];
  66. /* stuff from setinfo */
  67. uint32_t setinfo_max_samples_per_frame; /* 0x1000 = 4096 */ /* max samples per frame? */
  68. uint8_t setinfo_sample_size; /* 0x10 */
  69. uint8_t setinfo_rice_historymult; /* 0x28 */
  70. uint8_t setinfo_rice_initialhistory; /* 0x0a */
  71. uint8_t setinfo_rice_kmodifier; /* 0x0e */
  72. /* end setinfo stuff */
  73. int extra_bits; /**< number of extra bits beyond 16-bit */
  74. } ALACContext;
  75. static inline int decode_scalar(GetBitContext *gb, int k, int limit, int readsamplesize){
  76. /* read x - number of 1s before 0 represent the rice */
  77. int x = get_unary_0_9(gb);
  78. if (x > 8) { /* RICE THRESHOLD */
  79. /* use alternative encoding */
  80. x = get_bits(gb, readsamplesize);
  81. } else {
  82. if (k >= limit)
  83. k = limit;
  84. if (k != 1) {
  85. int extrabits = show_bits(gb, k);
  86. /* multiply x by 2^k - 1, as part of their strange algorithm */
  87. x = (x << k) - x;
  88. if (extrabits > 1) {
  89. x += extrabits - 1;
  90. skip_bits(gb, k);
  91. } else
  92. skip_bits(gb, k - 1);
  93. }
  94. }
  95. return x;
  96. }
  97. static void bastardized_rice_decompress(ALACContext *alac,
  98. int32_t *output_buffer,
  99. int output_size,
  100. int readsamplesize, /* arg_10 */
  101. int rice_initialhistory, /* arg424->b */
  102. int rice_kmodifier, /* arg424->d */
  103. int rice_historymult, /* arg424->c */
  104. int rice_kmodifier_mask /* arg424->e */
  105. )
  106. {
  107. int output_count;
  108. unsigned int history = rice_initialhistory;
  109. int sign_modifier = 0;
  110. for (output_count = 0; output_count < output_size; output_count++) {
  111. int32_t x;
  112. int32_t x_modified;
  113. int32_t final_val;
  114. /* standard rice encoding */
  115. int k; /* size of extra bits */
  116. /* read k, that is bits as is */
  117. k = av_log2((history >> 9) + 3);
  118. x= decode_scalar(&alac->gb, k, rice_kmodifier, readsamplesize);
  119. x_modified = sign_modifier + x;
  120. final_val = (x_modified + 1) / 2;
  121. if (x_modified & 1) final_val *= -1;
  122. output_buffer[output_count] = final_val;
  123. sign_modifier = 0;
  124. /* now update the history */
  125. history += x_modified * rice_historymult
  126. - ((history * rice_historymult) >> 9);
  127. if (x_modified > 0xffff)
  128. history = 0xffff;
  129. /* special case: there may be compressed blocks of 0 */
  130. if ((history < 128) && (output_count+1 < output_size)) {
  131. int k;
  132. unsigned int block_size;
  133. sign_modifier = 1;
  134. k = 7 - av_log2(history) + ((history + 16) >> 6 /* / 64 */);
  135. block_size= decode_scalar(&alac->gb, k, rice_kmodifier, 16);
  136. if (block_size > 0) {
  137. if(block_size >= output_size - output_count){
  138. av_log(alac->avctx, AV_LOG_ERROR, "invalid zero block size of %d %d %d\n", block_size, output_size, output_count);
  139. block_size= output_size - output_count - 1;
  140. }
  141. memset(&output_buffer[output_count+1], 0, block_size * 4);
  142. output_count += block_size;
  143. }
  144. if (block_size > 0xffff)
  145. sign_modifier = 0;
  146. history = 0;
  147. }
  148. }
  149. }
  150. static inline int sign_only(int v)
  151. {
  152. return v ? FFSIGN(v) : 0;
  153. }
  154. static void predictor_decompress_fir_adapt(int32_t *error_buffer,
  155. int32_t *buffer_out,
  156. int output_size,
  157. int readsamplesize,
  158. int16_t *predictor_coef_table,
  159. int predictor_coef_num,
  160. int predictor_quantitization)
  161. {
  162. int i;
  163. /* first sample always copies */
  164. *buffer_out = *error_buffer;
  165. if (!predictor_coef_num) {
  166. if (output_size <= 1)
  167. return;
  168. memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
  169. return;
  170. }
  171. if (predictor_coef_num == 0x1f) { /* 11111 - max value of predictor_coef_num */
  172. /* second-best case scenario for fir decompression,
  173. * error describes a small difference from the previous sample only
  174. */
  175. if (output_size <= 1)
  176. return;
  177. for (i = 0; i < output_size - 1; i++) {
  178. int32_t prev_value;
  179. int32_t error_value;
  180. prev_value = buffer_out[i];
  181. error_value = error_buffer[i+1];
  182. buffer_out[i+1] =
  183. sign_extend((prev_value + error_value), readsamplesize);
  184. }
  185. return;
  186. }
  187. /* read warm-up samples */
  188. if (predictor_coef_num > 0)
  189. for (i = 0; i < predictor_coef_num; i++) {
  190. int32_t val;
  191. val = buffer_out[i] + error_buffer[i+1];
  192. val = sign_extend(val, readsamplesize);
  193. buffer_out[i+1] = val;
  194. }
  195. /* 4 and 8 are very common cases (the only ones i've seen). these
  196. * should be unrolled and optimized
  197. */
  198. /* general case */
  199. if (predictor_coef_num > 0) {
  200. for (i = predictor_coef_num + 1; i < output_size; i++) {
  201. int j;
  202. int sum = 0;
  203. int outval;
  204. int error_val = error_buffer[i];
  205. for (j = 0; j < predictor_coef_num; j++) {
  206. sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
  207. predictor_coef_table[j];
  208. }
  209. outval = (1 << (predictor_quantitization-1)) + sum;
  210. outval = outval >> predictor_quantitization;
  211. outval = outval + buffer_out[0] + error_val;
  212. outval = sign_extend(outval, readsamplesize);
  213. buffer_out[predictor_coef_num+1] = outval;
  214. if (error_val > 0) {
  215. int predictor_num = predictor_coef_num - 1;
  216. while (predictor_num >= 0 && error_val > 0) {
  217. int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
  218. int sign = sign_only(val);
  219. predictor_coef_table[predictor_num] -= sign;
  220. val *= sign; /* absolute value */
  221. error_val -= ((val >> predictor_quantitization) *
  222. (predictor_coef_num - predictor_num));
  223. predictor_num--;
  224. }
  225. } else if (error_val < 0) {
  226. int predictor_num = predictor_coef_num - 1;
  227. while (predictor_num >= 0 && error_val < 0) {
  228. int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
  229. int sign = - sign_only(val);
  230. predictor_coef_table[predictor_num] -= sign;
  231. val *= sign; /* neg value */
  232. error_val -= ((val >> predictor_quantitization) *
  233. (predictor_coef_num - predictor_num));
  234. predictor_num--;
  235. }
  236. }
  237. buffer_out++;
  238. }
  239. }
  240. }
  241. static void decorrelate_stereo(int32_t *buffer[MAX_CHANNELS],
  242. int numsamples, uint8_t interlacing_shift,
  243. uint8_t interlacing_leftweight)
  244. {
  245. int i;
  246. for (i = 0; i < numsamples; i++) {
  247. int32_t a, b;
  248. a = buffer[0][i];
  249. b = buffer[1][i];
  250. a -= (b * interlacing_leftweight) >> interlacing_shift;
  251. b += a;
  252. buffer[0][i] = b;
  253. buffer[1][i] = a;
  254. }
  255. }
  256. static void append_extra_bits(int32_t *buffer[MAX_CHANNELS],
  257. int32_t *extra_bits_buffer[MAX_CHANNELS],
  258. int extra_bits, int numchannels, int numsamples)
  259. {
  260. int i, ch;
  261. for (ch = 0; ch < numchannels; ch++)
  262. for (i = 0; i < numsamples; i++)
  263. buffer[ch][i] = (buffer[ch][i] << extra_bits) | extra_bits_buffer[ch][i];
  264. }
  265. static void interleave_stereo_16(int32_t *buffer[MAX_CHANNELS],
  266. int16_t *buffer_out, int numsamples)
  267. {
  268. int i;
  269. for (i = 0; i < numsamples; i++) {
  270. *buffer_out++ = buffer[0][i];
  271. *buffer_out++ = buffer[1][i];
  272. }
  273. }
  274. static void interleave_stereo_24(int32_t *buffer[MAX_CHANNELS],
  275. int32_t *buffer_out, int numsamples)
  276. {
  277. int i;
  278. for (i = 0; i < numsamples; i++) {
  279. *buffer_out++ = buffer[0][i] << 8;
  280. *buffer_out++ = buffer[1][i] << 8;
  281. }
  282. }
  283. static int alac_decode_frame(AVCodecContext *avctx, void *data,
  284. int *got_frame_ptr, AVPacket *avpkt)
  285. {
  286. const uint8_t *inbuffer = avpkt->data;
  287. int input_buffer_size = avpkt->size;
  288. ALACContext *alac = avctx->priv_data;
  289. int channels;
  290. unsigned int outputsamples;
  291. int hassize;
  292. unsigned int readsamplesize;
  293. int isnotcompressed;
  294. uint8_t interlacing_shift;
  295. uint8_t interlacing_leftweight;
  296. int i, ch, ret;
  297. init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
  298. channels = get_bits(&alac->gb, 3) + 1;
  299. if (channels != avctx->channels) {
  300. av_log(avctx, AV_LOG_ERROR, "frame header channel count mismatch\n");
  301. return AVERROR_INVALIDDATA;
  302. }
  303. /* 2^result = something to do with output waiting.
  304. * perhaps matters if we read > 1 frame in a pass?
  305. */
  306. skip_bits(&alac->gb, 4);
  307. skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
  308. /* the output sample size is stored soon */
  309. hassize = get_bits1(&alac->gb);
  310. alac->extra_bits = get_bits(&alac->gb, 2) << 3;
  311. /* whether the frame is compressed */
  312. isnotcompressed = get_bits1(&alac->gb);
  313. if (hassize) {
  314. /* now read the number of samples as a 32bit integer */
  315. outputsamples = get_bits_long(&alac->gb, 32);
  316. if(outputsamples > alac->setinfo_max_samples_per_frame){
  317. av_log(avctx, AV_LOG_ERROR, "outputsamples %d > %d\n", outputsamples, alac->setinfo_max_samples_per_frame);
  318. return -1;
  319. }
  320. } else
  321. outputsamples = alac->setinfo_max_samples_per_frame;
  322. /* get output buffer */
  323. if (outputsamples > INT32_MAX) {
  324. av_log(avctx, AV_LOG_ERROR, "unsupported block size: %u\n", outputsamples);
  325. return AVERROR_INVALIDDATA;
  326. }
  327. alac->frame.nb_samples = outputsamples;
  328. if ((ret = avctx->get_buffer(avctx, &alac->frame)) < 0) {
  329. av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
  330. return ret;
  331. }
  332. readsamplesize = alac->setinfo_sample_size - alac->extra_bits + channels - 1;
  333. if (readsamplesize > MIN_CACHE_BITS) {
  334. av_log(avctx, AV_LOG_ERROR, "readsamplesize too big (%d)\n", readsamplesize);
  335. return -1;
  336. }
  337. if (!isnotcompressed) {
  338. /* so it is compressed */
  339. int16_t predictor_coef_table[MAX_CHANNELS][32];
  340. int predictor_coef_num[MAX_CHANNELS];
  341. int prediction_type[MAX_CHANNELS];
  342. int prediction_quantitization[MAX_CHANNELS];
  343. int ricemodifier[MAX_CHANNELS];
  344. interlacing_shift = get_bits(&alac->gb, 8);
  345. interlacing_leftweight = get_bits(&alac->gb, 8);
  346. for (ch = 0; ch < channels; ch++) {
  347. prediction_type[ch] = get_bits(&alac->gb, 4);
  348. prediction_quantitization[ch] = get_bits(&alac->gb, 4);
  349. ricemodifier[ch] = get_bits(&alac->gb, 3);
  350. predictor_coef_num[ch] = get_bits(&alac->gb, 5);
  351. /* read the predictor table */
  352. for (i = 0; i < predictor_coef_num[ch]; i++)
  353. predictor_coef_table[ch][i] = (int16_t)get_bits(&alac->gb, 16);
  354. }
  355. if (alac->extra_bits) {
  356. for (i = 0; i < outputsamples; i++) {
  357. for (ch = 0; ch < channels; ch++)
  358. alac->extra_bits_buffer[ch][i] = get_bits(&alac->gb, alac->extra_bits);
  359. }
  360. }
  361. for (ch = 0; ch < channels; ch++) {
  362. bastardized_rice_decompress(alac,
  363. alac->predicterror_buffer[ch],
  364. outputsamples,
  365. readsamplesize,
  366. alac->setinfo_rice_initialhistory,
  367. alac->setinfo_rice_kmodifier,
  368. ricemodifier[ch] * alac->setinfo_rice_historymult / 4,
  369. (1 << alac->setinfo_rice_kmodifier) - 1);
  370. if (prediction_type[ch] == 0) {
  371. /* adaptive fir */
  372. predictor_decompress_fir_adapt(alac->predicterror_buffer[ch],
  373. alac->outputsamples_buffer[ch],
  374. outputsamples,
  375. readsamplesize,
  376. predictor_coef_table[ch],
  377. predictor_coef_num[ch],
  378. prediction_quantitization[ch]);
  379. } else {
  380. av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[ch]);
  381. /* I think the only other prediction type (or perhaps this is
  382. * just a boolean?) runs adaptive fir twice.. like:
  383. * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
  384. * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
  385. * little strange..
  386. */
  387. }
  388. }
  389. } else {
  390. /* not compressed, easy case */
  391. for (i = 0; i < outputsamples; i++) {
  392. for (ch = 0; ch < channels; ch++) {
  393. alac->outputsamples_buffer[ch][i] = get_sbits_long(&alac->gb,
  394. alac->setinfo_sample_size);
  395. }
  396. }
  397. alac->extra_bits = 0;
  398. interlacing_shift = 0;
  399. interlacing_leftweight = 0;
  400. }
  401. if (get_bits(&alac->gb, 3) != 7)
  402. av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
  403. if (channels == 2 && interlacing_leftweight) {
  404. decorrelate_stereo(alac->outputsamples_buffer, outputsamples,
  405. interlacing_shift, interlacing_leftweight);
  406. }
  407. if (alac->extra_bits) {
  408. append_extra_bits(alac->outputsamples_buffer, alac->extra_bits_buffer,
  409. alac->extra_bits, alac->numchannels, outputsamples);
  410. }
  411. switch(alac->setinfo_sample_size) {
  412. case 16:
  413. if (channels == 2) {
  414. interleave_stereo_16(alac->outputsamples_buffer,
  415. (int16_t *)alac->frame.data[0], outputsamples);
  416. } else {
  417. int16_t *outbuffer = (int16_t *)alac->frame.data[0];
  418. for (i = 0; i < outputsamples; i++) {
  419. outbuffer[i] = alac->outputsamples_buffer[0][i];
  420. }
  421. }
  422. break;
  423. case 24:
  424. if (channels == 2) {
  425. interleave_stereo_24(alac->outputsamples_buffer,
  426. (int32_t *)alac->frame.data[0], outputsamples);
  427. } else {
  428. int32_t *outbuffer = (int32_t *)alac->frame.data[0];
  429. for (i = 0; i < outputsamples; i++)
  430. outbuffer[i] = alac->outputsamples_buffer[0][i] << 8;
  431. }
  432. break;
  433. }
  434. if (input_buffer_size * 8 - get_bits_count(&alac->gb) > 8)
  435. av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n", input_buffer_size * 8 - get_bits_count(&alac->gb));
  436. *got_frame_ptr = 1;
  437. *(AVFrame *)data = alac->frame;
  438. return input_buffer_size;
  439. }
  440. static av_cold int alac_decode_close(AVCodecContext *avctx)
  441. {
  442. ALACContext *alac = avctx->priv_data;
  443. int ch;
  444. for (ch = 0; ch < alac->numchannels; ch++) {
  445. av_freep(&alac->predicterror_buffer[ch]);
  446. av_freep(&alac->outputsamples_buffer[ch]);
  447. av_freep(&alac->extra_bits_buffer[ch]);
  448. }
  449. return 0;
  450. }
  451. static int allocate_buffers(ALACContext *alac)
  452. {
  453. int ch;
  454. for (ch = 0; ch < alac->numchannels; ch++) {
  455. int buf_size = alac->setinfo_max_samples_per_frame * sizeof(int32_t);
  456. FF_ALLOC_OR_GOTO(alac->avctx, alac->predicterror_buffer[ch],
  457. buf_size, buf_alloc_fail);
  458. FF_ALLOC_OR_GOTO(alac->avctx, alac->outputsamples_buffer[ch],
  459. buf_size, buf_alloc_fail);
  460. FF_ALLOC_OR_GOTO(alac->avctx, alac->extra_bits_buffer[ch],
  461. buf_size, buf_alloc_fail);
  462. }
  463. return 0;
  464. buf_alloc_fail:
  465. alac_decode_close(alac->avctx);
  466. return AVERROR(ENOMEM);
  467. }
  468. static int alac_set_info(ALACContext *alac)
  469. {
  470. const unsigned char *ptr = alac->avctx->extradata;
  471. ptr += 4; /* size */
  472. ptr += 4; /* alac */
  473. ptr += 4; /* 0 ? */
  474. if(AV_RB32(ptr) >= UINT_MAX/4){
  475. av_log(alac->avctx, AV_LOG_ERROR, "setinfo_max_samples_per_frame too large\n");
  476. return -1;
  477. }
  478. /* buffer size / 2 ? */
  479. alac->setinfo_max_samples_per_frame = bytestream_get_be32(&ptr);
  480. ptr++; /* ??? */
  481. alac->setinfo_sample_size = *ptr++;
  482. alac->setinfo_rice_historymult = *ptr++;
  483. alac->setinfo_rice_initialhistory = *ptr++;
  484. alac->setinfo_rice_kmodifier = *ptr++;
  485. alac->numchannels = *ptr++;
  486. bytestream_get_be16(&ptr); /* ??? */
  487. bytestream_get_be32(&ptr); /* max coded frame size */
  488. bytestream_get_be32(&ptr); /* bitrate ? */
  489. bytestream_get_be32(&ptr); /* samplerate */
  490. return 0;
  491. }
  492. static av_cold int alac_decode_init(AVCodecContext * avctx)
  493. {
  494. int ret;
  495. ALACContext *alac = avctx->priv_data;
  496. alac->avctx = avctx;
  497. /* initialize from the extradata */
  498. if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
  499. av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
  500. ALAC_EXTRADATA_SIZE);
  501. return -1;
  502. }
  503. if (alac_set_info(alac)) {
  504. av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
  505. return -1;
  506. }
  507. switch (alac->setinfo_sample_size) {
  508. case 16: avctx->sample_fmt = AV_SAMPLE_FMT_S16;
  509. break;
  510. case 24: avctx->sample_fmt = AV_SAMPLE_FMT_S32;
  511. break;
  512. default: av_log_ask_for_sample(avctx, "Sample depth %d is not supported.\n",
  513. alac->setinfo_sample_size);
  514. return AVERROR_PATCHWELCOME;
  515. }
  516. if (alac->numchannels < 1) {
  517. av_log(avctx, AV_LOG_WARNING, "Invalid channel count\n");
  518. alac->numchannels = avctx->channels;
  519. } else {
  520. if (alac->numchannels > MAX_CHANNELS)
  521. alac->numchannels = avctx->channels;
  522. else
  523. avctx->channels = alac->numchannels;
  524. }
  525. if (avctx->channels > MAX_CHANNELS) {
  526. av_log(avctx, AV_LOG_ERROR, "Unsupported channel count: %d\n",
  527. avctx->channels);
  528. return AVERROR_PATCHWELCOME;
  529. }
  530. if ((ret = allocate_buffers(alac)) < 0) {
  531. av_log(avctx, AV_LOG_ERROR, "Error allocating buffers\n");
  532. return ret;
  533. }
  534. avcodec_get_frame_defaults(&alac->frame);
  535. avctx->coded_frame = &alac->frame;
  536. return 0;
  537. }
  538. AVCodec ff_alac_decoder = {
  539. .name = "alac",
  540. .type = AVMEDIA_TYPE_AUDIO,
  541. .id = CODEC_ID_ALAC,
  542. .priv_data_size = sizeof(ALACContext),
  543. .init = alac_decode_init,
  544. .close = alac_decode_close,
  545. .decode = alac_decode_frame,
  546. .capabilities = CODEC_CAP_DR1,
  547. .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
  548. };