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.

661 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 - count_leading_zeros((history >> 9) + 3);
  160. if (k >= rice_kmodifier)
  161. k = rice_kmodifier;
  162. if (k != 1) {
  163. extrabits = show_bits(&alac->gb, k);
  164. /* multiply x by 2^k - 1, as part of their strange algorithm */
  165. x = (x << k) - x;
  166. if (extrabits > 1) {
  167. x += extrabits - 1;
  168. skip_bits(&alac->gb, k);
  169. } else
  170. skip_bits(&alac->gb, k - 1);
  171. }
  172. }
  173. x_modified = sign_modifier + x;
  174. final_val = (x_modified + 1) / 2;
  175. if (x_modified & 1) final_val *= -1;
  176. output_buffer[output_count] = final_val;
  177. sign_modifier = 0;
  178. /* now update the history */
  179. history += x_modified * rice_historymult
  180. - ((history * rice_historymult) >> 9);
  181. if (x_modified > 0xffff)
  182. history = 0xffff;
  183. /* special case: there may be compressed blocks of 0 */
  184. if ((history < 128) && (output_count+1 < output_size)) {
  185. int block_size;
  186. sign_modifier = 1;
  187. x = get_unary_0_9(&alac->gb);
  188. if (x > 8) {
  189. block_size = get_bits(&alac->gb, 16);
  190. block_size &= 0xffff;
  191. } else {
  192. int k;
  193. int extrabits;
  194. k = count_leading_zeros(history) + ((history + 16) >> 6 /* / 64 */) - 24;
  195. extrabits = show_bits(&alac->gb, k);
  196. block_size = (((1 << k) - 1) & rice_kmodifier_mask) * x
  197. + extrabits - 1;
  198. if (extrabits < 2) {
  199. x = 1 - extrabits;
  200. block_size += x;
  201. skip_bits(&alac->gb, k - 1);
  202. } else {
  203. skip_bits(&alac->gb, k);
  204. }
  205. }
  206. if (block_size > 0) {
  207. memset(&output_buffer[output_count+1], 0, block_size * 4);
  208. output_count += block_size;
  209. }
  210. if (block_size > 0xffff)
  211. sign_modifier = 0;
  212. history = 0;
  213. }
  214. }
  215. }
  216. static inline int32_t extend_sign32(int32_t val, int bits)
  217. {
  218. return (val << (32 - bits)) >> (32 - bits);
  219. }
  220. static inline int sign_only(int v)
  221. {
  222. return v ? FFSIGN(v) : 0;
  223. }
  224. static void predictor_decompress_fir_adapt(int32_t *error_buffer,
  225. int32_t *buffer_out,
  226. int output_size,
  227. int readsamplesize,
  228. int16_t *predictor_coef_table,
  229. int predictor_coef_num,
  230. int predictor_quantitization)
  231. {
  232. int i;
  233. /* first sample always copies */
  234. *buffer_out = *error_buffer;
  235. if (!predictor_coef_num) {
  236. if (output_size <= 1)
  237. return;
  238. memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
  239. return;
  240. }
  241. if (predictor_coef_num == 0x1f) { /* 11111 - max value of predictor_coef_num */
  242. /* second-best case scenario for fir decompression,
  243. * error describes a small difference from the previous sample only
  244. */
  245. if (output_size <= 1)
  246. return;
  247. for (i = 0; i < output_size - 1; i++) {
  248. int32_t prev_value;
  249. int32_t error_value;
  250. prev_value = buffer_out[i];
  251. error_value = error_buffer[i+1];
  252. buffer_out[i+1] =
  253. extend_sign32((prev_value + error_value), readsamplesize);
  254. }
  255. return;
  256. }
  257. /* read warm-up samples */
  258. if (predictor_coef_num > 0)
  259. for (i = 0; i < predictor_coef_num; i++) {
  260. int32_t val;
  261. val = buffer_out[i] + error_buffer[i+1];
  262. val = extend_sign32(val, readsamplesize);
  263. buffer_out[i+1] = val;
  264. }
  265. #if 0
  266. /* 4 and 8 are very common cases (the only ones i've seen). these
  267. * should be unrolled and optimized
  268. */
  269. if (predictor_coef_num == 4) {
  270. /* FIXME: optimized general case */
  271. return;
  272. }
  273. if (predictor_coef_table == 8) {
  274. /* FIXME: optimized general case */
  275. return;
  276. }
  277. #endif
  278. /* general case */
  279. if (predictor_coef_num > 0) {
  280. for (i = predictor_coef_num + 1; i < output_size; i++) {
  281. int j;
  282. int sum = 0;
  283. int outval;
  284. int error_val = error_buffer[i];
  285. for (j = 0; j < predictor_coef_num; j++) {
  286. sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
  287. predictor_coef_table[j];
  288. }
  289. outval = (1 << (predictor_quantitization-1)) + sum;
  290. outval = outval >> predictor_quantitization;
  291. outval = outval + buffer_out[0] + error_val;
  292. outval = extend_sign32(outval, readsamplesize);
  293. buffer_out[predictor_coef_num+1] = outval;
  294. if (error_val > 0) {
  295. int predictor_num = predictor_coef_num - 1;
  296. while (predictor_num >= 0 && error_val > 0) {
  297. int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
  298. int sign = sign_only(val);
  299. predictor_coef_table[predictor_num] -= sign;
  300. val *= sign; /* absolute value */
  301. error_val -= ((val >> predictor_quantitization) *
  302. (predictor_coef_num - predictor_num));
  303. predictor_num--;
  304. }
  305. } else if (error_val < 0) {
  306. int predictor_num = predictor_coef_num - 1;
  307. while (predictor_num >= 0 && error_val < 0) {
  308. int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
  309. int sign = - sign_only(val);
  310. predictor_coef_table[predictor_num] -= sign;
  311. val *= sign; /* neg value */
  312. error_val -= ((val >> predictor_quantitization) *
  313. (predictor_coef_num - predictor_num));
  314. predictor_num--;
  315. }
  316. }
  317. buffer_out++;
  318. }
  319. }
  320. }
  321. static void reconstruct_stereo_16(int32_t *buffer[MAX_CHANNELS],
  322. int16_t *buffer_out,
  323. int numchannels, int numsamples,
  324. uint8_t interlacing_shift,
  325. uint8_t interlacing_leftweight)
  326. {
  327. int i;
  328. if (numsamples <= 0)
  329. return;
  330. /* weighted interlacing */
  331. if (interlacing_leftweight) {
  332. for (i = 0; i < numsamples; i++) {
  333. int32_t a, b;
  334. a = buffer[0][i];
  335. b = buffer[1][i];
  336. a -= (b * interlacing_leftweight) >> interlacing_shift;
  337. b += a;
  338. buffer_out[i*numchannels] = b;
  339. buffer_out[i*numchannels + 1] = a;
  340. }
  341. return;
  342. }
  343. /* otherwise basic interlacing took place */
  344. for (i = 0; i < numsamples; i++) {
  345. int16_t left, right;
  346. left = buffer[0][i];
  347. right = buffer[1][i];
  348. buffer_out[i*numchannels] = left;
  349. buffer_out[i*numchannels + 1] = right;
  350. }
  351. }
  352. static int alac_decode_frame(AVCodecContext *avctx,
  353. void *outbuffer, int *outputsize,
  354. const uint8_t *inbuffer, int input_buffer_size)
  355. {
  356. ALACContext *alac = avctx->priv_data;
  357. int channels;
  358. int32_t outputsamples;
  359. int hassize;
  360. int readsamplesize;
  361. int wasted_bytes;
  362. int isnotcompressed;
  363. uint8_t interlacing_shift;
  364. uint8_t interlacing_leftweight;
  365. /* short-circuit null buffers */
  366. if (!inbuffer || !input_buffer_size)
  367. return input_buffer_size;
  368. /* initialize from the extradata */
  369. if (!alac->context_initialized) {
  370. if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
  371. av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
  372. ALAC_EXTRADATA_SIZE);
  373. return input_buffer_size;
  374. }
  375. if (alac_set_info(alac)) {
  376. av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
  377. return input_buffer_size;
  378. }
  379. alac->context_initialized = 1;
  380. }
  381. init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
  382. channels = get_bits(&alac->gb, 3) + 1;
  383. if (channels > MAX_CHANNELS) {
  384. av_log(avctx, AV_LOG_ERROR, "channels > %d not supported\n",
  385. MAX_CHANNELS);
  386. return input_buffer_size;
  387. }
  388. /* 2^result = something to do with output waiting.
  389. * perhaps matters if we read > 1 frame in a pass?
  390. */
  391. skip_bits(&alac->gb, 4);
  392. skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
  393. /* the output sample size is stored soon */
  394. hassize = get_bits1(&alac->gb);
  395. wasted_bytes = get_bits(&alac->gb, 2); /* unknown ? */
  396. /* whether the frame is compressed */
  397. isnotcompressed = get_bits1(&alac->gb);
  398. if (hassize) {
  399. /* now read the number of samples as a 32bit integer */
  400. outputsamples = get_bits(&alac->gb, 32);
  401. } else
  402. outputsamples = alac->setinfo_max_samples_per_frame;
  403. *outputsize = outputsamples * alac->bytespersample;
  404. readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8) + channels - 1;
  405. if (!isnotcompressed) {
  406. /* so it is compressed */
  407. int16_t predictor_coef_table[channels][32];
  408. int predictor_coef_num[channels];
  409. int prediction_type[channels];
  410. int prediction_quantitization[channels];
  411. int ricemodifier[channels];
  412. int i, chan;
  413. interlacing_shift = get_bits(&alac->gb, 8);
  414. interlacing_leftweight = get_bits(&alac->gb, 8);
  415. for (chan = 0; chan < channels; chan++) {
  416. prediction_type[chan] = get_bits(&alac->gb, 4);
  417. prediction_quantitization[chan] = get_bits(&alac->gb, 4);
  418. ricemodifier[chan] = get_bits(&alac->gb, 3);
  419. predictor_coef_num[chan] = get_bits(&alac->gb, 5);
  420. /* read the predictor table */
  421. for (i = 0; i < predictor_coef_num[chan]; i++)
  422. predictor_coef_table[chan][i] = (int16_t)get_bits(&alac->gb, 16);
  423. }
  424. if (wasted_bytes)
  425. av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
  426. for (chan = 0; chan < channels; chan++) {
  427. bastardized_rice_decompress(alac,
  428. alac->predicterror_buffer[chan],
  429. outputsamples,
  430. readsamplesize,
  431. alac->setinfo_rice_initialhistory,
  432. alac->setinfo_rice_kmodifier,
  433. ricemodifier[chan] * alac->setinfo_rice_historymult / 4,
  434. (1 << alac->setinfo_rice_kmodifier) - 1);
  435. if (prediction_type[chan] == 0) {
  436. /* adaptive fir */
  437. predictor_decompress_fir_adapt(alac->predicterror_buffer[chan],
  438. alac->outputsamples_buffer[chan],
  439. outputsamples,
  440. readsamplesize,
  441. predictor_coef_table[chan],
  442. predictor_coef_num[chan],
  443. prediction_quantitization[chan]);
  444. } else {
  445. av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[chan]);
  446. /* I think the only other prediction type (or perhaps this is
  447. * just a boolean?) runs adaptive fir twice.. like:
  448. * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
  449. * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
  450. * little strange..
  451. */
  452. }
  453. }
  454. } else {
  455. /* not compressed, easy case */
  456. if (alac->setinfo_sample_size <= 16) {
  457. int i, chan;
  458. for (chan = 0; chan < channels; chan++)
  459. for (i = 0; i < outputsamples; i++) {
  460. int32_t audiobits;
  461. audiobits = get_bits(&alac->gb, alac->setinfo_sample_size);
  462. audiobits = extend_sign32(audiobits, readsamplesize);
  463. alac->outputsamples_buffer[chan][i] = audiobits;
  464. }
  465. } else {
  466. int i, chan;
  467. for (chan = 0; chan < channels; chan++)
  468. for (i = 0; i < outputsamples; i++) {
  469. int32_t audiobits;
  470. audiobits = get_bits(&alac->gb, 16);
  471. /* special case of sign extension..
  472. * as we'll be ORing the low 16bits into this */
  473. audiobits = audiobits << 16;
  474. audiobits = audiobits >> (32 - alac->setinfo_sample_size);
  475. audiobits |= get_bits(&alac->gb, alac->setinfo_sample_size - 16);
  476. alac->outputsamples_buffer[chan][i] = audiobits;
  477. }
  478. }
  479. /* wasted_bytes = 0; */
  480. interlacing_shift = 0;
  481. interlacing_leftweight = 0;
  482. }
  483. switch(alac->setinfo_sample_size) {
  484. case 16:
  485. if (channels == 2) {
  486. reconstruct_stereo_16(alac->outputsamples_buffer,
  487. (int16_t*)outbuffer,
  488. alac->numchannels,
  489. outputsamples,
  490. interlacing_shift,
  491. interlacing_leftweight);
  492. } else {
  493. int i;
  494. for (i = 0; i < outputsamples; i++) {
  495. int16_t sample = alac->outputsamples_buffer[0][i];
  496. ((int16_t*)outbuffer)[i * alac->numchannels] = sample;
  497. }
  498. }
  499. break;
  500. case 20:
  501. case 24:
  502. // It is not clear if there exist any encoder that creates 24 bit ALAC
  503. // files. iTunes convert 24 bit raw files to 16 bit before encoding.
  504. case 32:
  505. av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
  506. break;
  507. default:
  508. break;
  509. }
  510. return input_buffer_size;
  511. }
  512. static av_cold int alac_decode_init(AVCodecContext * avctx)
  513. {
  514. ALACContext *alac = avctx->priv_data;
  515. alac->avctx = avctx;
  516. alac->context_initialized = 0;
  517. alac->samplesize = alac->avctx->bits_per_sample;
  518. alac->numchannels = alac->avctx->channels;
  519. alac->bytespersample = (alac->samplesize / 8) * alac->numchannels;
  520. return 0;
  521. }
  522. static av_cold int alac_decode_close(AVCodecContext *avctx)
  523. {
  524. ALACContext *alac = avctx->priv_data;
  525. int chan;
  526. for (chan = 0; chan < MAX_CHANNELS; chan++) {
  527. av_free(alac->predicterror_buffer[chan]);
  528. av_free(alac->outputsamples_buffer[chan]);
  529. }
  530. return 0;
  531. }
  532. AVCodec alac_decoder = {
  533. "alac",
  534. CODEC_TYPE_AUDIO,
  535. CODEC_ID_ALAC,
  536. sizeof(ALACContext),
  537. alac_decode_init,
  538. NULL,
  539. alac_decode_close,
  540. alac_decode_frame,
  541. };