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