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.

668 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. get_bits(&alac->gb, k);
  172. } else
  173. get_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. get_bits(&alac->gb, k - 1);
  208. } else {
  209. get_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 deinterlace_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 difference, midright;
  337. int16_t left;
  338. int16_t right;
  339. midright = buffer[0][i];
  340. difference = buffer[1][i];
  341. right = midright - ((difference * interlacing_leftweight) >> interlacing_shift);
  342. left = right + difference;
  343. buffer_out[i*numchannels] = left;
  344. buffer_out[i*numchannels + 1] = right;
  345. }
  346. return;
  347. }
  348. /* otherwise basic interlacing took place */
  349. for (i = 0; i < numsamples; i++) {
  350. int16_t left, right;
  351. left = buffer[0][i];
  352. right = buffer[1][i];
  353. buffer_out[i*numchannels] = left;
  354. buffer_out[i*numchannels + 1] = right;
  355. }
  356. }
  357. static int alac_decode_frame(AVCodecContext *avctx,
  358. void *outbuffer, int *outputsize,
  359. uint8_t *inbuffer, int input_buffer_size)
  360. {
  361. ALACContext *alac = avctx->priv_data;
  362. int channels;
  363. int32_t outputsamples;
  364. int hassize;
  365. int readsamplesize;
  366. int wasted_bytes;
  367. int isnotcompressed;
  368. uint8_t interlacing_shift;
  369. uint8_t interlacing_leftweight;
  370. /* short-circuit null buffers */
  371. if (!inbuffer || !input_buffer_size)
  372. return input_buffer_size;
  373. /* initialize from the extradata */
  374. if (!alac->context_initialized) {
  375. if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
  376. av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
  377. ALAC_EXTRADATA_SIZE);
  378. return input_buffer_size;
  379. }
  380. if (alac_set_info(alac)) {
  381. av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
  382. return input_buffer_size;
  383. }
  384. alac->context_initialized = 1;
  385. }
  386. init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
  387. channels = get_bits(&alac->gb, 3) + 1;
  388. if (channels > MAX_CHANNELS) {
  389. av_log(avctx, AV_LOG_ERROR, "channels > %d not supported\n",
  390. MAX_CHANNELS);
  391. return input_buffer_size;
  392. }
  393. /* 2^result = something to do with output waiting.
  394. * perhaps matters if we read > 1 frame in a pass?
  395. */
  396. get_bits(&alac->gb, 4);
  397. get_bits(&alac->gb, 12); /* unknown, skip 12 bits */
  398. /* the output sample size is stored soon */
  399. hassize = get_bits(&alac->gb, 1);
  400. wasted_bytes = get_bits(&alac->gb, 2); /* unknown ? */
  401. /* whether the frame is compressed */
  402. isnotcompressed = get_bits(&alac->gb, 1);
  403. if (hassize) {
  404. /* now read the number of samples as a 32bit integer */
  405. outputsamples = get_bits(&alac->gb, 32);
  406. } else
  407. outputsamples = alac->setinfo_max_samples_per_frame;
  408. *outputsize = outputsamples * alac->bytespersample;
  409. readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8) + channels - 1;
  410. if (!isnotcompressed) {
  411. /* so it is compressed */
  412. int16_t predictor_coef_table[channels][32];
  413. int predictor_coef_num[channels];
  414. int prediction_type[channels];
  415. int prediction_quantitization[channels];
  416. int ricemodifier[channels];
  417. int i, chan;
  418. interlacing_shift = get_bits(&alac->gb, 8);
  419. interlacing_leftweight = get_bits(&alac->gb, 8);
  420. for (chan = 0; chan < channels; chan++) {
  421. prediction_type[chan] = get_bits(&alac->gb, 4);
  422. prediction_quantitization[chan] = get_bits(&alac->gb, 4);
  423. ricemodifier[chan] = get_bits(&alac->gb, 3);
  424. predictor_coef_num[chan] = get_bits(&alac->gb, 5);
  425. /* read the predictor table */
  426. for (i = 0; i < predictor_coef_num[chan]; i++)
  427. predictor_coef_table[chan][i] = (int16_t)get_bits(&alac->gb, 16);
  428. }
  429. if (wasted_bytes) {
  430. av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
  431. }
  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 = SIGN_EXTENDED32(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. deinterlace_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. }
  507. case 20:
  508. case 24:
  509. case 32:
  510. av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
  511. break;
  512. default:
  513. break;
  514. }
  515. return input_buffer_size;
  516. }
  517. static int alac_decode_init(AVCodecContext * avctx)
  518. {
  519. ALACContext *alac = avctx->priv_data;
  520. alac->avctx = avctx;
  521. alac->context_initialized = 0;
  522. alac->samplesize = alac->avctx->bits_per_sample;
  523. alac->numchannels = alac->avctx->channels;
  524. alac->bytespersample = (alac->samplesize / 8) * alac->numchannels;
  525. return 0;
  526. }
  527. static int alac_decode_close(AVCodecContext *avctx)
  528. {
  529. ALACContext *alac = avctx->priv_data;
  530. int chan;
  531. for (chan = 0; chan < MAX_CHANNELS; chan++) {
  532. av_free(alac->predicterror_buffer[chan]);
  533. av_free(alac->outputsamples_buffer[chan]);
  534. }
  535. return 0;
  536. }
  537. AVCodec alac_decoder = {
  538. "alac",
  539. CODEC_TYPE_AUDIO,
  540. CODEC_ID_ALAC,
  541. sizeof(ALACContext),
  542. alac_decode_init,
  543. NULL,
  544. alac_decode_close,
  545. alac_decode_frame,
  546. };