alac.c 20 KB

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