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