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.

636 lines
20KB

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