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

libavcodec/flacenc.c

Go to the documentation of this file.
00001 
00022 #include "libavutil/crc.h"
00023 #include "libavutil/md5.h"
00024 #include "libavutil/opt.h"
00025 #include "avcodec.h"
00026 #include "get_bits.h"
00027 #include "golomb.h"
00028 #include "lpc.h"
00029 #include "flac.h"
00030 #include "flacdata.h"
00031 
00032 #define FLAC_SUBFRAME_CONSTANT  0
00033 #define FLAC_SUBFRAME_VERBATIM  1
00034 #define FLAC_SUBFRAME_FIXED     8
00035 #define FLAC_SUBFRAME_LPC      32
00036 
00037 #define MAX_FIXED_ORDER     4
00038 #define MAX_PARTITION_ORDER 8
00039 #define MAX_PARTITIONS     (1 << MAX_PARTITION_ORDER)
00040 #define MAX_LPC_PRECISION  15
00041 #define MAX_LPC_SHIFT      15
00042 #define MAX_RICE_PARAM     14
00043 
00044 typedef struct CompressionOptions {
00045     int compression_level;
00046     int block_time_ms;
00047     enum FFLPCType lpc_type;
00048     int lpc_passes;
00049     int lpc_coeff_precision;
00050     int min_prediction_order;
00051     int max_prediction_order;
00052     int prediction_order_method;
00053     int min_partition_order;
00054     int max_partition_order;
00055 } CompressionOptions;
00056 
00057 typedef struct RiceContext {
00058     int porder;
00059     int params[MAX_PARTITIONS];
00060 } RiceContext;
00061 
00062 typedef struct FlacSubframe {
00063     int type;
00064     int type_code;
00065     int obits;
00066     int order;
00067     int32_t coefs[MAX_LPC_ORDER];
00068     int shift;
00069     RiceContext rc;
00070     int32_t samples[FLAC_MAX_BLOCKSIZE];
00071     int32_t residual[FLAC_MAX_BLOCKSIZE+1];
00072 } FlacSubframe;
00073 
00074 typedef struct FlacFrame {
00075     FlacSubframe subframes[FLAC_MAX_CHANNELS];
00076     int blocksize;
00077     int bs_code[2];
00078     uint8_t crc8;
00079     int ch_mode;
00080     int verbatim_only;
00081 } FlacFrame;
00082 
00083 typedef struct FlacEncodeContext {
00084     AVClass *class;
00085     PutBitContext pb;
00086     int channels;
00087     int samplerate;
00088     int sr_code[2];
00089     int max_blocksize;
00090     int min_framesize;
00091     int max_framesize;
00092     int max_encoded_framesize;
00093     uint32_t frame_count;
00094     uint64_t sample_count;
00095     uint8_t md5sum[16];
00096     FlacFrame frame;
00097     CompressionOptions options;
00098     AVCodecContext *avctx;
00099     LPCContext lpc_ctx;
00100     struct AVMD5 *md5ctx;
00101 } FlacEncodeContext;
00102 
00103 
00107 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
00108 {
00109     PutBitContext pb;
00110 
00111     memset(header, 0, FLAC_STREAMINFO_SIZE);
00112     init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
00113 
00114     /* streaminfo metadata block */
00115     put_bits(&pb, 16, s->max_blocksize);
00116     put_bits(&pb, 16, s->max_blocksize);
00117     put_bits(&pb, 24, s->min_framesize);
00118     put_bits(&pb, 24, s->max_framesize);
00119     put_bits(&pb, 20, s->samplerate);
00120     put_bits(&pb, 3, s->channels-1);
00121     put_bits(&pb, 5, 15);       /* bits per sample - 1 */
00122     /* write 36-bit sample count in 2 put_bits() calls */
00123     put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
00124     put_bits(&pb, 12,  s->sample_count & 0x000000FFFLL);
00125     flush_put_bits(&pb);
00126     memcpy(&header[18], s->md5sum, 16);
00127 }
00128 
00129 
00134 static int select_blocksize(int samplerate, int block_time_ms)
00135 {
00136     int i;
00137     int target;
00138     int blocksize;
00139 
00140     assert(samplerate > 0);
00141     blocksize = ff_flac_blocksize_table[1];
00142     target    = (samplerate * block_time_ms) / 1000;
00143     for (i = 0; i < 16; i++) {
00144         if (target >= ff_flac_blocksize_table[i] &&
00145             ff_flac_blocksize_table[i] > blocksize) {
00146             blocksize = ff_flac_blocksize_table[i];
00147         }
00148     }
00149     return blocksize;
00150 }
00151 
00152 
00153 static av_cold void dprint_compression_options(FlacEncodeContext *s)
00154 {
00155     AVCodecContext     *avctx = s->avctx;
00156     CompressionOptions *opt   = &s->options;
00157 
00158     av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
00159 
00160     switch (opt->lpc_type) {
00161     case FF_LPC_TYPE_NONE:
00162         av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
00163         break;
00164     case FF_LPC_TYPE_FIXED:
00165         av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
00166         break;
00167     case FF_LPC_TYPE_LEVINSON:
00168         av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
00169         break;
00170     case FF_LPC_TYPE_CHOLESKY:
00171         av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
00172                opt->lpc_passes, opt->lpc_passes == 1 ? "" : "es");
00173         break;
00174     }
00175 
00176     av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
00177            opt->min_prediction_order, opt->max_prediction_order);
00178 
00179     switch (opt->prediction_order_method) {
00180     case ORDER_METHOD_EST:
00181         av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
00182         break;
00183     case ORDER_METHOD_2LEVEL:
00184         av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
00185         break;
00186     case ORDER_METHOD_4LEVEL:
00187         av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
00188         break;
00189     case ORDER_METHOD_8LEVEL:
00190         av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
00191         break;
00192     case ORDER_METHOD_SEARCH:
00193         av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
00194         break;
00195     case ORDER_METHOD_LOG:
00196         av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
00197         break;
00198     }
00199 
00200 
00201     av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
00202            opt->min_partition_order, opt->max_partition_order);
00203 
00204     av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
00205 
00206     av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
00207            opt->lpc_coeff_precision);
00208 }
00209 
00210 
00211 static av_cold int flac_encode_init(AVCodecContext *avctx)
00212 {
00213     int freq = avctx->sample_rate;
00214     int channels = avctx->channels;
00215     FlacEncodeContext *s = avctx->priv_data;
00216     int i, level, ret;
00217     uint8_t *streaminfo;
00218 
00219     s->avctx = avctx;
00220 
00221     if (avctx->sample_fmt != AV_SAMPLE_FMT_S16)
00222         return -1;
00223 
00224     if (channels < 1 || channels > FLAC_MAX_CHANNELS)
00225         return -1;
00226     s->channels = channels;
00227 
00228     /* find samplerate in table */
00229     if (freq < 1)
00230         return -1;
00231     for (i = 4; i < 12; i++) {
00232         if (freq == ff_flac_sample_rate_table[i]) {
00233             s->samplerate = ff_flac_sample_rate_table[i];
00234             s->sr_code[0] = i;
00235             s->sr_code[1] = 0;
00236             break;
00237         }
00238     }
00239     /* if not in table, samplerate is non-standard */
00240     if (i == 12) {
00241         if (freq % 1000 == 0 && freq < 255000) {
00242             s->sr_code[0] = 12;
00243             s->sr_code[1] = freq / 1000;
00244         } else if (freq % 10 == 0 && freq < 655350) {
00245             s->sr_code[0] = 14;
00246             s->sr_code[1] = freq / 10;
00247         } else if (freq < 65535) {
00248             s->sr_code[0] = 13;
00249             s->sr_code[1] = freq;
00250         } else {
00251             return -1;
00252         }
00253         s->samplerate = freq;
00254     }
00255 
00256     /* set compression option defaults based on avctx->compression_level */
00257     if (avctx->compression_level < 0)
00258         s->options.compression_level = 5;
00259     else
00260         s->options.compression_level = avctx->compression_level;
00261 
00262     level = s->options.compression_level;
00263     if (level > 12) {
00264         av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
00265                s->options.compression_level);
00266         return -1;
00267     }
00268 
00269     s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
00270 
00271     if (s->options.lpc_type == FF_LPC_TYPE_DEFAULT)
00272         s->options.lpc_type  = ((int[]){ FF_LPC_TYPE_FIXED,    FF_LPC_TYPE_FIXED,    FF_LPC_TYPE_FIXED,
00273                                          FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
00274                                          FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
00275                                          FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON, FF_LPC_TYPE_LEVINSON,
00276                                          FF_LPC_TYPE_LEVINSON})[level];
00277 
00278     s->options.min_prediction_order = ((int[]){  2,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1})[level];
00279     s->options.max_prediction_order = ((int[]){  3,  4,  4,  6,  8,  8,  8,  8, 12, 12, 12, 32, 32})[level];
00280 
00281     if (s->options.prediction_order_method < 0)
00282         s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST,    ORDER_METHOD_EST,    ORDER_METHOD_EST,
00283                                                        ORDER_METHOD_EST,    ORDER_METHOD_EST,    ORDER_METHOD_EST,
00284                                                        ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG,    ORDER_METHOD_4LEVEL,
00285                                                        ORDER_METHOD_LOG,    ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
00286                                                        ORDER_METHOD_SEARCH})[level];
00287 
00288     if (s->options.min_partition_order > s->options.max_partition_order) {
00289         av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
00290                s->options.min_partition_order, s->options.max_partition_order);
00291         return AVERROR(EINVAL);
00292     }
00293     if (s->options.min_partition_order < 0)
00294         s->options.min_partition_order = ((int[]){  2,  2,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0})[level];
00295     if (s->options.max_partition_order < 0)
00296         s->options.max_partition_order = ((int[]){  2,  2,  3,  3,  3,  8,  8,  8,  8,  8,  8,  8,  8})[level];
00297 
00298     /* set compression option overrides from AVCodecContext */
00299 #if FF_API_USE_LPC
00300     /* for compatibility with deprecated AVCodecContext.use_lpc */
00301     if (avctx->use_lpc == 0) {
00302         s->options.lpc_type = AV_LPC_TYPE_FIXED;
00303     } else if (avctx->use_lpc == 1) {
00304         s->options.lpc_type = AV_LPC_TYPE_LEVINSON;
00305     } else if (avctx->use_lpc > 1) {
00306         s->options.lpc_type   = AV_LPC_TYPE_CHOLESKY;
00307         s->options.lpc_passes = avctx->use_lpc - 1;
00308     }
00309 #endif
00310 #if FF_API_FLAC_GLOBAL_OPTS
00311     if (avctx->lpc_type > FF_LPC_TYPE_DEFAULT) {
00312         if (avctx->lpc_type > FF_LPC_TYPE_CHOLESKY) {
00313             av_log(avctx, AV_LOG_ERROR, "unknown lpc type: %d\n", avctx->lpc_type);
00314             return -1;
00315         }
00316         s->options.lpc_type = avctx->lpc_type;
00317         if (s->options.lpc_type == FF_LPC_TYPE_CHOLESKY) {
00318             if (avctx->lpc_passes < 0) {
00319                 // default number of passes for Cholesky
00320                 s->options.lpc_passes = 2;
00321             } else if (avctx->lpc_passes == 0) {
00322                 av_log(avctx, AV_LOG_ERROR, "invalid number of lpc passes: %d\n",
00323                        avctx->lpc_passes);
00324                 return -1;
00325             } else {
00326                 s->options.lpc_passes = avctx->lpc_passes;
00327             }
00328         }
00329     }
00330 #endif
00331 
00332     if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
00333         s->options.min_prediction_order = 0;
00334     } else if (avctx->min_prediction_order >= 0) {
00335         if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
00336             if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
00337                 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
00338                        avctx->min_prediction_order);
00339                 return -1;
00340             }
00341         } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
00342                    avctx->min_prediction_order > MAX_LPC_ORDER) {
00343             av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
00344                    avctx->min_prediction_order);
00345             return -1;
00346         }
00347         s->options.min_prediction_order = avctx->min_prediction_order;
00348     }
00349     if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
00350         s->options.max_prediction_order = 0;
00351     } else if (avctx->max_prediction_order >= 0) {
00352         if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
00353             if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
00354                 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
00355                        avctx->max_prediction_order);
00356                 return -1;
00357             }
00358         } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
00359                    avctx->max_prediction_order > MAX_LPC_ORDER) {
00360             av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
00361                    avctx->max_prediction_order);
00362             return -1;
00363         }
00364         s->options.max_prediction_order = avctx->max_prediction_order;
00365     }
00366     if (s->options.max_prediction_order < s->options.min_prediction_order) {
00367         av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
00368                s->options.min_prediction_order, s->options.max_prediction_order);
00369         return -1;
00370     }
00371 
00372 #if FF_API_FLAC_GLOBAL_OPTS
00373     if (avctx->prediction_order_method >= 0) {
00374         if (avctx->prediction_order_method > ORDER_METHOD_LOG) {
00375             av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n",
00376                    avctx->prediction_order_method);
00377             return -1;
00378         }
00379         s->options.prediction_order_method = avctx->prediction_order_method;
00380     }
00381 
00382     if (avctx->min_partition_order >= 0) {
00383         if (avctx->min_partition_order > MAX_PARTITION_ORDER) {
00384             av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n",
00385                    avctx->min_partition_order);
00386             return -1;
00387         }
00388         s->options.min_partition_order = avctx->min_partition_order;
00389     }
00390     if (avctx->max_partition_order >= 0) {
00391         if (avctx->max_partition_order > MAX_PARTITION_ORDER) {
00392             av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n",
00393                    avctx->max_partition_order);
00394             return -1;
00395         }
00396         s->options.max_partition_order = avctx->max_partition_order;
00397     }
00398     if (s->options.max_partition_order < s->options.min_partition_order) {
00399         av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
00400                s->options.min_partition_order, s->options.max_partition_order);
00401         return -1;
00402     }
00403 #endif
00404 
00405     if (avctx->frame_size > 0) {
00406         if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
00407                 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
00408             av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
00409                    avctx->frame_size);
00410             return -1;
00411         }
00412     } else {
00413         s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
00414     }
00415     s->max_blocksize = s->avctx->frame_size;
00416 
00417 #if FF_API_FLAC_GLOBAL_OPTS
00418     /* set LPC precision */
00419     if (avctx->lpc_coeff_precision > 0) {
00420         if (avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
00421             av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
00422                    avctx->lpc_coeff_precision);
00423             return -1;
00424         }
00425         s->options.lpc_coeff_precision = avctx->lpc_coeff_precision;
00426     }
00427 #endif
00428 
00429     /* set maximum encoded frame size in verbatim mode */
00430     s->max_framesize = ff_flac_get_max_frame_size(s->avctx->frame_size,
00431                                                   s->channels, 16);
00432 
00433     /* initialize MD5 context */
00434     s->md5ctx = av_malloc(av_md5_size);
00435     if (!s->md5ctx)
00436         return AVERROR(ENOMEM);
00437     av_md5_init(s->md5ctx);
00438 
00439     streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
00440     if (!streaminfo)
00441         return AVERROR(ENOMEM);
00442     write_streaminfo(s, streaminfo);
00443     avctx->extradata = streaminfo;
00444     avctx->extradata_size = FLAC_STREAMINFO_SIZE;
00445 
00446     s->frame_count   = 0;
00447     s->min_framesize = s->max_framesize;
00448 
00449     avctx->coded_frame = avcodec_alloc_frame();
00450     if (!avctx->coded_frame)
00451         return AVERROR(ENOMEM);
00452 
00453     if (channels == 3 &&
00454             avctx->channel_layout != (AV_CH_LAYOUT_STEREO|AV_CH_FRONT_CENTER) ||
00455         channels == 4 &&
00456             avctx->channel_layout != AV_CH_LAYOUT_2_2 &&
00457             avctx->channel_layout != AV_CH_LAYOUT_QUAD ||
00458         channels == 5 &&
00459             avctx->channel_layout != AV_CH_LAYOUT_5POINT0 &&
00460             avctx->channel_layout != AV_CH_LAYOUT_5POINT0_BACK ||
00461         channels == 6 &&
00462             avctx->channel_layout != AV_CH_LAYOUT_5POINT1 &&
00463             avctx->channel_layout != AV_CH_LAYOUT_5POINT1_BACK) {
00464         if (avctx->channel_layout) {
00465             av_log(avctx, AV_LOG_ERROR, "Channel layout not supported by Flac, "
00466                                              "output stream will have incorrect "
00467                                              "channel layout.\n");
00468         } else {
00469             av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The encoder "
00470                                                "will use Flac channel layout for "
00471                                                "%d channels.\n", channels);
00472         }
00473     }
00474 
00475     ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
00476                       s->options.max_prediction_order, FF_LPC_TYPE_LEVINSON);
00477 
00478     dprint_compression_options(s);
00479 
00480     return ret;
00481 }
00482 
00483 
00484 static void init_frame(FlacEncodeContext *s)
00485 {
00486     int i, ch;
00487     FlacFrame *frame;
00488 
00489     frame = &s->frame;
00490 
00491     for (i = 0; i < 16; i++) {
00492         if (s->avctx->frame_size == ff_flac_blocksize_table[i]) {
00493             frame->blocksize  = ff_flac_blocksize_table[i];
00494             frame->bs_code[0] = i;
00495             frame->bs_code[1] = 0;
00496             break;
00497         }
00498     }
00499     if (i == 16) {
00500         frame->blocksize = s->avctx->frame_size;
00501         if (frame->blocksize <= 256) {
00502             frame->bs_code[0] = 6;
00503             frame->bs_code[1] = frame->blocksize-1;
00504         } else {
00505             frame->bs_code[0] = 7;
00506             frame->bs_code[1] = frame->blocksize-1;
00507         }
00508     }
00509 
00510     for (ch = 0; ch < s->channels; ch++)
00511         frame->subframes[ch].obits = 16;
00512 
00513     frame->verbatim_only = 0;
00514 }
00515 
00516 
00520 static void copy_samples(FlacEncodeContext *s, const int16_t *samples)
00521 {
00522     int i, j, ch;
00523     FlacFrame *frame;
00524 
00525     frame = &s->frame;
00526     for (i = 0, j = 0; i < frame->blocksize; i++)
00527         for (ch = 0; ch < s->channels; ch++, j++)
00528             frame->subframes[ch].samples[i] = samples[j];
00529 }
00530 
00531 
00532 static int rice_count_exact(int32_t *res, int n, int k)
00533 {
00534     int i;
00535     int count = 0;
00536 
00537     for (i = 0; i < n; i++) {
00538         int32_t v = -2 * res[i] - 1;
00539         v ^= v >> 31;
00540         count += (v >> k) + 1 + k;
00541     }
00542     return count;
00543 }
00544 
00545 
00546 static int subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,
00547                                 int pred_order)
00548 {
00549     int p, porder, psize;
00550     int i, part_end;
00551     int count = 0;
00552 
00553     /* subframe header */
00554     count += 8;
00555 
00556     /* subframe */
00557     if (sub->type == FLAC_SUBFRAME_CONSTANT) {
00558         count += sub->obits;
00559     } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
00560         count += s->frame.blocksize * sub->obits;
00561     } else {
00562         /* warm-up samples */
00563         count += pred_order * sub->obits;
00564 
00565         /* LPC coefficients */
00566         if (sub->type == FLAC_SUBFRAME_LPC)
00567             count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
00568 
00569         /* rice-encoded block */
00570         count += 2;
00571 
00572         /* partition order */
00573         porder = sub->rc.porder;
00574         psize  = s->frame.blocksize >> porder;
00575         count += 4;
00576 
00577         /* residual */
00578         i        = pred_order;
00579         part_end = psize;
00580         for (p = 0; p < 1 << porder; p++) {
00581             int k = sub->rc.params[p];
00582             count += 4;
00583             count += rice_count_exact(&sub->residual[i], part_end - i, k);
00584             i = part_end;
00585             part_end = FFMIN(s->frame.blocksize, part_end + psize);
00586         }
00587     }
00588 
00589     return count;
00590 }
00591 
00592 
00593 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
00594 
00598 static int find_optimal_param(uint32_t sum, int n)
00599 {
00600     int k;
00601     uint32_t sum2;
00602 
00603     if (sum <= n >> 1)
00604         return 0;
00605     sum2 = sum - (n >> 1);
00606     k    = av_log2(n < 256 ? FASTDIV(sum2, n) : sum2 / n);
00607     return FFMIN(k, MAX_RICE_PARAM);
00608 }
00609 
00610 
00611 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
00612                                          uint32_t *sums, int n, int pred_order)
00613 {
00614     int i;
00615     int k, cnt, part;
00616     uint32_t all_bits;
00617 
00618     part     = (1 << porder);
00619     all_bits = 4 * part;
00620 
00621     cnt = (n >> porder) - pred_order;
00622     for (i = 0; i < part; i++) {
00623         k = find_optimal_param(sums[i], cnt);
00624         rc->params[i] = k;
00625         all_bits += rice_encode_count(sums[i], cnt, k);
00626         cnt = n >> porder;
00627     }
00628 
00629     rc->porder = porder;
00630 
00631     return all_bits;
00632 }
00633 
00634 
00635 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
00636                       uint32_t sums[][MAX_PARTITIONS])
00637 {
00638     int i, j;
00639     int parts;
00640     uint32_t *res, *res_end;
00641 
00642     /* sums for highest level */
00643     parts   = (1 << pmax);
00644     res     = &data[pred_order];
00645     res_end = &data[n >> pmax];
00646     for (i = 0; i < parts; i++) {
00647         uint32_t sum = 0;
00648         while (res < res_end)
00649             sum += *(res++);
00650         sums[pmax][i] = sum;
00651         res_end += n >> pmax;
00652     }
00653     /* sums for lower levels */
00654     for (i = pmax - 1; i >= pmin; i--) {
00655         parts = (1 << i);
00656         for (j = 0; j < parts; j++)
00657             sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
00658     }
00659 }
00660 
00661 
00662 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
00663                                  int32_t *data, int n, int pred_order)
00664 {
00665     int i;
00666     uint32_t bits[MAX_PARTITION_ORDER+1];
00667     int opt_porder;
00668     RiceContext tmp_rc;
00669     uint32_t *udata;
00670     uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
00671 
00672     assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
00673     assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
00674     assert(pmin <= pmax);
00675 
00676     udata = av_malloc(n * sizeof(uint32_t));
00677     for (i = 0; i < n; i++)
00678         udata[i] = (2*data[i]) ^ (data[i]>>31);
00679 
00680     calc_sums(pmin, pmax, udata, n, pred_order, sums);
00681 
00682     opt_porder = pmin;
00683     bits[pmin] = UINT32_MAX;
00684     for (i = pmin; i <= pmax; i++) {
00685         bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
00686         if (bits[i] <= bits[opt_porder]) {
00687             opt_porder = i;
00688             *rc = tmp_rc;
00689         }
00690     }
00691 
00692     av_freep(&udata);
00693     return bits[opt_porder];
00694 }
00695 
00696 
00697 static int get_max_p_order(int max_porder, int n, int order)
00698 {
00699     int porder = FFMIN(max_porder, av_log2(n^(n-1)));
00700     if (order > 0)
00701         porder = FFMIN(porder, av_log2(n/order));
00702     return porder;
00703 }
00704 
00705 
00706 static uint32_t find_subframe_rice_params(FlacEncodeContext *s,
00707                                           FlacSubframe *sub, int pred_order)
00708 {
00709     int pmin = get_max_p_order(s->options.min_partition_order,
00710                                s->frame.blocksize, pred_order);
00711     int pmax = get_max_p_order(s->options.max_partition_order,
00712                                s->frame.blocksize, pred_order);
00713 
00714     uint32_t bits = 8 + pred_order * sub->obits + 2 + 4;
00715     if (sub->type == FLAC_SUBFRAME_LPC)
00716         bits += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
00717     bits += calc_rice_params(&sub->rc, pmin, pmax, sub->residual,
00718                              s->frame.blocksize, pred_order);
00719     return bits;
00720 }
00721 
00722 
00723 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
00724                                   int order)
00725 {
00726     int i;
00727 
00728     for (i = 0; i < order; i++)
00729         res[i] = smp[i];
00730 
00731     if (order == 0) {
00732         for (i = order; i < n; i++)
00733             res[i] = smp[i];
00734     } else if (order == 1) {
00735         for (i = order; i < n; i++)
00736             res[i] = smp[i] - smp[i-1];
00737     } else if (order == 2) {
00738         int a = smp[order-1] - smp[order-2];
00739         for (i = order; i < n; i += 2) {
00740             int b    = smp[i  ] - smp[i-1];
00741             res[i]   = b - a;
00742             a        = smp[i+1] - smp[i  ];
00743             res[i+1] = a - b;
00744         }
00745     } else if (order == 3) {
00746         int a = smp[order-1] -   smp[order-2];
00747         int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
00748         for (i = order; i < n; i += 2) {
00749             int b    = smp[i  ] - smp[i-1];
00750             int d    = b - a;
00751             res[i]   = d - c;
00752             a        = smp[i+1] - smp[i  ];
00753             c        = a - b;
00754             res[i+1] = c - d;
00755         }
00756     } else {
00757         int a = smp[order-1] -   smp[order-2];
00758         int c = smp[order-1] - 2*smp[order-2] +   smp[order-3];
00759         int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
00760         for (i = order; i < n; i += 2) {
00761             int b    = smp[i  ] - smp[i-1];
00762             int d    = b - a;
00763             int f    = d - c;
00764             res[i  ] = f - e;
00765             a        = smp[i+1] - smp[i  ];
00766             c        = a - b;
00767             e        = c - d;
00768             res[i+1] = e - f;
00769         }
00770     }
00771 }
00772 
00773 
00774 #define LPC1(x) {\
00775     int c = coefs[(x)-1];\
00776     p0   += c * s;\
00777     s     = smp[i-(x)+1];\
00778     p1   += c * s;\
00779 }
00780 
00781 static av_always_inline void encode_residual_lpc_unrolled(int32_t *res,
00782                                     const int32_t *smp, int n, int order,
00783                                     const int32_t *coefs, int shift, int big)
00784 {
00785     int i;
00786     for (i = order; i < n; i += 2) {
00787         int s  = smp[i-order];
00788         int p0 = 0, p1 = 0;
00789         if (big) {
00790             switch (order) {
00791             case 32: LPC1(32)
00792             case 31: LPC1(31)
00793             case 30: LPC1(30)
00794             case 29: LPC1(29)
00795             case 28: LPC1(28)
00796             case 27: LPC1(27)
00797             case 26: LPC1(26)
00798             case 25: LPC1(25)
00799             case 24: LPC1(24)
00800             case 23: LPC1(23)
00801             case 22: LPC1(22)
00802             case 21: LPC1(21)
00803             case 20: LPC1(20)
00804             case 19: LPC1(19)
00805             case 18: LPC1(18)
00806             case 17: LPC1(17)
00807             case 16: LPC1(16)
00808             case 15: LPC1(15)
00809             case 14: LPC1(14)
00810             case 13: LPC1(13)
00811             case 12: LPC1(12)
00812             case 11: LPC1(11)
00813             case 10: LPC1(10)
00814             case  9: LPC1( 9)
00815                      LPC1( 8)
00816                      LPC1( 7)
00817                      LPC1( 6)
00818                      LPC1( 5)
00819                      LPC1( 4)
00820                      LPC1( 3)
00821                      LPC1( 2)
00822                      LPC1( 1)
00823             }
00824         } else {
00825             switch (order) {
00826             case  8: LPC1( 8)
00827             case  7: LPC1( 7)
00828             case  6: LPC1( 6)
00829             case  5: LPC1( 5)
00830             case  4: LPC1( 4)
00831             case  3: LPC1( 3)
00832             case  2: LPC1( 2)
00833             case  1: LPC1( 1)
00834             }
00835         }
00836         res[i  ] = smp[i  ] - (p0 >> shift);
00837         res[i+1] = smp[i+1] - (p1 >> shift);
00838     }
00839 }
00840 
00841 
00842 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
00843                                 int order, const int32_t *coefs, int shift)
00844 {
00845     int i;
00846     for (i = 0; i < order; i++)
00847         res[i] = smp[i];
00848 #if CONFIG_SMALL
00849     for (i = order; i < n; i += 2) {
00850         int j;
00851         int s  = smp[i];
00852         int p0 = 0, p1 = 0;
00853         for (j = 0; j < order; j++) {
00854             int c = coefs[j];
00855             p1   += c * s;
00856             s     = smp[i-j-1];
00857             p0   += c * s;
00858         }
00859         res[i  ] = smp[i  ] - (p0 >> shift);
00860         res[i+1] = smp[i+1] - (p1 >> shift);
00861     }
00862 #else
00863     switch (order) {
00864     case  1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
00865     case  2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
00866     case  3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
00867     case  4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
00868     case  5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
00869     case  6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
00870     case  7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
00871     case  8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
00872     default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
00873     }
00874 #endif
00875 }
00876 
00877 
00878 static int encode_residual_ch(FlacEncodeContext *s, int ch)
00879 {
00880     int i, n;
00881     int min_order, max_order, opt_order, omethod;
00882     FlacFrame *frame;
00883     FlacSubframe *sub;
00884     int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
00885     int shift[MAX_LPC_ORDER];
00886     int32_t *res, *smp;
00887 
00888     frame = &s->frame;
00889     sub   = &frame->subframes[ch];
00890     res   = sub->residual;
00891     smp   = sub->samples;
00892     n     = frame->blocksize;
00893 
00894     /* CONSTANT */
00895     for (i = 1; i < n; i++)
00896         if(smp[i] != smp[0])
00897             break;
00898     if (i == n) {
00899         sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
00900         res[0] = smp[0];
00901         return subframe_count_exact(s, sub, 0);
00902     }
00903 
00904     /* VERBATIM */
00905     if (frame->verbatim_only || n < 5) {
00906         sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
00907         memcpy(res, smp, n * sizeof(int32_t));
00908         return subframe_count_exact(s, sub, 0);
00909     }
00910 
00911     min_order  = s->options.min_prediction_order;
00912     max_order  = s->options.max_prediction_order;
00913     omethod    = s->options.prediction_order_method;
00914 
00915     /* FIXED */
00916     sub->type = FLAC_SUBFRAME_FIXED;
00917     if (s->options.lpc_type == FF_LPC_TYPE_NONE  ||
00918         s->options.lpc_type == FF_LPC_TYPE_FIXED || n <= max_order) {
00919         uint32_t bits[MAX_FIXED_ORDER+1];
00920         if (max_order > MAX_FIXED_ORDER)
00921             max_order = MAX_FIXED_ORDER;
00922         opt_order = 0;
00923         bits[0]   = UINT32_MAX;
00924         for (i = min_order; i <= max_order; i++) {
00925             encode_residual_fixed(res, smp, n, i);
00926             bits[i] = find_subframe_rice_params(s, sub, i);
00927             if (bits[i] < bits[opt_order])
00928                 opt_order = i;
00929         }
00930         sub->order     = opt_order;
00931         sub->type_code = sub->type | sub->order;
00932         if (sub->order != max_order) {
00933             encode_residual_fixed(res, smp, n, sub->order);
00934             find_subframe_rice_params(s, sub, sub->order);
00935         }
00936         return subframe_count_exact(s, sub, sub->order);
00937     }
00938 
00939     /* LPC */
00940     sub->type = FLAC_SUBFRAME_LPC;
00941     opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, smp, n, min_order, max_order,
00942                                   s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,
00943                                   s->options.lpc_passes, omethod,
00944                                   MAX_LPC_SHIFT, 0);
00945 
00946     if (omethod == ORDER_METHOD_2LEVEL ||
00947         omethod == ORDER_METHOD_4LEVEL ||
00948         omethod == ORDER_METHOD_8LEVEL) {
00949         int levels = 1 << omethod;
00950         uint32_t bits[1 << ORDER_METHOD_8LEVEL];
00951         int order       = -1;
00952         int opt_index   = levels-1;
00953         opt_order       = max_order-1;
00954         bits[opt_index] = UINT32_MAX;
00955         for (i = levels-1; i >= 0; i--) {
00956             int last_order = order;
00957             order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
00958             order = av_clip(order, min_order - 1, max_order - 1);
00959             if (order == last_order)
00960                 continue;
00961             encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
00962             bits[i] = find_subframe_rice_params(s, sub, order+1);
00963             if (bits[i] < bits[opt_index]) {
00964                 opt_index = i;
00965                 opt_order = order;
00966             }
00967         }
00968         opt_order++;
00969     } else if (omethod == ORDER_METHOD_SEARCH) {
00970         // brute-force optimal order search
00971         uint32_t bits[MAX_LPC_ORDER];
00972         opt_order = 0;
00973         bits[0]   = UINT32_MAX;
00974         for (i = min_order-1; i < max_order; i++) {
00975             encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
00976             bits[i] = find_subframe_rice_params(s, sub, i+1);
00977             if (bits[i] < bits[opt_order])
00978                 opt_order = i;
00979         }
00980         opt_order++;
00981     } else if (omethod == ORDER_METHOD_LOG) {
00982         uint32_t bits[MAX_LPC_ORDER];
00983         int step;
00984 
00985         opt_order = min_order - 1 + (max_order-min_order)/3;
00986         memset(bits, -1, sizeof(bits));
00987 
00988         for (step = 16; step; step >>= 1) {
00989             int last = opt_order;
00990             for (i = last-step; i <= last+step; i += step) {
00991                 if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
00992                     continue;
00993                 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
00994                 bits[i] = find_subframe_rice_params(s, sub, i+1);
00995                 if (bits[i] < bits[opt_order])
00996                     opt_order = i;
00997             }
00998         }
00999         opt_order++;
01000     }
01001 
01002     sub->order     = opt_order;
01003     sub->type_code = sub->type | (sub->order-1);
01004     sub->shift     = shift[sub->order-1];
01005     for (i = 0; i < sub->order; i++)
01006         sub->coefs[i] = coefs[sub->order-1][i];
01007 
01008     encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
01009 
01010     find_subframe_rice_params(s, sub, sub->order);
01011 
01012     return subframe_count_exact(s, sub, sub->order);
01013 }
01014 
01015 
01016 static int count_frame_header(FlacEncodeContext *s)
01017 {
01018     uint8_t av_unused tmp;
01019     int count;
01020 
01021     /*
01022     <14> Sync code
01023     <1>  Reserved
01024     <1>  Blocking strategy
01025     <4>  Block size in inter-channel samples
01026     <4>  Sample rate
01027     <4>  Channel assignment
01028     <3>  Sample size in bits
01029     <1>  Reserved
01030     */
01031     count = 32;
01032 
01033     /* coded frame number */
01034     PUT_UTF8(s->frame_count, tmp, count += 8;)
01035 
01036     /* explicit block size */
01037     if (s->frame.bs_code[0] == 6)
01038         count += 8;
01039     else if (s->frame.bs_code[0] == 7)
01040         count += 16;
01041 
01042     /* explicit sample rate */
01043     count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12)) * 8;
01044 
01045     /* frame header CRC-8 */
01046     count += 8;
01047 
01048     return count;
01049 }
01050 
01051 
01052 static int encode_frame(FlacEncodeContext *s)
01053 {
01054     int ch, count;
01055 
01056     count = count_frame_header(s);
01057 
01058     for (ch = 0; ch < s->channels; ch++)
01059         count += encode_residual_ch(s, ch);
01060 
01061     count += (8 - (count & 7)) & 7; // byte alignment
01062     count += 16;                    // CRC-16
01063 
01064     return count >> 3;
01065 }
01066 
01067 
01068 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
01069 {
01070     int i, best;
01071     int32_t lt, rt;
01072     uint64_t sum[4];
01073     uint64_t score[4];
01074     int k;
01075 
01076     /* calculate sum of 2nd order residual for each channel */
01077     sum[0] = sum[1] = sum[2] = sum[3] = 0;
01078     for (i = 2; i < n; i++) {
01079         lt = left_ch[i]  - 2*left_ch[i-1]  + left_ch[i-2];
01080         rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
01081         sum[2] += FFABS((lt + rt) >> 1);
01082         sum[3] += FFABS(lt - rt);
01083         sum[0] += FFABS(lt);
01084         sum[1] += FFABS(rt);
01085     }
01086     /* estimate bit counts */
01087     for (i = 0; i < 4; i++) {
01088         k      = find_optimal_param(2 * sum[i], n);
01089         sum[i] = rice_encode_count( 2 * sum[i], n, k);
01090     }
01091 
01092     /* calculate score for each mode */
01093     score[0] = sum[0] + sum[1];
01094     score[1] = sum[0] + sum[3];
01095     score[2] = sum[1] + sum[3];
01096     score[3] = sum[2] + sum[3];
01097 
01098     /* return mode with lowest score */
01099     best = 0;
01100     for (i = 1; i < 4; i++)
01101         if (score[i] < score[best])
01102             best = i;
01103     if (best == 0) {
01104         return FLAC_CHMODE_INDEPENDENT;
01105     } else if (best == 1) {
01106         return FLAC_CHMODE_LEFT_SIDE;
01107     } else if (best == 2) {
01108         return FLAC_CHMODE_RIGHT_SIDE;
01109     } else {
01110         return FLAC_CHMODE_MID_SIDE;
01111     }
01112 }
01113 
01114 
01118 static void channel_decorrelation(FlacEncodeContext *s)
01119 {
01120     FlacFrame *frame;
01121     int32_t *left, *right;
01122     int i, n;
01123 
01124     frame = &s->frame;
01125     n     = frame->blocksize;
01126     left  = frame->subframes[0].samples;
01127     right = frame->subframes[1].samples;
01128 
01129     if (s->channels != 2) {
01130         frame->ch_mode = FLAC_CHMODE_INDEPENDENT;
01131         return;
01132     }
01133 
01134     frame->ch_mode = estimate_stereo_mode(left, right, n);
01135 
01136     /* perform decorrelation and adjust bits-per-sample */
01137     if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
01138         return;
01139     if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
01140         int32_t tmp;
01141         for (i = 0; i < n; i++) {
01142             tmp      = left[i];
01143             left[i]  = (tmp + right[i]) >> 1;
01144             right[i] =  tmp - right[i];
01145         }
01146         frame->subframes[1].obits++;
01147     } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
01148         for (i = 0; i < n; i++)
01149             right[i] = left[i] - right[i];
01150         frame->subframes[1].obits++;
01151     } else {
01152         for (i = 0; i < n; i++)
01153             left[i] -= right[i];
01154         frame->subframes[0].obits++;
01155     }
01156 }
01157 
01158 
01159 static void write_utf8(PutBitContext *pb, uint32_t val)
01160 {
01161     uint8_t tmp;
01162     PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
01163 }
01164 
01165 
01166 static void write_frame_header(FlacEncodeContext *s)
01167 {
01168     FlacFrame *frame;
01169     int crc;
01170 
01171     frame = &s->frame;
01172 
01173     put_bits(&s->pb, 16, 0xFFF8);
01174     put_bits(&s->pb, 4, frame->bs_code[0]);
01175     put_bits(&s->pb, 4, s->sr_code[0]);
01176 
01177     if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
01178         put_bits(&s->pb, 4, s->channels-1);
01179     else
01180         put_bits(&s->pb, 4, frame->ch_mode);
01181 
01182     put_bits(&s->pb, 3, 4); /* bits-per-sample code */
01183     put_bits(&s->pb, 1, 0);
01184     write_utf8(&s->pb, s->frame_count);
01185 
01186     if (frame->bs_code[0] == 6)
01187         put_bits(&s->pb, 8, frame->bs_code[1]);
01188     else if (frame->bs_code[0] == 7)
01189         put_bits(&s->pb, 16, frame->bs_code[1]);
01190 
01191     if (s->sr_code[0] == 12)
01192         put_bits(&s->pb, 8, s->sr_code[1]);
01193     else if (s->sr_code[0] > 12)
01194         put_bits(&s->pb, 16, s->sr_code[1]);
01195 
01196     flush_put_bits(&s->pb);
01197     crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
01198                  put_bits_count(&s->pb) >> 3);
01199     put_bits(&s->pb, 8, crc);
01200 }
01201 
01202 
01203 static void write_subframes(FlacEncodeContext *s)
01204 {
01205     int ch;
01206 
01207     for (ch = 0; ch < s->channels; ch++) {
01208         FlacSubframe *sub = &s->frame.subframes[ch];
01209         int i, p, porder, psize;
01210         int32_t *part_end;
01211         int32_t *res       =  sub->residual;
01212         int32_t *frame_end = &sub->residual[s->frame.blocksize];
01213 
01214         /* subframe header */
01215         put_bits(&s->pb, 1, 0);
01216         put_bits(&s->pb, 6, sub->type_code);
01217         put_bits(&s->pb, 1, 0); /* no wasted bits */
01218 
01219         /* subframe */
01220         if (sub->type == FLAC_SUBFRAME_CONSTANT) {
01221             put_sbits(&s->pb, sub->obits, res[0]);
01222         } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
01223             while (res < frame_end)
01224                 put_sbits(&s->pb, sub->obits, *res++);
01225         } else {
01226             /* warm-up samples */
01227             for (i = 0; i < sub->order; i++)
01228                 put_sbits(&s->pb, sub->obits, *res++);
01229 
01230             /* LPC coefficients */
01231             if (sub->type == FLAC_SUBFRAME_LPC) {
01232                 int cbits = s->options.lpc_coeff_precision;
01233                 put_bits( &s->pb, 4, cbits-1);
01234                 put_sbits(&s->pb, 5, sub->shift);
01235                 for (i = 0; i < sub->order; i++)
01236                     put_sbits(&s->pb, cbits, sub->coefs[i]);
01237             }
01238 
01239             /* rice-encoded block */
01240             put_bits(&s->pb, 2, 0);
01241 
01242             /* partition order */
01243             porder  = sub->rc.porder;
01244             psize   = s->frame.blocksize >> porder;
01245             put_bits(&s->pb, 4, porder);
01246 
01247             /* residual */
01248             part_end  = &sub->residual[psize];
01249             for (p = 0; p < 1 << porder; p++) {
01250                 int k = sub->rc.params[p];
01251                 put_bits(&s->pb, 4, k);
01252                 while (res < part_end)
01253                     set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
01254                 part_end = FFMIN(frame_end, part_end + psize);
01255             }
01256         }
01257     }
01258 }
01259 
01260 
01261 static void write_frame_footer(FlacEncodeContext *s)
01262 {
01263     int crc;
01264     flush_put_bits(&s->pb);
01265     crc = av_bswap16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, s->pb.buf,
01266                             put_bits_count(&s->pb)>>3));
01267     put_bits(&s->pb, 16, crc);
01268     flush_put_bits(&s->pb);
01269 }
01270 
01271 
01272 static int write_frame(FlacEncodeContext *s, uint8_t *frame, int buf_size)
01273 {
01274     init_put_bits(&s->pb, frame, buf_size);
01275     write_frame_header(s);
01276     write_subframes(s);
01277     write_frame_footer(s);
01278     return put_bits_count(&s->pb) >> 3;
01279 }
01280 
01281 
01282 static void update_md5_sum(FlacEncodeContext *s, const int16_t *samples)
01283 {
01284 #if HAVE_BIGENDIAN
01285     int i;
01286     for (i = 0; i < s->frame.blocksize * s->channels; i++) {
01287         int16_t smp = av_le2ne16(samples[i]);
01288         av_md5_update(s->md5ctx, (uint8_t *)&smp, 2);
01289     }
01290 #else
01291     av_md5_update(s->md5ctx, (const uint8_t *)samples, s->frame.blocksize*s->channels*2);
01292 #endif
01293 }
01294 
01295 
01296 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
01297                              int buf_size, void *data)
01298 {
01299     FlacEncodeContext *s;
01300     const int16_t *samples = data;
01301     int frame_bytes, out_bytes;
01302 
01303     s = avctx->priv_data;
01304 
01305     /* when the last block is reached, update the header in extradata */
01306     if (!data) {
01307         s->max_framesize = s->max_encoded_framesize;
01308         av_md5_final(s->md5ctx, s->md5sum);
01309         write_streaminfo(s, avctx->extradata);
01310         return 0;
01311     }
01312 
01313     /* change max_framesize for small final frame */
01314     if (avctx->frame_size < s->frame.blocksize) {
01315         s->max_framesize = ff_flac_get_max_frame_size(avctx->frame_size,
01316                                                       s->channels, 16);
01317     }
01318 
01319     init_frame(s);
01320 
01321     copy_samples(s, samples);
01322 
01323     channel_decorrelation(s);
01324 
01325     frame_bytes = encode_frame(s);
01326 
01327     /* fallback to verbatim mode if the compressed frame is larger than it
01328        would be if encoded uncompressed. */
01329     if (frame_bytes > s->max_framesize) {
01330         s->frame.verbatim_only = 1;
01331         frame_bytes = encode_frame(s);
01332     }
01333 
01334     if (buf_size < frame_bytes) {
01335         av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");
01336         return 0;
01337     }
01338     out_bytes = write_frame(s, frame, buf_size);
01339 
01340     s->frame_count++;
01341     avctx->coded_frame->pts = s->sample_count;
01342     s->sample_count += avctx->frame_size;
01343     update_md5_sum(s, samples);
01344     if (out_bytes > s->max_encoded_framesize)
01345         s->max_encoded_framesize = out_bytes;
01346     if (out_bytes < s->min_framesize)
01347         s->min_framesize = out_bytes;
01348 
01349     return out_bytes;
01350 }
01351 
01352 
01353 static av_cold int flac_encode_close(AVCodecContext *avctx)
01354 {
01355     if (avctx->priv_data) {
01356         FlacEncodeContext *s = avctx->priv_data;
01357         av_freep(&s->md5ctx);
01358         ff_lpc_end(&s->lpc_ctx);
01359     }
01360     av_freep(&avctx->extradata);
01361     avctx->extradata_size = 0;
01362     av_freep(&avctx->coded_frame);
01363     return 0;
01364 }
01365 
01366 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
01367 static const AVOption options[] = {
01368 { "lpc_coeff_precision", "LPC coefficient precision", offsetof(FlacEncodeContext, options.lpc_coeff_precision), FF_OPT_TYPE_INT, {.dbl = 15 }, 0, MAX_LPC_PRECISION, FLAGS },
01369 { "lpc_type", "LPC algorithm", offsetof(FlacEncodeContext, options.lpc_type), FF_OPT_TYPE_INT, {.dbl = FF_LPC_TYPE_DEFAULT }, FF_LPC_TYPE_DEFAULT, FF_LPC_TYPE_NB-1, FLAGS, "lpc_type" },
01370 { "none",     NULL, 0, FF_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_NONE },     INT_MIN, INT_MAX, FLAGS, "lpc_type" },
01371 { "fixed",    NULL, 0, FF_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_FIXED },    INT_MIN, INT_MAX, FLAGS, "lpc_type" },
01372 { "levinson", NULL, 0, FF_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_LEVINSON }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
01373 { "cholesky", NULL, 0, FF_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_CHOLESKY }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
01374 { "lpc_passes", "Number of passes to use for Cholesky factorization during LPC analysis", offsetof(FlacEncodeContext, options.lpc_passes),  FF_OPT_TYPE_INT, {.dbl = -1 }, INT_MIN, INT_MAX, FLAGS },
01375 { "min_partition_order",  NULL, offsetof(FlacEncodeContext, options.min_partition_order),  FF_OPT_TYPE_INT, {.dbl = -1 },      -1, MAX_PARTITION_ORDER, FLAGS },
01376 { "max_partition_order",  NULL, offsetof(FlacEncodeContext, options.max_partition_order),  FF_OPT_TYPE_INT, {.dbl = -1 },      -1, MAX_PARTITION_ORDER, FLAGS },
01377 { "prediction_order_method", "Search method for selecting prediction order", offsetof(FlacEncodeContext, options.prediction_order_method), FF_OPT_TYPE_INT, {.dbl = -1 }, -1, ORDER_METHOD_LOG, FLAGS, "predm" },
01378 { "estimation", NULL, 0, FF_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_EST },    INT_MIN, INT_MAX, FLAGS, "predm" },
01379 { "2level",     NULL, 0, FF_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_2LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
01380 { "4level",     NULL, 0, FF_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_4LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
01381 { "8level",     NULL, 0, FF_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_8LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
01382 { "search",     NULL, 0, FF_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_SEARCH }, INT_MIN, INT_MAX, FLAGS, "predm" },
01383 { "log",        NULL, 0, FF_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_LOG },    INT_MIN, INT_MAX, FLAGS, "predm" },
01384 { NULL },
01385 };
01386 
01387 static const AVClass flac_encoder_class = {
01388     "FLAC encoder",
01389     av_default_item_name,
01390     options,
01391     LIBAVUTIL_VERSION_INT,
01392 };
01393 
01394 AVCodec ff_flac_encoder = {
01395     "flac",
01396     AVMEDIA_TYPE_AUDIO,
01397     CODEC_ID_FLAC,
01398     sizeof(FlacEncodeContext),
01399     flac_encode_init,
01400     flac_encode_frame,
01401     flac_encode_close,
01402     NULL,
01403     .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY | CODEC_CAP_LOSSLESS,
01404     .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
01405     .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
01406     .priv_class = &flac_encoder_class,
01407 };

Generated on Fri Feb 22 2013 07:24:26 for FFmpeg by  doxygen 1.7.1