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.

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