flacenc.c

Go to the documentation of this file.
00001 /**
00002  * FLAC audio encoder
00003  * Copyright (c) 2006  Justin Ruggles <jruggle@earthlink.net>
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 #include "libavutil/crc.h"
00023 #include "libavutil/lls.h"
00024 #include "avcodec.h"
00025 #include "bitstream.h"
00026 #include "dsputil.h"
00027 #include "golomb.h"
00028 
00029 #define FLAC_MAX_CH  8
00030 #define FLAC_MIN_BLOCKSIZE  16
00031 #define FLAC_MAX_BLOCKSIZE  65535
00032 
00033 #define FLAC_SUBFRAME_CONSTANT  0
00034 #define FLAC_SUBFRAME_VERBATIM  1
00035 #define FLAC_SUBFRAME_FIXED     8
00036 #define FLAC_SUBFRAME_LPC      32
00037 
00038 #define FLAC_CHMODE_NOT_STEREO      0
00039 #define FLAC_CHMODE_LEFT_RIGHT      1
00040 #define FLAC_CHMODE_LEFT_SIDE       8
00041 #define FLAC_CHMODE_RIGHT_SIDE      9
00042 #define FLAC_CHMODE_MID_SIDE       10
00043 
00044 #define ORDER_METHOD_EST     0
00045 #define ORDER_METHOD_2LEVEL  1
00046 #define ORDER_METHOD_4LEVEL  2
00047 #define ORDER_METHOD_8LEVEL  3
00048 #define ORDER_METHOD_SEARCH  4
00049 #define ORDER_METHOD_LOG     5
00050 
00051 #define FLAC_STREAMINFO_SIZE  34
00052 
00053 #define MIN_LPC_ORDER       1
00054 #define MAX_LPC_ORDER      32
00055 #define MAX_FIXED_ORDER     4
00056 #define MAX_PARTITION_ORDER 8
00057 #define MAX_PARTITIONS     (1 << MAX_PARTITION_ORDER)
00058 #define MAX_LPC_PRECISION  15
00059 #define MAX_LPC_SHIFT      15
00060 #define MAX_RICE_PARAM     14
00061 
00062 typedef struct CompressionOptions {
00063     int compression_level;
00064     int block_time_ms;
00065     int use_lpc;
00066     int lpc_coeff_precision;
00067     int min_prediction_order;
00068     int max_prediction_order;
00069     int prediction_order_method;
00070     int min_partition_order;
00071     int max_partition_order;
00072 } CompressionOptions;
00073 
00074 typedef struct RiceContext {
00075     int porder;
00076     int params[MAX_PARTITIONS];
00077 } RiceContext;
00078 
00079 typedef struct FlacSubframe {
00080     int type;
00081     int type_code;
00082     int obits;
00083     int order;
00084     int32_t coefs[MAX_LPC_ORDER];
00085     int shift;
00086     RiceContext rc;
00087     int32_t samples[FLAC_MAX_BLOCKSIZE];
00088     int32_t residual[FLAC_MAX_BLOCKSIZE+1];
00089 } FlacSubframe;
00090 
00091 typedef struct FlacFrame {
00092     FlacSubframe subframes[FLAC_MAX_CH];
00093     int blocksize;
00094     int bs_code[2];
00095     uint8_t crc8;
00096     int ch_mode;
00097 } FlacFrame;
00098 
00099 typedef struct FlacEncodeContext {
00100     PutBitContext pb;
00101     int channels;
00102     int ch_code;
00103     int samplerate;
00104     int sr_code[2];
00105     int max_framesize;
00106     uint32_t frame_count;
00107     FlacFrame frame;
00108     CompressionOptions options;
00109     AVCodecContext *avctx;
00110     DSPContext dsp;
00111 } FlacEncodeContext;
00112 
00113 static const int flac_samplerates[16] = {
00114     0, 0, 0, 0,
00115     8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000,
00116     0, 0, 0, 0
00117 };
00118 
00119 static const int flac_blocksizes[16] = {
00120     0,
00121     192,
00122     576, 1152, 2304, 4608,
00123     0, 0,
00124     256, 512, 1024, 2048, 4096, 8192, 16384, 32768
00125 };
00126 
00127 /**
00128  * Writes streaminfo metadata block to byte array
00129  */
00130 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
00131 {
00132     PutBitContext pb;
00133 
00134     memset(header, 0, FLAC_STREAMINFO_SIZE);
00135     init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
00136 
00137     /* streaminfo metadata block */
00138     put_bits(&pb, 16, s->avctx->frame_size);
00139     put_bits(&pb, 16, s->avctx->frame_size);
00140     put_bits(&pb, 24, 0);
00141     put_bits(&pb, 24, s->max_framesize);
00142     put_bits(&pb, 20, s->samplerate);
00143     put_bits(&pb, 3, s->channels-1);
00144     put_bits(&pb, 5, 15);       /* bits per sample - 1 */
00145     flush_put_bits(&pb);
00146     /* total samples = 0 */
00147     /* MD5 signature = 0 */
00148 }
00149 
00150 /**
00151  * Sets blocksize based on samplerate
00152  * Chooses the closest predefined blocksize >= BLOCK_TIME_MS milliseconds
00153  */
00154 static int select_blocksize(int samplerate, int block_time_ms)
00155 {
00156     int i;
00157     int target;
00158     int blocksize;
00159 
00160     assert(samplerate > 0);
00161     blocksize = flac_blocksizes[1];
00162     target = (samplerate * block_time_ms) / 1000;
00163     for(i=0; i<16; i++) {
00164         if(target >= flac_blocksizes[i] && flac_blocksizes[i] > blocksize) {
00165             blocksize = flac_blocksizes[i];
00166         }
00167     }
00168     return blocksize;
00169 }
00170 
00171 static av_cold int flac_encode_init(AVCodecContext *avctx)
00172 {
00173     int freq = avctx->sample_rate;
00174     int channels = avctx->channels;
00175     FlacEncodeContext *s = avctx->priv_data;
00176     int i, level;
00177     uint8_t *streaminfo;
00178 
00179     s->avctx = avctx;
00180 
00181     dsputil_init(&s->dsp, avctx);
00182 
00183     if(avctx->sample_fmt != SAMPLE_FMT_S16) {
00184         return -1;
00185     }
00186 
00187     if(channels < 1 || channels > FLAC_MAX_CH) {
00188         return -1;
00189     }
00190     s->channels = channels;
00191     s->ch_code = s->channels-1;
00192 
00193     /* find samplerate in table */
00194     if(freq < 1)
00195         return -1;
00196     for(i=4; i<12; i++) {
00197         if(freq == flac_samplerates[i]) {
00198             s->samplerate = flac_samplerates[i];
00199             s->sr_code[0] = i;
00200             s->sr_code[1] = 0;
00201             break;
00202         }
00203     }
00204     /* if not in table, samplerate is non-standard */
00205     if(i == 12) {
00206         if(freq % 1000 == 0 && freq < 255000) {
00207             s->sr_code[0] = 12;
00208             s->sr_code[1] = freq / 1000;
00209         } else if(freq % 10 == 0 && freq < 655350) {
00210             s->sr_code[0] = 14;
00211             s->sr_code[1] = freq / 10;
00212         } else if(freq < 65535) {
00213             s->sr_code[0] = 13;
00214             s->sr_code[1] = freq;
00215         } else {
00216             return -1;
00217         }
00218         s->samplerate = freq;
00219     }
00220 
00221     /* set compression option defaults based on avctx->compression_level */
00222     if(avctx->compression_level < 0) {
00223         s->options.compression_level = 5;
00224     } else {
00225         s->options.compression_level = avctx->compression_level;
00226     }
00227     av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", s->options.compression_level);
00228 
00229     level= s->options.compression_level;
00230     if(level > 12) {
00231         av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
00232                s->options.compression_level);
00233         return -1;
00234     }
00235 
00236     s->options.block_time_ms       = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
00237     s->options.use_lpc             = ((int[]){  0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1})[level];
00238     s->options.min_prediction_order= ((int[]){  2,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1})[level];
00239     s->options.max_prediction_order= ((int[]){  3,  4,  4,  6,  8,  8,  8,  8, 12, 12, 12, 32, 32})[level];
00240     s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST,    ORDER_METHOD_EST,    ORDER_METHOD_EST,
00241                                                    ORDER_METHOD_EST,    ORDER_METHOD_EST,    ORDER_METHOD_EST,
00242                                                    ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG,    ORDER_METHOD_4LEVEL,
00243                                                    ORDER_METHOD_LOG,    ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
00244                                                    ORDER_METHOD_SEARCH})[level];
00245     s->options.min_partition_order = ((int[]){  2,  2,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0})[level];
00246     s->options.max_partition_order = ((int[]){  2,  2,  3,  3,  3,  8,  8,  8,  8,  8,  8,  8,  8})[level];
00247 
00248     /* set compression option overrides from AVCodecContext */
00249     if(avctx->use_lpc >= 0) {
00250         s->options.use_lpc = av_clip(avctx->use_lpc, 0, 11);
00251     }
00252     if(s->options.use_lpc == 1)
00253         av_log(avctx, AV_LOG_DEBUG, " use lpc: Levinson-Durbin recursion with Welch window\n");
00254     else if(s->options.use_lpc > 1)
00255         av_log(avctx, AV_LOG_DEBUG, " use lpc: Cholesky factorization\n");
00256 
00257     if(avctx->min_prediction_order >= 0) {
00258         if(s->options.use_lpc) {
00259             if(avctx->min_prediction_order < MIN_LPC_ORDER ||
00260                     avctx->min_prediction_order > MAX_LPC_ORDER) {
00261                 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
00262                        avctx->min_prediction_order);
00263                 return -1;
00264             }
00265         } else {
00266             if(avctx->min_prediction_order > MAX_FIXED_ORDER) {
00267                 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
00268                        avctx->min_prediction_order);
00269                 return -1;
00270             }
00271         }
00272         s->options.min_prediction_order = avctx->min_prediction_order;
00273     }
00274     if(avctx->max_prediction_order >= 0) {
00275         if(s->options.use_lpc) {
00276             if(avctx->max_prediction_order < MIN_LPC_ORDER ||
00277                     avctx->max_prediction_order > MAX_LPC_ORDER) {
00278                 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
00279                        avctx->max_prediction_order);
00280                 return -1;
00281             }
00282         } else {
00283             if(avctx->max_prediction_order > MAX_FIXED_ORDER) {
00284                 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
00285                        avctx->max_prediction_order);
00286                 return -1;
00287             }
00288         }
00289         s->options.max_prediction_order = avctx->max_prediction_order;
00290     }
00291     if(s->options.max_prediction_order < s->options.min_prediction_order) {
00292         av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
00293                s->options.min_prediction_order, s->options.max_prediction_order);
00294         return -1;
00295     }
00296     av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
00297            s->options.min_prediction_order, s->options.max_prediction_order);
00298 
00299     if(avctx->prediction_order_method >= 0) {
00300         if(avctx->prediction_order_method > ORDER_METHOD_LOG) {
00301             av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n",
00302                    avctx->prediction_order_method);
00303             return -1;
00304         }
00305         s->options.prediction_order_method = avctx->prediction_order_method;
00306     }
00307     switch(s->options.prediction_order_method) {
00308         case ORDER_METHOD_EST:    av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
00309                                          "estimate"); break;
00310         case ORDER_METHOD_2LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
00311                                          "2-level"); break;
00312         case ORDER_METHOD_4LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
00313                                          "4-level"); break;
00314         case ORDER_METHOD_8LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
00315                                          "8-level"); break;
00316         case ORDER_METHOD_SEARCH: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
00317                                          "full search"); break;
00318         case ORDER_METHOD_LOG:    av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
00319                                          "log search"); break;
00320     }
00321 
00322     if(avctx->min_partition_order >= 0) {
00323         if(avctx->min_partition_order > MAX_PARTITION_ORDER) {
00324             av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n",
00325                    avctx->min_partition_order);
00326             return -1;
00327         }
00328         s->options.min_partition_order = avctx->min_partition_order;
00329     }
00330     if(avctx->max_partition_order >= 0) {
00331         if(avctx->max_partition_order > MAX_PARTITION_ORDER) {
00332             av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n",
00333                    avctx->max_partition_order);
00334             return -1;
00335         }
00336         s->options.max_partition_order = avctx->max_partition_order;
00337     }
00338     if(s->options.max_partition_order < s->options.min_partition_order) {
00339         av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
00340                s->options.min_partition_order, s->options.max_partition_order);
00341         return -1;
00342     }
00343     av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
00344            s->options.min_partition_order, s->options.max_partition_order);
00345 
00346     if(avctx->frame_size > 0) {
00347         if(avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
00348                 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
00349             av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
00350                    avctx->frame_size);
00351             return -1;
00352         }
00353     } else {
00354         s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
00355     }
00356     av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", s->avctx->frame_size);
00357 
00358     /* set LPC precision */
00359     if(avctx->lpc_coeff_precision > 0) {
00360         if(avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
00361             av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
00362                    avctx->lpc_coeff_precision);
00363             return -1;
00364         }
00365         s->options.lpc_coeff_precision = avctx->lpc_coeff_precision;
00366     } else {
00367         /* default LPC precision */
00368         s->options.lpc_coeff_precision = 15;
00369     }
00370     av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
00371            s->options.lpc_coeff_precision);
00372 
00373     /* set maximum encoded frame size in verbatim mode */
00374     if(s->channels == 2) {
00375         s->max_framesize = 14 + ((s->avctx->frame_size * 33 + 7) >> 3);
00376     } else {
00377         s->max_framesize = 14 + (s->avctx->frame_size * s->channels * 2);
00378     }
00379 
00380     streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
00381     write_streaminfo(s, streaminfo);
00382     avctx->extradata = streaminfo;
00383     avctx->extradata_size = FLAC_STREAMINFO_SIZE;
00384 
00385     s->frame_count = 0;
00386 
00387     avctx->coded_frame = avcodec_alloc_frame();
00388     avctx->coded_frame->key_frame = 1;
00389 
00390     return 0;
00391 }
00392 
00393 static void init_frame(FlacEncodeContext *s)
00394 {
00395     int i, ch;
00396     FlacFrame *frame;
00397 
00398     frame = &s->frame;
00399 
00400     for(i=0; i<16; i++) {
00401         if(s->avctx->frame_size == flac_blocksizes[i]) {
00402             frame->blocksize = flac_blocksizes[i];
00403             frame->bs_code[0] = i;
00404             frame->bs_code[1] = 0;
00405             break;
00406         }
00407     }
00408     if(i == 16) {
00409         frame->blocksize = s->avctx->frame_size;
00410         if(frame->blocksize <= 256) {
00411             frame->bs_code[0] = 6;
00412             frame->bs_code[1] = frame->blocksize-1;
00413         } else {
00414             frame->bs_code[0] = 7;
00415             frame->bs_code[1] = frame->blocksize-1;
00416         }
00417     }
00418 
00419     for(ch=0; ch<s->channels; ch++) {
00420         frame->subframes[ch].obits = 16;
00421     }
00422 }
00423 
00424 /**
00425  * Copy channel-interleaved input samples into separate subframes
00426  */
00427 static void copy_samples(FlacEncodeContext *s, int16_t *samples)
00428 {
00429     int i, j, ch;
00430     FlacFrame *frame;
00431 
00432     frame = &s->frame;
00433     for(i=0,j=0; i<frame->blocksize; i++) {
00434         for(ch=0; ch<s->channels; ch++,j++) {
00435             frame->subframes[ch].samples[i] = samples[j];
00436         }
00437     }
00438 }
00439 
00440 
00441 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
00442 
00443 /**
00444  * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0
00445  */
00446 static int find_optimal_param(uint32_t sum, int n)
00447 {
00448     int k;
00449     uint32_t sum2;
00450 
00451     if(sum <= n>>1)
00452         return 0;
00453     sum2 = sum-(n>>1);
00454     k = av_log2(n<256 ? FASTDIV(sum2,n) : sum2/n);
00455     return FFMIN(k, MAX_RICE_PARAM);
00456 }
00457 
00458 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
00459                                          uint32_t *sums, int n, int pred_order)
00460 {
00461     int i;
00462     int k, cnt, part;
00463     uint32_t all_bits;
00464 
00465     part = (1 << porder);
00466     all_bits = 4 * part;
00467 
00468     cnt = (n >> porder) - pred_order;
00469     for(i=0; i<part; i++) {
00470         k = find_optimal_param(sums[i], cnt);
00471         rc->params[i] = k;
00472         all_bits += rice_encode_count(sums[i], cnt, k);
00473         cnt = n >> porder;
00474     }
00475 
00476     rc->porder = porder;
00477 
00478     return all_bits;
00479 }
00480 
00481 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
00482                       uint32_t sums[][MAX_PARTITIONS])
00483 {
00484     int i, j;
00485     int parts;
00486     uint32_t *res, *res_end;
00487 
00488     /* sums for highest level */
00489     parts = (1 << pmax);
00490     res = &data[pred_order];
00491     res_end = &data[n >> pmax];
00492     for(i=0; i<parts; i++) {
00493         uint32_t sum = 0;
00494         while(res < res_end){
00495             sum += *(res++);
00496         }
00497         sums[pmax][i] = sum;
00498         res_end+= n >> pmax;
00499     }
00500     /* sums for lower levels */
00501     for(i=pmax-1; i>=pmin; i--) {
00502         parts = (1 << i);
00503         for(j=0; j<parts; j++) {
00504             sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
00505         }
00506     }
00507 }
00508 
00509 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
00510                                  int32_t *data, int n, int pred_order)
00511 {
00512     int i;
00513     uint32_t bits[MAX_PARTITION_ORDER+1];
00514     int opt_porder;
00515     RiceContext tmp_rc;
00516     uint32_t *udata;
00517     uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
00518 
00519     assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
00520     assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
00521     assert(pmin <= pmax);
00522 
00523     udata = av_malloc(n * sizeof(uint32_t));
00524     for(i=0; i<n; i++) {
00525         udata[i] = (2*data[i]) ^ (data[i]>>31);
00526     }
00527 
00528     calc_sums(pmin, pmax, udata, n, pred_order, sums);
00529 
00530     opt_porder = pmin;
00531     bits[pmin] = UINT32_MAX;
00532     for(i=pmin; i<=pmax; i++) {
00533         bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
00534         if(bits[i] <= bits[opt_porder]) {
00535             opt_porder = i;
00536             *rc= tmp_rc;
00537         }
00538     }
00539 
00540     av_freep(&udata);
00541     return bits[opt_porder];
00542 }
00543 
00544 static int get_max_p_order(int max_porder, int n, int order)
00545 {
00546     int porder = FFMIN(max_porder, av_log2(n^(n-1)));
00547     if(order > 0)
00548         porder = FFMIN(porder, av_log2(n/order));
00549     return porder;
00550 }
00551 
00552 static uint32_t calc_rice_params_fixed(RiceContext *rc, int pmin, int pmax,
00553                                        int32_t *data, int n, int pred_order,
00554                                        int bps)
00555 {
00556     uint32_t bits;
00557     pmin = get_max_p_order(pmin, n, pred_order);
00558     pmax = get_max_p_order(pmax, n, pred_order);
00559     bits = pred_order*bps + 6;
00560     bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
00561     return bits;
00562 }
00563 
00564 static uint32_t calc_rice_params_lpc(RiceContext *rc, int pmin, int pmax,
00565                                      int32_t *data, int n, int pred_order,
00566                                      int bps, int precision)
00567 {
00568     uint32_t bits;
00569     pmin = get_max_p_order(pmin, n, pred_order);
00570     pmax = get_max_p_order(pmax, n, pred_order);
00571     bits = pred_order*bps + 4 + 5 + pred_order*precision + 6;
00572     bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
00573     return bits;
00574 }
00575 
00576 /**
00577  * Apply Welch window function to audio block
00578  */
00579 static void apply_welch_window(const int32_t *data, int len, double *w_data)
00580 {
00581     int i, n2;
00582     double w;
00583     double c;
00584 
00585     assert(!(len&1)); //the optimization in r11881 does not support odd len
00586                       //if someone wants odd len extend the change in r11881
00587 
00588     n2 = (len >> 1);
00589     c = 2.0 / (len - 1.0);
00590 
00591     w_data+=n2;
00592       data+=n2;
00593     for(i=0; i<n2; i++) {
00594         w = c - n2 + i;
00595         w = 1.0 - (w * w);
00596         w_data[-i-1] = data[-i-1] * w;
00597         w_data[+i  ] = data[+i  ] * w;
00598     }
00599 }
00600 
00601 /**
00602  * Calculates autocorrelation data from audio samples
00603  * A Welch window function is applied before calculation.
00604  */
00605 void ff_flac_compute_autocorr(const int32_t *data, int len, int lag,
00606                               double *autoc)
00607 {
00608     int i, j;
00609     double tmp[len + lag + 1];
00610     double *data1= tmp + lag;
00611 
00612     apply_welch_window(data, len, data1);
00613 
00614     for(j=0; j<lag; j++)
00615         data1[j-lag]= 0.0;
00616     data1[len] = 0.0;
00617 
00618     for(j=0; j<lag; j+=2){
00619         double sum0 = 1.0, sum1 = 1.0;
00620         for(i=0; i<len; i++){
00621             sum0 += data1[i] * data1[i-j];
00622             sum1 += data1[i] * data1[i-j-1];
00623         }
00624         autoc[j  ] = sum0;
00625         autoc[j+1] = sum1;
00626     }
00627 
00628     if(j==lag){
00629         double sum = 1.0;
00630         for(i=0; i<len; i+=2){
00631             sum += data1[i  ] * data1[i-j  ]
00632                  + data1[i+1] * data1[i-j+1];
00633         }
00634         autoc[j] = sum;
00635     }
00636 }
00637 
00638 /**
00639  * Levinson-Durbin recursion.
00640  * Produces LPC coefficients from autocorrelation data.
00641  */
00642 static void compute_lpc_coefs(const double *autoc, int max_order,
00643                               double lpc[][MAX_LPC_ORDER], double *ref)
00644 {
00645    int i, j, i2;
00646    double r, err, tmp;
00647    double lpc_tmp[MAX_LPC_ORDER];
00648 
00649    for(i=0; i<max_order; i++) lpc_tmp[i] = 0;
00650    err = autoc[0];
00651 
00652    for(i=0; i<max_order; i++) {
00653       r = -autoc[i+1];
00654       for(j=0; j<i; j++) {
00655           r -= lpc_tmp[j] * autoc[i-j];
00656       }
00657       r /= err;
00658       ref[i] = fabs(r);
00659 
00660       err *= 1.0 - (r * r);
00661 
00662       i2 = (i >> 1);
00663       lpc_tmp[i] = r;
00664       for(j=0; j<i2; j++) {
00665          tmp = lpc_tmp[j];
00666          lpc_tmp[j] += r * lpc_tmp[i-1-j];
00667          lpc_tmp[i-1-j] += r * tmp;
00668       }
00669       if(i & 1) {
00670           lpc_tmp[j] += lpc_tmp[j] * r;
00671       }
00672 
00673       for(j=0; j<=i; j++) {
00674           lpc[i][j] = -lpc_tmp[j];
00675       }
00676    }
00677 }
00678 
00679 /**
00680  * Quantize LPC coefficients
00681  */
00682 static void quantize_lpc_coefs(double *lpc_in, int order, int precision,
00683                                int32_t *lpc_out, int *shift)
00684 {
00685     int i;
00686     double cmax, error;
00687     int32_t qmax;
00688     int sh;
00689 
00690     /* define maximum levels */
00691     qmax = (1 << (precision - 1)) - 1;
00692 
00693     /* find maximum coefficient value */
00694     cmax = 0.0;
00695     for(i=0; i<order; i++) {
00696         cmax= FFMAX(cmax, fabs(lpc_in[i]));
00697     }
00698 
00699     /* if maximum value quantizes to zero, return all zeros */
00700     if(cmax * (1 << MAX_LPC_SHIFT) < 1.0) {
00701         *shift = 0;
00702         memset(lpc_out, 0, sizeof(int32_t) * order);
00703         return;
00704     }
00705 
00706     /* calculate level shift which scales max coeff to available bits */
00707     sh = MAX_LPC_SHIFT;
00708     while((cmax * (1 << sh) > qmax) && (sh > 0)) {
00709         sh--;
00710     }
00711 
00712     /* since negative shift values are unsupported in decoder, scale down
00713        coefficients instead */
00714     if(sh == 0 && cmax > qmax) {
00715         double scale = ((double)qmax) / cmax;
00716         for(i=0; i<order; i++) {
00717             lpc_in[i] *= scale;
00718         }
00719     }
00720 
00721     /* output quantized coefficients and level shift */
00722     error=0;
00723     for(i=0; i<order; i++) {
00724         error += lpc_in[i] * (1 << sh);
00725         lpc_out[i] = av_clip(lrintf(error), -qmax, qmax);
00726         error -= lpc_out[i];
00727     }
00728     *shift = sh;
00729 }
00730 
00731 static int estimate_best_order(double *ref, int max_order)
00732 {
00733     int i, est;
00734 
00735     est = 1;
00736     for(i=max_order-1; i>=0; i--) {
00737         if(ref[i] > 0.10) {
00738             est = i+1;
00739             break;
00740         }
00741     }
00742     return est;
00743 }
00744 
00745 /**
00746  * Calculate LPC coefficients for multiple orders
00747  */
00748 static int lpc_calc_coefs(FlacEncodeContext *s,
00749                           const int32_t *samples, int blocksize, int max_order,
00750                           int precision, int32_t coefs[][MAX_LPC_ORDER],
00751                           int *shift, int use_lpc, int omethod)
00752 {
00753     double autoc[MAX_LPC_ORDER+1];
00754     double ref[MAX_LPC_ORDER];
00755     double lpc[MAX_LPC_ORDER][MAX_LPC_ORDER];
00756     int i, j, pass;
00757     int opt_order;
00758 
00759     assert(max_order >= MIN_LPC_ORDER && max_order <= MAX_LPC_ORDER);
00760 
00761     if(use_lpc == 1){
00762         s->dsp.flac_compute_autocorr(samples, blocksize, max_order, autoc);
00763 
00764         compute_lpc_coefs(autoc, max_order, lpc, ref);
00765     }else{
00766         LLSModel m[2];
00767         double var[MAX_LPC_ORDER+1], weight;
00768 
00769         for(pass=0; pass<use_lpc-1; pass++){
00770             av_init_lls(&m[pass&1], max_order);
00771 
00772             weight=0;
00773             for(i=max_order; i<blocksize; i++){
00774                 for(j=0; j<=max_order; j++)
00775                     var[j]= samples[i-j];
00776 
00777                 if(pass){
00778                     double eval, inv, rinv;
00779                     eval= av_evaluate_lls(&m[(pass-1)&1], var+1, max_order-1);
00780                     eval= (512>>pass) + fabs(eval - var[0]);
00781                     inv = 1/eval;
00782                     rinv = sqrt(inv);
00783                     for(j=0; j<=max_order; j++)
00784                         var[j] *= rinv;
00785                     weight += inv;
00786                 }else
00787                     weight++;
00788 
00789                 av_update_lls(&m[pass&1], var, 1.0);
00790             }
00791             av_solve_lls(&m[pass&1], 0.001, 0);
00792         }
00793 
00794         for(i=0; i<max_order; i++){
00795             for(j=0; j<max_order; j++)
00796                 lpc[i][j]= m[(pass-1)&1].coeff[i][j];
00797             ref[i]= sqrt(m[(pass-1)&1].variance[i] / weight) * (blocksize - max_order) / 4000;
00798         }
00799         for(i=max_order-1; i>0; i--)
00800             ref[i] = ref[i-1] - ref[i];
00801     }
00802     opt_order = max_order;
00803 
00804     if(omethod == ORDER_METHOD_EST) {
00805         opt_order = estimate_best_order(ref, max_order);
00806         i = opt_order-1;
00807         quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
00808     } else {
00809         for(i=0; i<max_order; i++) {
00810             quantize_lpc_coefs(lpc[i], i+1, precision, coefs[i], &shift[i]);
00811         }
00812     }
00813 
00814     return opt_order;
00815 }
00816 
00817 
00818 static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
00819 {
00820     assert(n > 0);
00821     memcpy(res, smp, n * sizeof(int32_t));
00822 }
00823 
00824 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
00825                                   int order)
00826 {
00827     int i;
00828 
00829     for(i=0; i<order; i++) {
00830         res[i] = smp[i];
00831     }
00832 
00833     if(order==0){
00834         for(i=order; i<n; i++)
00835             res[i]= smp[i];
00836     }else if(order==1){
00837         for(i=order; i<n; i++)
00838             res[i]= smp[i] - smp[i-1];
00839     }else if(order==2){
00840         int a = smp[order-1] - smp[order-2];
00841         for(i=order; i<n; i+=2) {
00842             int b = smp[i] - smp[i-1];
00843             res[i]= b - a;
00844             a = smp[i+1] - smp[i];
00845             res[i+1]= a - b;
00846         }
00847     }else if(order==3){
00848         int a = smp[order-1] - smp[order-2];
00849         int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
00850         for(i=order; i<n; i+=2) {
00851             int b = smp[i] - smp[i-1];
00852             int d = b - a;
00853             res[i]= d - c;
00854             a = smp[i+1] - smp[i];
00855             c = a - b;
00856             res[i+1]= c - d;
00857         }
00858     }else{
00859         int a = smp[order-1] - smp[order-2];
00860         int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
00861         int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
00862         for(i=order; i<n; i+=2) {
00863             int b = smp[i] - smp[i-1];
00864             int d = b - a;
00865             int f = d - c;
00866             res[i]= f - e;
00867             a = smp[i+1] - smp[i];
00868             c = a - b;
00869             e = c - d;
00870             res[i+1]= e - f;
00871         }
00872     }
00873 }
00874 
00875 #define LPC1(x) {\
00876     int c = coefs[(x)-1];\
00877     p0 += c*s;\
00878     s = smp[i-(x)+1];\
00879     p1 += c*s;\
00880 }
00881 
00882 static av_always_inline void encode_residual_lpc_unrolled(
00883     int32_t *res, const int32_t *smp, int n,
00884     int order, const int32_t *coefs, int shift, int big)
00885 {
00886     int i;
00887     for(i=order; i<n; i+=2) {
00888         int s = smp[i-order];
00889         int p0 = 0, p1 = 0;
00890         if(big) {
00891             switch(order) {
00892                 case 32: LPC1(32)
00893                 case 31: LPC1(31)
00894                 case 30: LPC1(30)
00895                 case 29: LPC1(29)
00896                 case 28: LPC1(28)
00897                 case 27: LPC1(27)
00898                 case 26: LPC1(26)
00899                 case 25: LPC1(25)
00900                 case 24: LPC1(24)
00901                 case 23: LPC1(23)
00902                 case 22: LPC1(22)
00903                 case 21: LPC1(21)
00904                 case 20: LPC1(20)
00905                 case 19: LPC1(19)
00906                 case 18: LPC1(18)
00907                 case 17: LPC1(17)
00908                 case 16: LPC1(16)
00909                 case 15: LPC1(15)
00910                 case 14: LPC1(14)
00911                 case 13: LPC1(13)
00912                 case 12: LPC1(12)
00913                 case 11: LPC1(11)
00914                 case 10: LPC1(10)
00915                 case  9: LPC1( 9)
00916                          LPC1( 8)
00917                          LPC1( 7)
00918                          LPC1( 6)
00919                          LPC1( 5)
00920                          LPC1( 4)
00921                          LPC1( 3)
00922                          LPC1( 2)
00923                          LPC1( 1)
00924             }
00925         } else {
00926             switch(order) {
00927                 case  8: LPC1( 8)
00928                 case  7: LPC1( 7)
00929                 case  6: LPC1( 6)
00930                 case  5: LPC1( 5)
00931                 case  4: LPC1( 4)
00932                 case  3: LPC1( 3)
00933                 case  2: LPC1( 2)
00934                 case  1: LPC1( 1)
00935             }
00936         }
00937         res[i  ] = smp[i  ] - (p0 >> shift);
00938         res[i+1] = smp[i+1] - (p1 >> shift);
00939     }
00940 }
00941 
00942 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
00943                                 int order, const int32_t *coefs, int shift)
00944 {
00945     int i;
00946     for(i=0; i<order; i++) {
00947         res[i] = smp[i];
00948     }
00949 #ifdef CONFIG_SMALL
00950     for(i=order; i<n; i+=2) {
00951         int j;
00952         int s = smp[i];
00953         int p0 = 0, p1 = 0;
00954         for(j=0; j<order; j++) {
00955             int c = coefs[j];
00956             p1 += c*s;
00957             s = smp[i-j-1];
00958             p0 += c*s;
00959         }
00960         res[i  ] = smp[i  ] - (p0 >> shift);
00961         res[i+1] = smp[i+1] - (p1 >> shift);
00962     }
00963 #else
00964     switch(order) {
00965         case  1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
00966         case  2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
00967         case  3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
00968         case  4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
00969         case  5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
00970         case  6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
00971         case  7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
00972         case  8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
00973         default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
00974     }
00975 #endif
00976 }
00977 
00978 static int encode_residual(FlacEncodeContext *ctx, int ch)
00979 {
00980     int i, n;
00981     int min_order, max_order, opt_order, precision, omethod;
00982     int min_porder, max_porder;
00983     FlacFrame *frame;
00984     FlacSubframe *sub;
00985     int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
00986     int shift[MAX_LPC_ORDER];
00987     int32_t *res, *smp;
00988 
00989     frame = &ctx->frame;
00990     sub = &frame->subframes[ch];
00991     res = sub->residual;
00992     smp = sub->samples;
00993     n = frame->blocksize;
00994 
00995     /* CONSTANT */
00996     for(i=1; i<n; i++) {
00997         if(smp[i] != smp[0]) break;
00998     }
00999     if(i == n) {
01000         sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
01001         res[0] = smp[0];
01002         return sub->obits;
01003     }
01004 
01005     /* VERBATIM */
01006     if(n < 5) {
01007         sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
01008         encode_residual_verbatim(res, smp, n);
01009         return sub->obits * n;
01010     }
01011 
01012     min_order = ctx->options.min_prediction_order;
01013     max_order = ctx->options.max_prediction_order;
01014     min_porder = ctx->options.min_partition_order;
01015     max_porder = ctx->options.max_partition_order;
01016     precision = ctx->options.lpc_coeff_precision;
01017     omethod = ctx->options.prediction_order_method;
01018 
01019     /* FIXED */
01020     if(!ctx->options.use_lpc || max_order == 0 || (n <= max_order)) {
01021         uint32_t bits[MAX_FIXED_ORDER+1];
01022         if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;
01023         opt_order = 0;
01024         bits[0] = UINT32_MAX;
01025         for(i=min_order; i<=max_order; i++) {
01026             encode_residual_fixed(res, smp, n, i);
01027             bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res,
01028                                              n, i, sub->obits);
01029             if(bits[i] < bits[opt_order]) {
01030                 opt_order = i;
01031             }
01032         }
01033         sub->order = opt_order;
01034         sub->type = FLAC_SUBFRAME_FIXED;
01035         sub->type_code = sub->type | sub->order;
01036         if(sub->order != max_order) {
01037             encode_residual_fixed(res, smp, n, sub->order);
01038             return calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res, n,
01039                                           sub->order, sub->obits);
01040         }
01041         return bits[sub->order];
01042     }
01043 
01044     /* LPC */
01045     opt_order = lpc_calc_coefs(ctx, smp, n, max_order, precision, coefs, shift, ctx->options.use_lpc, omethod);
01046 
01047     if(omethod == ORDER_METHOD_2LEVEL ||
01048        omethod == ORDER_METHOD_4LEVEL ||
01049        omethod == ORDER_METHOD_8LEVEL) {
01050         int levels = 1 << omethod;
01051         uint32_t bits[levels];
01052         int order;
01053         int opt_index = levels-1;
01054         opt_order = max_order-1;
01055         bits[opt_index] = UINT32_MAX;
01056         for(i=levels-1; i>=0; i--) {
01057             order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
01058             if(order < 0) order = 0;
01059             encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
01060             bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
01061                                            res, n, order+1, sub->obits, precision);
01062             if(bits[i] < bits[opt_index]) {
01063                 opt_index = i;
01064                 opt_order = order;
01065             }
01066         }
01067         opt_order++;
01068     } else if(omethod == ORDER_METHOD_SEARCH) {
01069         // brute-force optimal order search
01070         uint32_t bits[MAX_LPC_ORDER];
01071         opt_order = 0;
01072         bits[0] = UINT32_MAX;
01073         for(i=min_order-1; i<max_order; i++) {
01074             encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
01075             bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
01076                                            res, n, i+1, sub->obits, precision);
01077             if(bits[i] < bits[opt_order]) {
01078                 opt_order = i;
01079             }
01080         }
01081         opt_order++;
01082     } else if(omethod == ORDER_METHOD_LOG) {
01083         uint32_t bits[MAX_LPC_ORDER];
01084         int step;
01085 
01086         opt_order= min_order - 1 + (max_order-min_order)/3;
01087         memset(bits, -1, sizeof(bits));
01088 
01089         for(step=16 ;step; step>>=1){
01090             int last= opt_order;
01091             for(i=last-step; i<=last+step; i+= step){
01092                 if(i<min_order-1 || i>=max_order || bits[i] < UINT32_MAX)
01093                     continue;
01094                 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
01095                 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
01096                                             res, n, i+1, sub->obits, precision);
01097                 if(bits[i] < bits[opt_order])
01098                     opt_order= i;
01099             }
01100         }
01101         opt_order++;
01102     }
01103 
01104     sub->order = opt_order;
01105     sub->type = FLAC_SUBFRAME_LPC;
01106     sub->type_code = sub->type | (sub->order-1);
01107     sub->shift = shift[sub->order-1];
01108     for(i=0; i<sub->order; i++) {
01109         sub->coefs[i] = coefs[sub->order-1][i];
01110     }
01111     encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
01112     return calc_rice_params_lpc(&sub->rc, min_porder, max_porder, res, n, sub->order,
01113