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.

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