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.

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