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.

653 lines
21KB

  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. GetBitContext gb;
  60. int numchannels;
  61. int bytespersample;
  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,
  284. void *outbuffer, int *outputsize,
  285. AVPacket *avpkt)
  286. {
  287. const uint8_t *inbuffer = avpkt->data;
  288. int input_buffer_size = avpkt->size;
  289. ALACContext *alac = avctx->priv_data;
  290. int channels;
  291. unsigned int outputsamples;
  292. int hassize;
  293. unsigned int readsamplesize;
  294. int isnotcompressed;
  295. uint8_t interlacing_shift;
  296. uint8_t interlacing_leftweight;
  297. int i, ch;
  298. init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
  299. channels = get_bits(&alac->gb, 3) + 1;
  300. if (channels != avctx->channels) {
  301. av_log(avctx, AV_LOG_ERROR, "frame header channel count mismatch\n");
  302. return AVERROR_INVALIDDATA;
  303. }
  304. /* 2^result = something to do with output waiting.
  305. * perhaps matters if we read > 1 frame in a pass?
  306. */
  307. skip_bits(&alac->gb, 4);
  308. skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
  309. /* the output sample size is stored soon */
  310. hassize = get_bits1(&alac->gb);
  311. alac->extra_bits = get_bits(&alac->gb, 2) << 3;
  312. /* whether the frame is compressed */
  313. isnotcompressed = get_bits1(&alac->gb);
  314. if (hassize) {
  315. /* now read the number of samples as a 32bit integer */
  316. outputsamples = get_bits_long(&alac->gb, 32);
  317. if(outputsamples > alac->setinfo_max_samples_per_frame){
  318. av_log(avctx, AV_LOG_ERROR, "outputsamples %d > %d\n", outputsamples, alac->setinfo_max_samples_per_frame);
  319. return -1;
  320. }
  321. } else
  322. outputsamples = alac->setinfo_max_samples_per_frame;
  323. alac->bytespersample = channels * av_get_bytes_per_sample(avctx->sample_fmt);
  324. if(outputsamples > *outputsize / alac->bytespersample){
  325. av_log(avctx, AV_LOG_ERROR, "sample buffer too small\n");
  326. return -1;
  327. }
  328. *outputsize = outputsamples * alac->bytespersample;
  329. readsamplesize = alac->setinfo_sample_size - alac->extra_bits + channels - 1;
  330. if (readsamplesize > MIN_CACHE_BITS) {
  331. av_log(avctx, AV_LOG_ERROR, "readsamplesize too big (%d)\n", readsamplesize);
  332. return -1;
  333. }
  334. if (!isnotcompressed) {
  335. /* so it is compressed */
  336. int16_t predictor_coef_table[MAX_CHANNELS][32];
  337. int predictor_coef_num[MAX_CHANNELS];
  338. int prediction_type[MAX_CHANNELS];
  339. int prediction_quantitization[MAX_CHANNELS];
  340. int ricemodifier[MAX_CHANNELS];
  341. interlacing_shift = get_bits(&alac->gb, 8);
  342. interlacing_leftweight = get_bits(&alac->gb, 8);
  343. for (ch = 0; ch < channels; ch++) {
  344. prediction_type[ch] = get_bits(&alac->gb, 4);
  345. prediction_quantitization[ch] = get_bits(&alac->gb, 4);
  346. ricemodifier[ch] = get_bits(&alac->gb, 3);
  347. predictor_coef_num[ch] = get_bits(&alac->gb, 5);
  348. /* read the predictor table */
  349. for (i = 0; i < predictor_coef_num[ch]; i++)
  350. predictor_coef_table[ch][i] = (int16_t)get_bits(&alac->gb, 16);
  351. }
  352. if (alac->extra_bits) {
  353. for (i = 0; i < outputsamples; i++) {
  354. for (ch = 0; ch < channels; ch++)
  355. alac->extra_bits_buffer[ch][i] = get_bits(&alac->gb, alac->extra_bits);
  356. }
  357. }
  358. for (ch = 0; ch < channels; ch++) {
  359. bastardized_rice_decompress(alac,
  360. alac->predicterror_buffer[ch],
  361. outputsamples,
  362. readsamplesize,
  363. alac->setinfo_rice_initialhistory,
  364. alac->setinfo_rice_kmodifier,
  365. ricemodifier[ch] * alac->setinfo_rice_historymult / 4,
  366. (1 << alac->setinfo_rice_kmodifier) - 1);
  367. if (prediction_type[ch] == 0) {
  368. /* adaptive fir */
  369. predictor_decompress_fir_adapt(alac->predicterror_buffer[ch],
  370. alac->outputsamples_buffer[ch],
  371. outputsamples,
  372. readsamplesize,
  373. predictor_coef_table[ch],
  374. predictor_coef_num[ch],
  375. prediction_quantitization[ch]);
  376. } else {
  377. av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[ch]);
  378. /* I think the only other prediction type (or perhaps this is
  379. * just a boolean?) runs adaptive fir twice.. like:
  380. * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
  381. * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
  382. * little strange..
  383. */
  384. }
  385. }
  386. } else {
  387. /* not compressed, easy case */
  388. for (i = 0; i < outputsamples; i++) {
  389. for (ch = 0; ch < channels; ch++) {
  390. alac->outputsamples_buffer[ch][i] = get_sbits_long(&alac->gb,
  391. alac->setinfo_sample_size);
  392. }
  393. }
  394. alac->extra_bits = 0;
  395. interlacing_shift = 0;
  396. interlacing_leftweight = 0;
  397. }
  398. if (get_bits(&alac->gb, 3) != 7)
  399. av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
  400. if (channels == 2 && interlacing_leftweight) {
  401. decorrelate_stereo(alac->outputsamples_buffer, outputsamples,
  402. interlacing_shift, interlacing_leftweight);
  403. }
  404. if (alac->extra_bits) {
  405. append_extra_bits(alac->outputsamples_buffer, alac->extra_bits_buffer,
  406. alac->extra_bits, alac->numchannels, outputsamples);
  407. }
  408. switch(alac->setinfo_sample_size) {
  409. case 16:
  410. if (channels == 2) {
  411. interleave_stereo_16(alac->outputsamples_buffer, outbuffer,
  412. outputsamples);
  413. } else {
  414. for (i = 0; i < outputsamples; i++) {
  415. ((int16_t*)outbuffer)[i] = alac->outputsamples_buffer[0][i];
  416. }
  417. }
  418. break;
  419. case 24:
  420. if (channels == 2) {
  421. interleave_stereo_24(alac->outputsamples_buffer, outbuffer,
  422. outputsamples);
  423. } else {
  424. for (i = 0; i < outputsamples; i++)
  425. ((int32_t *)outbuffer)[i] = alac->outputsamples_buffer[0][i] << 8;
  426. }
  427. break;
  428. }
  429. if (input_buffer_size * 8 - get_bits_count(&alac->gb) > 8)
  430. av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n", input_buffer_size * 8 - get_bits_count(&alac->gb));
  431. return input_buffer_size;
  432. }
  433. static av_cold int alac_decode_close(AVCodecContext *avctx)
  434. {
  435. ALACContext *alac = avctx->priv_data;
  436. int ch;
  437. for (ch = 0; ch < alac->numchannels; ch++) {
  438. av_freep(&alac->predicterror_buffer[ch]);
  439. av_freep(&alac->outputsamples_buffer[ch]);
  440. av_freep(&alac->extra_bits_buffer[ch]);
  441. }
  442. return 0;
  443. }
  444. static int allocate_buffers(ALACContext *alac)
  445. {
  446. int ch;
  447. for (ch = 0; ch < alac->numchannels; ch++) {
  448. int buf_size = alac->setinfo_max_samples_per_frame * sizeof(int32_t);
  449. FF_ALLOC_OR_GOTO(alac->avctx, alac->predicterror_buffer[ch],
  450. buf_size, buf_alloc_fail);
  451. FF_ALLOC_OR_GOTO(alac->avctx, alac->outputsamples_buffer[ch],
  452. buf_size, buf_alloc_fail);
  453. FF_ALLOC_OR_GOTO(alac->avctx, alac->extra_bits_buffer[ch],
  454. buf_size, buf_alloc_fail);
  455. }
  456. return 0;
  457. buf_alloc_fail:
  458. alac_decode_close(alac->avctx);
  459. return AVERROR(ENOMEM);
  460. }
  461. static int alac_set_info(ALACContext *alac)
  462. {
  463. const unsigned char *ptr = alac->avctx->extradata;
  464. ptr += 4; /* size */
  465. ptr += 4; /* alac */
  466. ptr += 4; /* 0 ? */
  467. if(AV_RB32(ptr) >= UINT_MAX/4){
  468. av_log(alac->avctx, AV_LOG_ERROR, "setinfo_max_samples_per_frame too large\n");
  469. return -1;
  470. }
  471. /* buffer size / 2 ? */
  472. alac->setinfo_max_samples_per_frame = bytestream_get_be32(&ptr);
  473. ptr++; /* ??? */
  474. alac->setinfo_sample_size = *ptr++;
  475. alac->setinfo_rice_historymult = *ptr++;
  476. alac->setinfo_rice_initialhistory = *ptr++;
  477. alac->setinfo_rice_kmodifier = *ptr++;
  478. alac->numchannels = *ptr++;
  479. bytestream_get_be16(&ptr); /* ??? */
  480. bytestream_get_be32(&ptr); /* max coded frame size */
  481. bytestream_get_be32(&ptr); /* bitrate ? */
  482. bytestream_get_be32(&ptr); /* samplerate */
  483. return 0;
  484. }
  485. static av_cold int alac_decode_init(AVCodecContext * avctx)
  486. {
  487. int ret;
  488. ALACContext *alac = avctx->priv_data;
  489. alac->avctx = avctx;
  490. /* initialize from the extradata */
  491. if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
  492. av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
  493. ALAC_EXTRADATA_SIZE);
  494. return -1;
  495. }
  496. if (alac_set_info(alac)) {
  497. av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
  498. return -1;
  499. }
  500. switch (alac->setinfo_sample_size) {
  501. case 16: avctx->sample_fmt = AV_SAMPLE_FMT_S16;
  502. break;
  503. case 24: avctx->sample_fmt = AV_SAMPLE_FMT_S32;
  504. break;
  505. default: av_log_ask_for_sample(avctx, "Sample depth %d is not supported.\n",
  506. alac->setinfo_sample_size);
  507. return AVERROR_PATCHWELCOME;
  508. }
  509. if (alac->numchannels < 1) {
  510. av_log(avctx, AV_LOG_WARNING, "Invalid channel count\n");
  511. alac->numchannels = avctx->channels;
  512. } else {
  513. if (alac->numchannels > MAX_CHANNELS)
  514. alac->numchannels = avctx->channels;
  515. else
  516. avctx->channels = alac->numchannels;
  517. }
  518. if (avctx->channels > MAX_CHANNELS) {
  519. av_log(avctx, AV_LOG_ERROR, "Unsupported channel count: %d\n",
  520. avctx->channels);
  521. return AVERROR_PATCHWELCOME;
  522. }
  523. if ((ret = allocate_buffers(alac)) < 0) {
  524. av_log(avctx, AV_LOG_ERROR, "Error allocating buffers\n");
  525. return ret;
  526. }
  527. return 0;
  528. }
  529. AVCodec ff_alac_decoder = {
  530. .name = "alac",
  531. .type = AVMEDIA_TYPE_AUDIO,
  532. .id = CODEC_ID_ALAC,
  533. .priv_data_size = sizeof(ALACContext),
  534. .init = alac_decode_init,
  535. .close = alac_decode_close,
  536. .decode = alac_decode_frame,
  537. .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
  538. };