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.

627 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 "get_bits.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. AVPacket *avpkt)
  327. {
  328. const uint8_t *inbuffer = avpkt->data;
  329. int input_buffer_size = avpkt->size;
  330. ALACContext *alac = avctx->priv_data;
  331. int channels;
  332. unsigned int outputsamples;
  333. int hassize;
  334. unsigned int readsamplesize;
  335. int wasted_bytes;
  336. int isnotcompressed;
  337. uint8_t interlacing_shift;
  338. uint8_t interlacing_leftweight;
  339. /* short-circuit null buffers */
  340. if (!inbuffer || !input_buffer_size)
  341. return input_buffer_size;
  342. /* initialize from the extradata */
  343. if (!alac->context_initialized) {
  344. if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
  345. av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
  346. ALAC_EXTRADATA_SIZE);
  347. return input_buffer_size;
  348. }
  349. if (alac_set_info(alac)) {
  350. av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
  351. return input_buffer_size;
  352. }
  353. alac->context_initialized = 1;
  354. }
  355. init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
  356. channels = get_bits(&alac->gb, 3) + 1;
  357. if (channels > MAX_CHANNELS) {
  358. av_log(avctx, AV_LOG_ERROR, "channels > %d not supported\n",
  359. MAX_CHANNELS);
  360. return input_buffer_size;
  361. }
  362. /* 2^result = something to do with output waiting.
  363. * perhaps matters if we read > 1 frame in a pass?
  364. */
  365. skip_bits(&alac->gb, 4);
  366. skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
  367. /* the output sample size is stored soon */
  368. hassize = get_bits1(&alac->gb);
  369. wasted_bytes = get_bits(&alac->gb, 2); /* unknown ? */
  370. /* whether the frame is compressed */
  371. isnotcompressed = get_bits1(&alac->gb);
  372. if (hassize) {
  373. /* now read the number of samples as a 32bit integer */
  374. outputsamples = get_bits_long(&alac->gb, 32);
  375. if(outputsamples > alac->setinfo_max_samples_per_frame){
  376. av_log(avctx, AV_LOG_ERROR, "outputsamples %d > %d\n", outputsamples, alac->setinfo_max_samples_per_frame);
  377. return -1;
  378. }
  379. } else
  380. outputsamples = alac->setinfo_max_samples_per_frame;
  381. if(outputsamples > *outputsize / alac->bytespersample){
  382. av_log(avctx, AV_LOG_ERROR, "sample buffer too small\n");
  383. return -1;
  384. }
  385. *outputsize = outputsamples * alac->bytespersample;
  386. readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8) + channels - 1;
  387. if (readsamplesize > MIN_CACHE_BITS) {
  388. av_log(avctx, AV_LOG_ERROR, "readsamplesize too big (%d)\n", readsamplesize);
  389. return -1;
  390. }
  391. if (!isnotcompressed) {
  392. /* so it is compressed */
  393. int16_t predictor_coef_table[channels][32];
  394. int predictor_coef_num[channels];
  395. int prediction_type[channels];
  396. int prediction_quantitization[channels];
  397. int ricemodifier[channels];
  398. int i, chan;
  399. interlacing_shift = get_bits(&alac->gb, 8);
  400. interlacing_leftweight = get_bits(&alac->gb, 8);
  401. for (chan = 0; chan < channels; chan++) {
  402. prediction_type[chan] = get_bits(&alac->gb, 4);
  403. prediction_quantitization[chan] = get_bits(&alac->gb, 4);
  404. ricemodifier[chan] = get_bits(&alac->gb, 3);
  405. predictor_coef_num[chan] = get_bits(&alac->gb, 5);
  406. /* read the predictor table */
  407. for (i = 0; i < predictor_coef_num[chan]; i++)
  408. predictor_coef_table[chan][i] = (int16_t)get_bits(&alac->gb, 16);
  409. }
  410. if (wasted_bytes)
  411. av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
  412. for (chan = 0; chan < channels; chan++) {
  413. bastardized_rice_decompress(alac,
  414. alac->predicterror_buffer[chan],
  415. outputsamples,
  416. readsamplesize,
  417. alac->setinfo_rice_initialhistory,
  418. alac->setinfo_rice_kmodifier,
  419. ricemodifier[chan] * alac->setinfo_rice_historymult / 4,
  420. (1 << alac->setinfo_rice_kmodifier) - 1);
  421. if (prediction_type[chan] == 0) {
  422. /* adaptive fir */
  423. predictor_decompress_fir_adapt(alac->predicterror_buffer[chan],
  424. alac->outputsamples_buffer[chan],
  425. outputsamples,
  426. readsamplesize,
  427. predictor_coef_table[chan],
  428. predictor_coef_num[chan],
  429. prediction_quantitization[chan]);
  430. } else {
  431. av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[chan]);
  432. /* I think the only other prediction type (or perhaps this is
  433. * just a boolean?) runs adaptive fir twice.. like:
  434. * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
  435. * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
  436. * little strange..
  437. */
  438. }
  439. }
  440. } else {
  441. /* not compressed, easy case */
  442. int i, chan;
  443. for (i = 0; i < outputsamples; i++)
  444. for (chan = 0; chan < channels; chan++) {
  445. int32_t audiobits;
  446. audiobits = get_sbits_long(&alac->gb, alac->setinfo_sample_size);
  447. alac->outputsamples_buffer[chan][i] = audiobits;
  448. }
  449. /* wasted_bytes = 0; */
  450. interlacing_shift = 0;
  451. interlacing_leftweight = 0;
  452. }
  453. if (get_bits(&alac->gb, 3) != 7)
  454. av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
  455. switch(alac->setinfo_sample_size) {
  456. case 16:
  457. if (channels == 2) {
  458. reconstruct_stereo_16(alac->outputsamples_buffer,
  459. (int16_t*)outbuffer,
  460. alac->numchannels,
  461. outputsamples,
  462. interlacing_shift,
  463. interlacing_leftweight);
  464. } else {
  465. int i;
  466. for (i = 0; i < outputsamples; i++) {
  467. int16_t sample = alac->outputsamples_buffer[0][i];
  468. ((int16_t*)outbuffer)[i * alac->numchannels] = sample;
  469. }
  470. }
  471. break;
  472. case 20:
  473. case 24:
  474. // It is not clear if there exist any encoder that creates 24 bit ALAC
  475. // files. iTunes convert 24 bit raw files to 16 bit before encoding.
  476. case 32:
  477. av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
  478. break;
  479. default:
  480. break;
  481. }
  482. if (input_buffer_size * 8 - get_bits_count(&alac->gb) > 8)
  483. av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n", input_buffer_size * 8 - get_bits_count(&alac->gb));
  484. return input_buffer_size;
  485. }
  486. static av_cold int alac_decode_init(AVCodecContext * avctx)
  487. {
  488. ALACContext *alac = avctx->priv_data;
  489. alac->avctx = avctx;
  490. alac->context_initialized = 0;
  491. alac->numchannels = alac->avctx->channels;
  492. alac->bytespersample = 2 * alac->numchannels;
  493. avctx->sample_fmt = SAMPLE_FMT_S16;
  494. return 0;
  495. }
  496. static av_cold int alac_decode_close(AVCodecContext *avctx)
  497. {
  498. ALACContext *alac = avctx->priv_data;
  499. int chan;
  500. for (chan = 0; chan < MAX_CHANNELS; chan++) {
  501. av_free(alac->predicterror_buffer[chan]);
  502. av_free(alac->outputsamples_buffer[chan]);
  503. }
  504. return 0;
  505. }
  506. AVCodec alac_decoder = {
  507. "alac",
  508. CODEC_TYPE_AUDIO,
  509. CODEC_ID_ALAC,
  510. sizeof(ALACContext),
  511. alac_decode_init,
  512. NULL,
  513. alac_decode_close,
  514. alac_decode_frame,
  515. .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
  516. };