alac.c

Go to the documentation of this file.
00001 /*
00002  * ALAC (Apple Lossless Audio Codec) decoder
00003  * Copyright (c) 2005 David Hammerton
00004  *
00005  * This file is part of FFmpeg.
00006  *
00007  * FFmpeg is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU Lesser General Public
00009  * License as published by the Free Software Foundation; either
00010  * version 2.1 of the License, or (at your option) any later version.
00011  *
00012  * FFmpeg is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00015  * Lesser General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU Lesser General Public
00018  * License along with FFmpeg; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00020  */
00021 
00022 /**
00023  * @file alac.c
00024  * ALAC (Apple Lossless Audio Codec) decoder
00025  * @author 2005 David Hammerton
00026  *
00027  * For more information on the ALAC format, visit:
00028  *  http://crazney.net/programs/itunes/alac.html
00029  *
00030  * Note: This decoder expects a 36- (0x24-)byte QuickTime atom to be
00031  * passed through the extradata[_size] fields. This atom is tacked onto
00032  * the end of an 'alac' stsd atom and has the following format:
00033  *  bytes 0-3   atom size (0x24), big-endian
00034  *  bytes 4-7   atom type ('alac', not the 'alac' tag from start of stsd)
00035  *  bytes 8-35  data bytes needed by decoder
00036  *
00037  * Extradata:
00038  * 32bit  size
00039  * 32bit  tag (=alac)
00040  * 32bit  zero?
00041  * 32bit  max sample per frame
00042  *  8bit  ?? (zero?)
00043  *  8bit  sample size
00044  *  8bit  history mult
00045  *  8bit  initial history
00046  *  8bit  kmodifier
00047  *  8bit  channels?
00048  * 16bit  ??
00049  * 32bit  max coded frame size
00050  * 32bit  bitrate?
00051  * 32bit  samplerate
00052  */
00053 
00054 
00055 #include "avcodec.h"
00056 #include "bitstream.h"
00057 #include "bytestream.h"
00058 #include "unary.h"
00059 
00060 #define ALAC_EXTRADATA_SIZE 36
00061 #define MAX_CHANNELS 2
00062 
00063 typedef struct {
00064 
00065     AVCodecContext *avctx;
00066     GetBitContext gb;
00067     /* init to 0; first frame decode should initialize from extradata and
00068      * set this to 1 */
00069     int context_initialized;
00070 
00071     int numchannels;
00072     int bytespersample;
00073 
00074     /* buffers */
00075     int32_t *predicterror_buffer[MAX_CHANNELS];
00076 
00077     int32_t *outputsamples_buffer[MAX_CHANNELS];
00078 
00079     /* stuff from setinfo */
00080     uint32_t setinfo_max_samples_per_frame; /* 0x1000 = 4096 */    /* max samples per frame? */
00081     uint8_t setinfo_sample_size; /* 0x10 */
00082     uint8_t setinfo_rice_historymult; /* 0x28 */
00083     uint8_t setinfo_rice_initialhistory; /* 0x0a */
00084     uint8_t setinfo_rice_kmodifier; /* 0x0e */
00085     /* end setinfo stuff */
00086 
00087 } ALACContext;
00088 
00089 static void allocate_buffers(ALACContext *alac)
00090 {
00091     int chan;
00092     for (chan = 0; chan < MAX_CHANNELS; chan++) {
00093         alac->predicterror_buffer[chan] =
00094             av_malloc(alac->setinfo_max_samples_per_frame * 4);
00095 
00096         alac->outputsamples_buffer[chan] =
00097             av_malloc(alac->setinfo_max_samples_per_frame * 4);
00098     }
00099 }
00100 
00101 static int alac_set_info(ALACContext *alac)
00102 {
00103     const unsigned char *ptr = alac->avctx->extradata;
00104 
00105     ptr += 4; /* size */
00106     ptr += 4; /* alac */
00107     ptr += 4; /* 0 ? */
00108 
00109     if(AV_RB32(ptr) >= UINT_MAX/4){
00110         av_log(alac->avctx, AV_LOG_ERROR, "setinfo_max_samples_per_frame too large\n");
00111         return -1;
00112     }
00113 
00114     /* buffer size / 2 ? */
00115     alac->setinfo_max_samples_per_frame = bytestream_get_be32(&ptr);
00116     ptr++;                          /* ??? */
00117     alac->setinfo_sample_size           = *ptr++;
00118     if (alac->setinfo_sample_size > 32) {
00119         av_log(alac->avctx, AV_LOG_ERROR, "setinfo_sample_size too large\n");
00120         return -1;
00121     }
00122     alac->setinfo_rice_historymult      = *ptr++;
00123     alac->setinfo_rice_initialhistory   = *ptr++;
00124     alac->setinfo_rice_kmodifier        = *ptr++;
00125     ptr++;                         /* channels? */
00126     bytestream_get_be16(&ptr);      /* ??? */
00127     bytestream_get_be32(&ptr);      /* max coded frame size */
00128     bytestream_get_be32(&ptr);      /* bitrate ? */
00129     bytestream_get_be32(&ptr);      /* samplerate */
00130 
00131     allocate_buffers(alac);
00132 
00133     return 0;
00134 }
00135 
00136 static inline int decode_scalar(GetBitContext *gb, int k, int limit, int readsamplesize){
00137     /* read x - number of 1s before 0 represent the rice */
00138     int x = get_unary_0_9(gb);
00139 
00140     if (x > 8) { /* RICE THRESHOLD */
00141         /* use alternative encoding */
00142         x = get_bits(gb, readsamplesize);
00143     } else {
00144         if (k >= limit)
00145             k = limit;
00146 
00147         if (k != 1) {
00148             int extrabits = show_bits(gb, k);
00149 
00150             /* multiply x by 2^k - 1, as part of their strange algorithm */
00151             x = (x << k) - x;
00152 
00153             if (extrabits > 1) {
00154                 x += extrabits - 1;
00155                 skip_bits(gb, k);
00156             } else
00157                 skip_bits(gb, k - 1);
00158         }
00159     }
00160     return x;
00161 }
00162 
00163 static void bastardized_rice_decompress(ALACContext *alac,
00164                                  int32_t *output_buffer,
00165                                  int output_size,
00166                                  int readsamplesize, /* arg_10 */
00167                                  int rice_initialhistory, /* arg424->b */
00168                                  int rice_kmodifier, /* arg424->d */
00169                                  int rice_historymult, /* arg424->c */
00170                                  int rice_kmodifier_mask /* arg424->e */
00171         )
00172 {
00173     int output_count;
00174     unsigned int history = rice_initialhistory;
00175     int sign_modifier = 0;
00176 
00177     for (output_count = 0; output_count < output_size; output_count++) {
00178         int32_t x;
00179         int32_t x_modified;
00180         int32_t final_val;
00181 
00182         /* standard rice encoding */
00183         int k; /* size of extra bits */
00184 
00185         /* read k, that is bits as is */
00186         k = av_log2((history >> 9) + 3);
00187         x= decode_scalar(&alac->gb, k, rice_kmodifier, readsamplesize);
00188 
00189         x_modified = sign_modifier + x;
00190         final_val = (x_modified + 1) / 2;
00191         if (x_modified & 1) final_val *= -1;
00192 
00193         output_buffer[output_count] = final_val;
00194 
00195         sign_modifier = 0;
00196 
00197         /* now update the history */
00198         history += x_modified * rice_historymult
00199                    - ((history * rice_historymult) >> 9);
00200 
00201         if (x_modified > 0xffff)
00202             history = 0xffff;
00203 
00204         /* special case: there may be compressed blocks of 0 */
00205         if ((history < 128) && (output_count+1 < output_size)) {
00206             int k;
00207             unsigned int block_size;
00208 
00209             sign_modifier = 1;
00210 
00211             k = 7 - av_log2(history) + ((history + 16) >> 6 /* / 64 */);
00212 
00213             block_size= decode_scalar(&alac->gb, k, rice_kmodifier, 16);
00214 
00215             if (block_size > 0) {
00216                 if(block_size >= output_size - output_count){
00217                     av_log(alac->avctx, AV_LOG_ERROR, "invalid zero block size of %d %d %d\n", block_size, output_size, output_count);
00218                     block_size= output_size - output_count - 1;
00219                 }
00220                 memset(&output_buffer[output_count+1], 0, block_size * 4);
00221                 output_count += block_size;
00222             }
00223 
00224             if (block_size > 0xffff)
00225                 sign_modifier = 0;
00226 
00227             history = 0;
00228         }
00229     }
00230 }
00231 
00232 static inline int32_t extend_sign32(int32_t val, int bits)
00233 {
00234     return (val << (32 - bits)) >> (32 - bits);
00235 }
00236 
00237 static inline int sign_only(int v)
00238 {
00239     return v ? FFSIGN(v) : 0;
00240 }
00241 
00242 static void predictor_decompress_fir_adapt(int32_t *error_buffer,
00243                                            int32_t *buffer_out,
00244                                            int output_size,
00245                                            int readsamplesize,
00246                                            int16_t *predictor_coef_table,
00247                                            int predictor_coef_num,
00248                                            int predictor_quantitization)
00249 {
00250     int i;
00251 
00252     /* first sample always copies */
00253     *buffer_out = *error_buffer;
00254 
00255     if (!predictor_coef_num) {
00256         if (output_size <= 1)
00257             return;
00258 
00259         memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
00260         return;
00261     }
00262 
00263     if (predictor_coef_num == 0x1f) { /* 11111 - max value of predictor_coef_num */
00264       /* second-best case scenario for fir decompression,
00265        * error describes a small difference from the previous sample only
00266        */
00267         if (output_size <= 1)
00268             return;
00269         for (i = 0; i < output_size - 1; i++) {
00270             int32_t prev_value;
00271             int32_t error_value;
00272 
00273             prev_value = buffer_out[i];
00274             error_value = error_buffer[i+1];
00275             buffer_out[i+1] =
00276                 extend_sign32((prev_value + error_value), readsamplesize);
00277         }
00278         return;
00279     }
00280 
00281     /* read warm-up samples */
00282     if (predictor_coef_num > 0)
00283         for (i = 0; i < predictor_coef_num; i++) {
00284             int32_t val;
00285 
00286             val = buffer_out[i] + error_buffer[i+1];
00287             val = extend_sign32(val, readsamplesize);
00288             buffer_out[i+1] = val;
00289         }
00290 
00291 #if 0
00292     /* 4 and 8 are very common cases (the only ones i've seen). these
00293      * should be unrolled and optimized
00294      */
00295     if (predictor_coef_num == 4) {
00296         /* FIXME: optimized general case */
00297         return;
00298     }
00299 
00300     if (predictor_coef_table == 8) {
00301         /* FIXME: optimized general case */
00302         return;
00303     }
00304 #endif
00305 
00306     /* general case */
00307     if (predictor_coef_num > 0) {
00308         for (i = predictor_coef_num + 1; i < output_size; i++) {
00309             int j;
00310             int sum = 0;
00311             int outval;
00312             int error_val = error_buffer[i];
00313 
00314             for (j = 0; j < predictor_coef_num; j++) {
00315                 sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
00316                        predictor_coef_table[j];
00317             }
00318 
00319             outval = (1 << (predictor_quantitization-1)) + sum;
00320             outval = outval >> predictor_quantitization;
00321             outval = outval + buffer_out[0] + error_val;
00322             outval = extend_sign32(outval, readsamplesize);
00323 
00324             buffer_out[predictor_coef_num+1] = outval;
00325 
00326             if (error_val > 0) {
00327                 int predictor_num = predictor_coef_num - 1;
00328 
00329                 while (predictor_num >= 0 && error_val > 0) {
00330                     int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
00331                     int sign = sign_only(val);
00332 
00333                     predictor_coef_table[predictor_num] -= sign;
00334 
00335                     val *= sign; /* absolute value */
00336 
00337                     error_val -= ((val >> predictor_quantitization) *
00338                                   (predictor_coef_num - predictor_num));
00339 
00340                     predictor_num--;
00341                 }
00342             } else if (error_val < 0) {
00343                 int predictor_num = predictor_coef_num - 1;
00344 
00345                 while (predictor_num >= 0 && error_val < 0) {
00346                     int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
00347                     int sign = - sign_only(val);
00348 
00349                     predictor_coef_table[predictor_num] -= sign;
00350 
00351                     val *= sign; /* neg value */
00352 
00353                     error_val -= ((val >> predictor_quantitization) *
00354                                   (predictor_coef_num - predictor_num));
00355 
00356                     predictor_num--;
00357                 }
00358             }
00359 
00360             buffer_out++;
00361         }
00362     }
00363 }
00364 
00365 static void reconstruct_stereo_16(int32_t *buffer[MAX_CHANNELS],
00366                                   int16_t *buffer_out,
00367                                   int numchannels, int numsamples,
00368                                   uint8_t interlacing_shift,
00369                                   uint8_t interlacing_leftweight)
00370 {
00371     int i;
00372     if (numsamples <= 0)
00373         return;
00374 
00375     /* weighted interlacing */
00376     if (interlacing_leftweight) {
00377         for (i = 0; i < numsamples; i++) {
00378             int32_t a, b;
00379 
00380             a = buffer[0][i];
00381             b = buffer[1][i];
00382 
00383             a -= (b * interlacing_leftweight) >> interlacing_shift;
00384             b += a;
00385 
00386             buffer_out[i*numchannels] = b;
00387             buffer_out[i*numchannels + 1] = a;
00388         }
00389 
00390         return;
00391     }
00392 
00393     /* otherwise basic interlacing took place */
00394     for (i = 0; i < numsamples; i++) {
00395         int16_t left, right;
00396 
00397         left = buffer[0][i];
00398         right = buffer[1][i];
00399 
00400         buffer_out[i*numchannels] = left;
00401         buffer_out[i*numchannels + 1] = right;
00402     }
00403 }
00404 
00405 static int alac_decode_frame(AVCodecContext *avctx,
00406                              void *outbuffer, int *outputsize,
00407                              const uint8_t *inbuffer, int input_buffer_size)
00408 {
00409     ALACContext *alac = avctx->priv_data;
00410 
00411     int channels;
00412     unsigned int outputsamples;
00413     int hassize;
00414     int readsamplesize;
00415     int wasted_bytes;
00416     int isnotcompressed;
00417     uint8_t interlacing_shift;
00418     uint8_t interlacing_leftweight;
00419 
00420     /* short-circuit null buffers */
00421     if (!inbuffer || !input_buffer_size)
00422         return input_buffer_size;
00423 
00424     /* initialize from the extradata */
00425     if (!alac->context_initialized) {
00426         if (alac->avctx->extradata_size != ALAC_EXTRADATA_SIZE) {
00427             av_log(avctx, AV_LOG_ERROR, "alac: expected %d extradata bytes\n",
00428                 ALAC_EXTRADATA_SIZE);
00429             return input_buffer_size;
00430         }
00431         if (alac_set_info(alac)) {
00432             av_log(avctx, AV_LOG_ERROR, "alac: set_info failed\n");
00433             return input_buffer_size;
00434         }
00435         alac->context_initialized = 1;
00436     }
00437 
00438     init_get_bits(&alac->gb, inbuffer, input_buffer_size * 8);
00439 
00440     channels = get_bits(&alac->gb, 3) + 1;
00441     if (channels > MAX_CHANNELS) {
00442         av_log(avctx, AV_LOG_ERROR, "channels > %d not supported\n",
00443                MAX_CHANNELS);
00444         return input_buffer_size;
00445     }
00446 
00447     /* 2^result = something to do with output waiting.
00448      * perhaps matters if we read > 1 frame in a pass?
00449      */
00450     skip_bits(&alac->gb, 4);
00451 
00452     skip_bits(&alac->gb, 12); /* unknown, skip 12 bits */
00453 
00454     /* the output sample size is stored soon */
00455     hassize = get_bits1(&alac->gb);
00456 
00457     wasted_bytes = get_bits(&alac->gb, 2); /* unknown ? */
00458 
00459     /* whether the frame is compressed */
00460     isnotcompressed = get_bits1(&alac->gb);
00461 
00462     if (hassize) {
00463         /* now read the number of samples as a 32bit integer */
00464         outputsamples = get_bits_long(&alac->gb, 32);
00465         if(outputsamples > alac->setinfo_max_samples_per_frame){
00466             av_log(avctx, AV_LOG_ERROR, "outputsamples %d > %d\n", outputsamples, alac->setinfo_max_samples_per_frame);
00467             return -1;
00468         }
00469     } else
00470         outputsamples = alac->setinfo_max_samples_per_frame;
00471 
00472     if(outputsamples > *outputsize / alac->bytespersample){
00473         av_log(avctx, AV_LOG_ERROR, "sample buffer too small\n");
00474         return -1;
00475     }
00476 
00477     *outputsize = outputsamples * alac->bytespersample;
00478     readsamplesize = alac->setinfo_sample_size - (wasted_bytes * 8) + channels - 1;
00479 
00480     if (!isnotcompressed) {
00481         /* so it is compressed */
00482         int16_t predictor_coef_table[channels][32];
00483         int predictor_coef_num[channels];
00484         int prediction_type[channels];
00485         int prediction_quantitization[channels];
00486         int ricemodifier[channels];
00487         int i, chan;
00488 
00489         interlacing_shift = get_bits(&alac->gb, 8);
00490         interlacing_leftweight = get_bits(&alac->gb, 8);
00491 
00492         for (chan = 0; chan < channels; chan++) {
00493             prediction_type[chan] = get_bits(&alac->gb, 4);
00494             prediction_quantitization[chan] = get_bits(&alac->gb, 4);
00495 
00496             ricemodifier[chan] = get_bits(&alac->gb, 3);
00497             predictor_coef_num[chan] = get_bits(&alac->gb, 5);
00498 
00499             /* read the predictor table */
00500             for (i = 0; i < predictor_coef_num[chan]; i++)
00501                 predictor_coef_table[chan][i] = (int16_t)get_bits(&alac->gb, 16);
00502         }
00503 
00504         if (wasted_bytes)
00505             av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented, unhandling of wasted_bytes\n");
00506 
00507         for (chan = 0; chan < channels; chan++) {
00508             bastardized_rice_decompress(alac,
00509                                         alac->predicterror_buffer[chan],
00510                                         outputsamples,
00511                                         readsamplesize,
00512                                         alac->setinfo_rice_initialhistory,
00513                                         alac->setinfo_rice_kmodifier,
00514                                         ricemodifier[chan] * alac->setinfo_rice_historymult / 4,
00515                                         (1 << alac->setinfo_rice_kmodifier) - 1);
00516 
00517             if (prediction_type[chan] == 0) {
00518                 /* adaptive fir */
00519                 predictor_decompress_fir_adapt(alac->predicterror_buffer[chan],
00520                                                alac->outputsamples_buffer[chan],
00521                                                outputsamples,
00522                                                readsamplesize,
00523                                                predictor_coef_table[chan],
00524                                                predictor_coef_num[chan],
00525                                                prediction_quantitization[chan]);
00526             } else {
00527                 av_log(avctx, AV_LOG_ERROR, "FIXME: unhandled prediction type: %i\n", prediction_type[chan]);
00528                 /* I think the only other prediction type (or perhaps this is
00529                  * just a boolean?) runs adaptive fir twice.. like:
00530                  * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
00531                  * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
00532                  * little strange..
00533                  */
00534             }
00535         }
00536     } else {
00537         /* not compressed, easy case */
00538         int i, chan;
00539         for (i = 0; i < outputsamples; i++)
00540             for (chan = 0; chan < channels; chan++) {
00541                 int32_t audiobits;
00542 
00543                 audiobits = get_bits_long(&alac->gb, alac->setinfo_sample_size);
00544                 audiobits = extend_sign32(audiobits, alac->setinfo_sample_size);
00545 
00546                 alac->outputsamples_buffer[chan][i] = audiobits;
00547             }
00548         /* wasted_bytes = 0; */
00549         interlacing_shift = 0;
00550         interlacing_leftweight = 0;
00551     }
00552     if (get_bits(&alac->gb, 3) != 7)
00553         av_log(avctx, AV_LOG_ERROR, "Error : Wrong End Of Frame\n");
00554 
00555     switch(alac->setinfo_sample_size) {
00556     case 16:
00557         if (channels == 2) {
00558             reconstruct_stereo_16(alac->outputsamples_buffer,
00559                                   (int16_t*)outbuffer,
00560                                   alac->numchannels,
00561                                   outputsamples,
00562                                   interlacing_shift,
00563                                   interlacing_leftweight);
00564         } else {
00565             int i;
00566             for (i = 0; i < outputsamples; i++) {
00567                 int16_t sample = alac->outputsamples_buffer[0][i];
00568                 ((int16_t*)outbuffer)[i * alac->numchannels] = sample;
00569             }
00570         }
00571         break;
00572     case 20:
00573     case 24:
00574         // It is not clear if there exist any encoder that creates 24 bit ALAC
00575         // files. iTunes convert 24 bit raw files to 16 bit before encoding.
00576     case 32:
00577         av_log(avctx, AV_LOG_ERROR, "FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
00578         break;
00579     default:
00580         break;
00581     }
00582 
00583     if (input_buffer_size * 8 - get_bits_count(&alac->gb) > 8)
00584         av_log(avctx, AV_LOG_ERROR, "Error : %d bits left\n", input_buffer_size * 8 - get_bits_count(&alac->gb));
00585 
00586     return input_buffer_size;
00587 }
00588 
00589 static av_cold int alac_decode_init(AVCodecContext * avctx)
00590 {
00591     ALACContext *alac = avctx->priv_data;
00592     alac->avctx = avctx;
00593     alac->context_initialized = 0;
00594 
00595     alac->numchannels = alac->avctx->channels;
00596     alac->bytespersample = (avctx->bits_per_sample / 8) * alac->numchannels;
00597 
00598     return 0;
00599 }
00600 
00601 static av_cold int alac_decode_close(AVCodecContext *avctx)
00602 {
00603     ALACContext *alac = avctx->priv_data;
00604 
00605     int chan;
00606     for (chan = 0; chan < MAX_CHANNELS; chan++) {
00607         av_free(alac->predicterror_buffer[chan]);
00608         av_free(alac->outputsamples_buffer[chan]);
00609     }
00610 
00611     return 0;
00612 }
00613 
00614 AVCodec alac_decoder = {
00615     "alac",
00616     CODEC_TYPE_AUDIO,
00617     CODEC_ID_ALAC,
00618     sizeof(ALACContext),
00619     alac_decode_init,
00620     NULL,
00621     alac_decode_close,
00622     alac_decode_frame,
00623     .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
00624 };

Generated on Sat Oct 11 19:44:27 2008 for libextractor by  doxygen 1.5.1