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.

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