• Main Page
  • Related Pages
  • Modules
  • Data Structures
  • Files
  • File List
  • Globals

libavcodec/alacenc.c

Go to the documentation of this file.
00001 
00022 #include "avcodec.h"
00023 #include "bitstream.h"
00024 #include "dsputil.h"
00025 #include "lpc.h"
00026 
00027 #define DEFAULT_FRAME_SIZE        4096
00028 #define DEFAULT_SAMPLE_SIZE       16
00029 #define MAX_CHANNELS              8
00030 #define ALAC_EXTRADATA_SIZE       36
00031 #define ALAC_FRAME_HEADER_SIZE    55
00032 #define ALAC_FRAME_FOOTER_SIZE    3
00033 
00034 #define ALAC_ESCAPE_CODE          0x1FF
00035 #define ALAC_MAX_LPC_ORDER        30
00036 #define DEFAULT_MAX_PRED_ORDER    6
00037 #define DEFAULT_MIN_PRED_ORDER    4
00038 #define ALAC_MAX_LPC_PRECISION    9
00039 #define ALAC_MAX_LPC_SHIFT        9
00040 
00041 #define ALAC_CHMODE_LEFT_RIGHT    0
00042 #define ALAC_CHMODE_LEFT_SIDE     1
00043 #define ALAC_CHMODE_RIGHT_SIDE    2
00044 #define ALAC_CHMODE_MID_SIDE      3
00045 
00046 typedef struct RiceContext {
00047     int history_mult;
00048     int initial_history;
00049     int k_modifier;
00050     int rice_modifier;
00051 } RiceContext;
00052 
00053 typedef struct LPCContext {
00054     int lpc_order;
00055     int lpc_coeff[ALAC_MAX_LPC_ORDER+1];
00056     int lpc_quant;
00057 } LPCContext;
00058 
00059 typedef struct AlacEncodeContext {
00060     int compression_level;
00061     int min_prediction_order;
00062     int max_prediction_order;
00063     int max_coded_frame_size;
00064     int write_sample_size;
00065     int32_t sample_buf[MAX_CHANNELS][DEFAULT_FRAME_SIZE];
00066     int32_t predictor_buf[DEFAULT_FRAME_SIZE];
00067     int interlacing_shift;
00068     int interlacing_leftweight;
00069     PutBitContext pbctx;
00070     RiceContext rc;
00071     LPCContext lpc[MAX_CHANNELS];
00072     DSPContext dspctx;
00073     AVCodecContext *avctx;
00074 } AlacEncodeContext;
00075 
00076 
00077 static void init_sample_buffers(AlacEncodeContext *s, int16_t *input_samples)
00078 {
00079     int ch, i;
00080 
00081     for(ch=0;ch<s->avctx->channels;ch++) {
00082         int16_t *sptr = input_samples + ch;
00083         for(i=0;i<s->avctx->frame_size;i++) {
00084             s->sample_buf[ch][i] = *sptr;
00085             sptr += s->avctx->channels;
00086         }
00087     }
00088 }
00089 
00090 static void encode_scalar(AlacEncodeContext *s, int x, int k, int write_sample_size)
00091 {
00092     int divisor, q, r;
00093 
00094     k = FFMIN(k, s->rc.k_modifier);
00095     divisor = (1<<k) - 1;
00096     q = x / divisor;
00097     r = x % divisor;
00098 
00099     if(q > 8) {
00100         // write escape code and sample value directly
00101         put_bits(&s->pbctx, 9, ALAC_ESCAPE_CODE);
00102         put_bits(&s->pbctx, write_sample_size, x);
00103     } else {
00104         if(q)
00105             put_bits(&s->pbctx, q, (1<<q) - 1);
00106         put_bits(&s->pbctx, 1, 0);
00107 
00108         if(k != 1) {
00109             if(r > 0)
00110                 put_bits(&s->pbctx, k, r+1);
00111             else
00112                 put_bits(&s->pbctx, k-1, 0);
00113         }
00114     }
00115 }
00116 
00117 static void write_frame_header(AlacEncodeContext *s, int is_verbatim)
00118 {
00119     put_bits(&s->pbctx, 3,  s->avctx->channels-1);          // No. of channels -1
00120     put_bits(&s->pbctx, 16, 0);                             // Seems to be zero
00121     put_bits(&s->pbctx, 1,  1);                             // Sample count is in the header
00122     put_bits(&s->pbctx, 2,  0);                             // FIXME: Wasted bytes field
00123     put_bits(&s->pbctx, 1,  is_verbatim);                   // Audio block is verbatim
00124     put_bits(&s->pbctx, 32, s->avctx->frame_size);          // No. of samples in the frame
00125 }
00126 
00127 static void calc_predictor_params(AlacEncodeContext *s, int ch)
00128 {
00129     int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
00130     int shift[MAX_LPC_ORDER];
00131     int opt_order;
00132 
00133     opt_order = ff_lpc_calc_coefs(&s->dspctx, s->sample_buf[ch], s->avctx->frame_size, s->min_prediction_order, s->max_prediction_order,
00134                                    ALAC_MAX_LPC_PRECISION, coefs, shift, 1, ORDER_METHOD_EST, ALAC_MAX_LPC_SHIFT, 1);
00135 
00136     s->lpc[ch].lpc_order = opt_order;
00137     s->lpc[ch].lpc_quant = shift[opt_order-1];
00138     memcpy(s->lpc[ch].lpc_coeff, coefs[opt_order-1], opt_order*sizeof(int));
00139 }
00140 
00141 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
00142 {
00143     int i, best;
00144     int32_t lt, rt;
00145     uint64_t sum[4];
00146     uint64_t score[4];
00147 
00148     /* calculate sum of 2nd order residual for each channel */
00149     sum[0] = sum[1] = sum[2] = sum[3] = 0;
00150     for(i=2; i<n; i++) {
00151         lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
00152         rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
00153         sum[2] += FFABS((lt + rt) >> 1);
00154         sum[3] += FFABS(lt - rt);
00155         sum[0] += FFABS(lt);
00156         sum[1] += FFABS(rt);
00157     }
00158 
00159     /* calculate score for each mode */
00160     score[0] = sum[0] + sum[1];
00161     score[1] = sum[0] + sum[3];
00162     score[2] = sum[1] + sum[3];
00163     score[3] = sum[2] + sum[3];
00164 
00165     /* return mode with lowest score */
00166     best = 0;
00167     for(i=1; i<4; i++) {
00168         if(score[i] < score[best]) {
00169             best = i;
00170         }
00171     }
00172     return best;
00173 }
00174 
00175 static void alac_stereo_decorrelation(AlacEncodeContext *s)
00176 {
00177     int32_t *left = s->sample_buf[0], *right = s->sample_buf[1];
00178     int i, mode, n = s->avctx->frame_size;
00179     int32_t tmp;
00180 
00181     mode = estimate_stereo_mode(left, right, n);
00182 
00183     switch(mode)
00184     {
00185         case ALAC_CHMODE_LEFT_RIGHT:
00186             s->interlacing_leftweight = 0;
00187             s->interlacing_shift = 0;
00188             break;
00189 
00190         case ALAC_CHMODE_LEFT_SIDE:
00191             for(i=0; i<n; i++) {
00192                 right[i] = left[i] - right[i];
00193             }
00194             s->interlacing_leftweight = 1;
00195             s->interlacing_shift = 0;
00196             break;
00197 
00198         case ALAC_CHMODE_RIGHT_SIDE:
00199             for(i=0; i<n; i++) {
00200                 tmp = right[i];
00201                 right[i] = left[i] - right[i];
00202                 left[i] = tmp + (right[i] >> 31);
00203             }
00204             s->interlacing_leftweight = 1;
00205             s->interlacing_shift = 31;
00206             break;
00207 
00208         default:
00209             for(i=0; i<n; i++) {
00210                 tmp = left[i];
00211                 left[i] = (tmp + right[i]) >> 1;
00212                 right[i] = tmp - right[i];
00213             }
00214             s->interlacing_leftweight = 1;
00215             s->interlacing_shift = 1;
00216             break;
00217     }
00218 }
00219 
00220 static void alac_linear_predictor(AlacEncodeContext *s, int ch)
00221 {
00222     int i;
00223     LPCContext lpc = s->lpc[ch];
00224 
00225     if(lpc.lpc_order == 31) {
00226         s->predictor_buf[0] = s->sample_buf[ch][0];
00227 
00228         for(i=1; i<s->avctx->frame_size; i++)
00229             s->predictor_buf[i] = s->sample_buf[ch][i] - s->sample_buf[ch][i-1];
00230 
00231         return;
00232     }
00233 
00234     // generalised linear predictor
00235 
00236     if(lpc.lpc_order > 0) {
00237         int32_t *samples  = s->sample_buf[ch];
00238         int32_t *residual = s->predictor_buf;
00239 
00240         // generate warm-up samples
00241         residual[0] = samples[0];
00242         for(i=1;i<=lpc.lpc_order;i++)
00243             residual[i] = samples[i] - samples[i-1];
00244 
00245         // perform lpc on remaining samples
00246         for(i = lpc.lpc_order + 1; i < s->avctx->frame_size; i++) {
00247             int sum = 1 << (lpc.lpc_quant - 1), res_val, j;
00248 
00249             for (j = 0; j < lpc.lpc_order; j++) {
00250                 sum += (samples[lpc.lpc_order-j] - samples[0]) *
00251                         lpc.lpc_coeff[j];
00252             }
00253 
00254             sum >>= lpc.lpc_quant;
00255             sum += samples[0];
00256             residual[i] = (samples[lpc.lpc_order+1] - sum) << (32 - s->write_sample_size) >>
00257                           (32 - s->write_sample_size);
00258             res_val = residual[i];
00259 
00260             if(res_val) {
00261                 int index = lpc.lpc_order - 1;
00262                 int neg = (res_val < 0);
00263 
00264                 while(index >= 0 && (neg ? (res_val < 0):(res_val > 0))) {
00265                     int val = samples[0] - samples[lpc.lpc_order - index];
00266                     int sign = (val ? FFSIGN(val) : 0);
00267 
00268                     if(neg)
00269                         sign*=-1;
00270 
00271                     lpc.lpc_coeff[index] -= sign;
00272                     val *= sign;
00273                     res_val -= ((val >> lpc.lpc_quant) *
00274                             (lpc.lpc_order - index));
00275                     index--;
00276                 }
00277             }
00278             samples++;
00279         }
00280     }
00281 }
00282 
00283 static void alac_entropy_coder(AlacEncodeContext *s)
00284 {
00285     unsigned int history = s->rc.initial_history;
00286     int sign_modifier = 0, i, k;
00287     int32_t *samples = s->predictor_buf;
00288 
00289     for(i=0;i < s->avctx->frame_size;) {
00290         int x;
00291 
00292         k = av_log2((history >> 9) + 3);
00293 
00294         x = -2*(*samples)-1;
00295         x ^= (x>>31);
00296 
00297         samples++;
00298         i++;
00299 
00300         encode_scalar(s, x - sign_modifier, k, s->write_sample_size);
00301 
00302         history += x * s->rc.history_mult
00303                    - ((history * s->rc.history_mult) >> 9);
00304 
00305         sign_modifier = 0;
00306         if(x > 0xFFFF)
00307             history = 0xFFFF;
00308 
00309         if((history < 128) && (i < s->avctx->frame_size)) {
00310             unsigned int block_size = 0;
00311 
00312             k = 7 - av_log2(history) + ((history + 16) >> 6);
00313 
00314             while((*samples == 0) && (i < s->avctx->frame_size)) {
00315                 samples++;
00316                 i++;
00317                 block_size++;
00318             }
00319             encode_scalar(s, block_size, k, 16);
00320 
00321             sign_modifier = (block_size <= 0xFFFF);
00322 
00323             history = 0;
00324         }
00325 
00326     }
00327 }
00328 
00329 static void write_compressed_frame(AlacEncodeContext *s)
00330 {
00331     int i, j;
00332 
00333     /* only simple mid/side decorrelation supported as of now */
00334     if(s->avctx->channels == 2)
00335         alac_stereo_decorrelation(s);
00336     put_bits(&s->pbctx, 8, s->interlacing_shift);
00337     put_bits(&s->pbctx, 8, s->interlacing_leftweight);
00338 
00339     for(i=0;i<s->avctx->channels;i++) {
00340 
00341         calc_predictor_params(s, i);
00342 
00343         put_bits(&s->pbctx, 4, 0);  // prediction type : currently only type 0 has been RE'd
00344         put_bits(&s->pbctx, 4, s->lpc[i].lpc_quant);
00345 
00346         put_bits(&s->pbctx, 3, s->rc.rice_modifier);
00347         put_bits(&s->pbctx, 5, s->lpc[i].lpc_order);
00348         // predictor coeff. table
00349         for(j=0;j<s->lpc[i].lpc_order;j++) {
00350             put_sbits(&s->pbctx, 16, s->lpc[i].lpc_coeff[j]);
00351         }
00352     }
00353 
00354     // apply lpc and entropy coding to audio samples
00355 
00356     for(i=0;i<s->avctx->channels;i++) {
00357         alac_linear_predictor(s, i);
00358         alac_entropy_coder(s);
00359     }
00360 }
00361 
00362 static av_cold int alac_encode_init(AVCodecContext *avctx)
00363 {
00364     AlacEncodeContext *s    = avctx->priv_data;
00365     uint8_t *alac_extradata = av_mallocz(ALAC_EXTRADATA_SIZE+1);
00366 
00367     avctx->frame_size      = DEFAULT_FRAME_SIZE;
00368     avctx->bits_per_coded_sample = DEFAULT_SAMPLE_SIZE;
00369 
00370     if(avctx->sample_fmt != SAMPLE_FMT_S16) {
00371         av_log(avctx, AV_LOG_ERROR, "only pcm_s16 input samples are supported\n");
00372         return -1;
00373     }
00374 
00375     // Set default compression level
00376     if(avctx->compression_level == FF_COMPRESSION_DEFAULT)
00377         s->compression_level = 1;
00378     else
00379         s->compression_level = av_clip(avctx->compression_level, 0, 1);
00380 
00381     // Initialize default Rice parameters
00382     s->rc.history_mult    = 40;
00383     s->rc.initial_history = 10;
00384     s->rc.k_modifier      = 14;
00385     s->rc.rice_modifier   = 4;
00386 
00387     s->max_coded_frame_size = (ALAC_FRAME_HEADER_SIZE + ALAC_FRAME_FOOTER_SIZE +
00388                                avctx->frame_size*avctx->channels*avctx->bits_per_coded_sample)>>3;
00389 
00390     s->write_sample_size  = avctx->bits_per_coded_sample + avctx->channels - 1; // FIXME: consider wasted_bytes
00391 
00392     AV_WB32(alac_extradata,    ALAC_EXTRADATA_SIZE);
00393     AV_WB32(alac_extradata+4,  MKBETAG('a','l','a','c'));
00394     AV_WB32(alac_extradata+12, avctx->frame_size);
00395     AV_WB8 (alac_extradata+17, avctx->bits_per_coded_sample);
00396     AV_WB8 (alac_extradata+21, avctx->channels);
00397     AV_WB32(alac_extradata+24, s->max_coded_frame_size);
00398     AV_WB32(alac_extradata+28, avctx->sample_rate*avctx->channels*avctx->bits_per_coded_sample); // average bitrate
00399     AV_WB32(alac_extradata+32, avctx->sample_rate);
00400 
00401     // Set relevant extradata fields
00402     if(s->compression_level > 0) {
00403         AV_WB8(alac_extradata+18, s->rc.history_mult);
00404         AV_WB8(alac_extradata+19, s->rc.initial_history);
00405         AV_WB8(alac_extradata+20, s->rc.k_modifier);
00406     }
00407 
00408     s->min_prediction_order = DEFAULT_MIN_PRED_ORDER;
00409     if(avctx->min_prediction_order >= 0) {
00410         if(avctx->min_prediction_order < MIN_LPC_ORDER ||
00411            avctx->min_prediction_order > ALAC_MAX_LPC_ORDER) {
00412             av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n", avctx->min_prediction_order);
00413                 return -1;
00414         }
00415 
00416         s->min_prediction_order = avctx->min_prediction_order;
00417     }
00418 
00419     s->max_prediction_order = DEFAULT_MAX_PRED_ORDER;
00420     if(avctx->max_prediction_order >= 0) {
00421         if(avctx->max_prediction_order < MIN_LPC_ORDER ||
00422            avctx->max_prediction_order > ALAC_MAX_LPC_ORDER) {
00423             av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n", avctx->max_prediction_order);
00424                 return -1;
00425         }
00426 
00427         s->max_prediction_order = avctx->max_prediction_order;
00428     }
00429 
00430     if(s->max_prediction_order < s->min_prediction_order) {
00431         av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
00432                s->min_prediction_order, s->max_prediction_order);
00433         return -1;
00434     }
00435 
00436     avctx->extradata = alac_extradata;
00437     avctx->extradata_size = ALAC_EXTRADATA_SIZE;
00438 
00439     avctx->coded_frame = avcodec_alloc_frame();
00440     avctx->coded_frame->key_frame = 1;
00441 
00442     s->avctx = avctx;
00443     dsputil_init(&s->dspctx, avctx);
00444 
00445     return 0;
00446 }
00447 
00448 static int alac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
00449                              int buf_size, void *data)
00450 {
00451     AlacEncodeContext *s = avctx->priv_data;
00452     PutBitContext *pb = &s->pbctx;
00453     int i, out_bytes, verbatim_flag = 0;
00454 
00455     if(avctx->frame_size > DEFAULT_FRAME_SIZE) {
00456         av_log(avctx, AV_LOG_ERROR, "input frame size exceeded\n");
00457         return -1;
00458     }
00459 
00460     if(buf_size < 2*s->max_coded_frame_size) {
00461         av_log(avctx, AV_LOG_ERROR, "buffer size is too small\n");
00462         return -1;
00463     }
00464 
00465 verbatim:
00466     init_put_bits(pb, frame, buf_size);
00467 
00468     if((s->compression_level == 0) || verbatim_flag) {
00469         // Verbatim mode
00470         int16_t *samples = data;
00471         write_frame_header(s, 1);
00472         for(i=0; i<avctx->frame_size*avctx->channels; i++) {
00473             put_sbits(pb, 16, *samples++);
00474         }
00475     } else {
00476         init_sample_buffers(s, data);
00477         write_frame_header(s, 0);
00478         write_compressed_frame(s);
00479     }
00480 
00481     put_bits(pb, 3, 7);
00482     flush_put_bits(pb);
00483     out_bytes = put_bits_count(pb) >> 3;
00484 
00485     if(out_bytes > s->max_coded_frame_size) {
00486         /* frame too large. use verbatim mode */
00487         if(verbatim_flag || (s->compression_level == 0)) {
00488             /* still too large. must be an error. */
00489             av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
00490             return -1;
00491         }
00492         verbatim_flag = 1;
00493         goto verbatim;
00494     }
00495 
00496     return out_bytes;
00497 }
00498 
00499 static av_cold int alac_encode_close(AVCodecContext *avctx)
00500 {
00501     av_freep(&avctx->extradata);
00502     avctx->extradata_size = 0;
00503     av_freep(&avctx->coded_frame);
00504     return 0;
00505 }
00506 
00507 AVCodec alac_encoder = {
00508     "alac",
00509     CODEC_TYPE_AUDIO,
00510     CODEC_ID_ALAC,
00511     sizeof(AlacEncodeContext),
00512     alac_encode_init,
00513     alac_encode_frame,
00514     alac_encode_close,
00515     .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
00516     .long_name = NULL_IF_CONFIG_SMALL("ALAC (Apple Lossless Audio Codec)"),
00517 };

Generated on Sat Feb 16 2013 09:23:11 for ffmpeg by  doxygen 1.7.1