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.

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