]> git.sesse.net Git - ffmpeg/blob - libavcodec/ratecontrol.c
Merge commit 'b326755989b346d0d935e0628e8865f9b2951c30'
[ffmpeg] / libavcodec / ratecontrol.c
1 /*
2  * Rate control for video encoders
3  *
4  * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * Rate control for video encoders.
26  */
27
28 #include "libavutil/intmath.h"
29 #include "avcodec.h"
30 #include "dsputil.h"
31 #include "ratecontrol.h"
32 #include "mpegvideo.h"
33 #include "libavutil/eval.h"
34
35 #undef NDEBUG // Always check asserts, the speed effect is far too small to disable them.
36 #include <assert.h>
37
38 #ifndef M_E
39 #define M_E 2.718281828
40 #endif
41
42 static int init_pass2(MpegEncContext *s);
43 static double get_qscale(MpegEncContext *s, RateControlEntry *rce, double rate_factor, int frame_num);
44
45 void ff_write_pass1_stats(MpegEncContext *s){
46     snprintf(s->avctx->stats_out, 256, "in:%d out:%d type:%d q:%d itex:%d ptex:%d mv:%d misc:%d fcode:%d bcode:%d mc-var:%d var:%d icount:%d skipcount:%d hbits:%d;\n",
47              s->current_picture_ptr->f.display_picture_number, s->current_picture_ptr->f.coded_picture_number, s->pict_type,
48              s->current_picture.f.quality, s->i_tex_bits, s->p_tex_bits, s->mv_bits, s->misc_bits,
49              s->f_code, s->b_code, s->current_picture.mc_mb_var_sum, s->current_picture.mb_var_sum, s->i_count, s->skip_count, s->header_bits);
50 }
51
52 static double get_fps(AVCodecContext *avctx){
53     return 1.0 / av_q2d(avctx->time_base) / FFMAX(avctx->ticks_per_frame, 1);
54 }
55
56 static inline double qp2bits(RateControlEntry *rce, double qp){
57     if(qp<=0.0){
58         av_log(NULL, AV_LOG_ERROR, "qp<=0.0\n");
59     }
60     return rce->qscale * (double)(rce->i_tex_bits + rce->p_tex_bits+1)/ qp;
61 }
62
63 static inline double bits2qp(RateControlEntry *rce, double bits){
64     if(bits<0.9){
65         av_log(NULL, AV_LOG_ERROR, "bits<0.9\n");
66     }
67     return rce->qscale * (double)(rce->i_tex_bits + rce->p_tex_bits+1)/ bits;
68 }
69
70 int ff_rate_control_init(MpegEncContext *s)
71 {
72     RateControlContext *rcc= &s->rc_context;
73     int i, res;
74     static const char * const const_names[]={
75         "PI",
76         "E",
77         "iTex",
78         "pTex",
79         "tex",
80         "mv",
81         "fCode",
82         "iCount",
83         "mcVar",
84         "var",
85         "isI",
86         "isP",
87         "isB",
88         "avgQP",
89         "qComp",
90 /*        "lastIQP",
91         "lastPQP",
92         "lastBQP",
93         "nextNonBQP",*/
94         "avgIITex",
95         "avgPITex",
96         "avgPPTex",
97         "avgBPTex",
98         "avgTex",
99         NULL
100     };
101     static double (* const func1[])(void *, double)={
102         (void *)bits2qp,
103         (void *)qp2bits,
104         NULL
105     };
106     static const char * const func1_names[]={
107         "bits2qp",
108         "qp2bits",
109         NULL
110     };
111     emms_c();
112
113     if (!s->avctx->rc_max_available_vbv_use && s->avctx->rc_buffer_size) {
114         if (s->avctx->rc_max_rate) {
115             s->avctx->rc_max_available_vbv_use = av_clipf(s->avctx->rc_max_rate/(s->avctx->rc_buffer_size*get_fps(s->avctx)), 1.0/3, 1.0);
116         } else
117             s->avctx->rc_max_available_vbv_use = 1.0;
118     }
119
120     res = av_expr_parse(&rcc->rc_eq_eval, s->avctx->rc_eq ? s->avctx->rc_eq : "tex^qComp", const_names, func1_names, func1, NULL, NULL, 0, s->avctx);
121     if (res < 0) {
122         av_log(s->avctx, AV_LOG_ERROR, "Error parsing rc_eq \"%s\"\n", s->avctx->rc_eq);
123         return res;
124     }
125
126     for(i=0; i<5; i++){
127         rcc->pred[i].coeff= FF_QP2LAMBDA * 7.0;
128         rcc->pred[i].count= 1.0;
129
130         rcc->pred[i].decay= 0.4;
131         rcc->i_cplx_sum [i]=
132         rcc->p_cplx_sum [i]=
133         rcc->mv_bits_sum[i]=
134         rcc->qscale_sum [i]=
135         rcc->frame_count[i]= 1; // 1 is better because of 1/0 and such
136         rcc->last_qscale_for[i]=FF_QP2LAMBDA * 5;
137     }
138     rcc->buffer_index= s->avctx->rc_initial_buffer_occupancy;
139     if (!rcc->buffer_index)
140         rcc->buffer_index = s->avctx->rc_buffer_size * 3 / 4;
141
142     if(s->flags&CODEC_FLAG_PASS2){
143         int i;
144         char *p;
145
146         /* find number of pics */
147         p= s->avctx->stats_in;
148         for(i=-1; p; i++){
149             p= strchr(p+1, ';');
150         }
151         i+= s->max_b_frames;
152         if(i<=0 || i>=INT_MAX / sizeof(RateControlEntry))
153             return -1;
154         rcc->entry = av_mallocz(i*sizeof(RateControlEntry));
155         rcc->num_entries= i;
156
157         /* init all to skipped p frames (with b frames we might have a not encoded frame at the end FIXME) */
158         for(i=0; i<rcc->num_entries; i++){
159             RateControlEntry *rce= &rcc->entry[i];
160             rce->pict_type= rce->new_pict_type=AV_PICTURE_TYPE_P;
161             rce->qscale= rce->new_qscale=FF_QP2LAMBDA * 2;
162             rce->misc_bits= s->mb_num + 10;
163             rce->mb_var_sum= s->mb_num*100;
164         }
165
166         /* read stats */
167         p= s->avctx->stats_in;
168         for(i=0; i<rcc->num_entries - s->max_b_frames; i++){
169             RateControlEntry *rce;
170             int picture_number;
171             int e;
172             char *next;
173
174             next= strchr(p, ';');
175             if(next){
176                 (*next)=0; //sscanf in unbelievably slow on looong strings //FIXME copy / do not write
177                 next++;
178             }
179             e= sscanf(p, " in:%d ", &picture_number);
180
181             assert(picture_number >= 0);
182             assert(picture_number < rcc->num_entries);
183             rce= &rcc->entry[picture_number];
184
185             e+=sscanf(p, " in:%*d out:%*d type:%d q:%f itex:%d ptex:%d mv:%d misc:%d fcode:%d bcode:%d mc-var:%d var:%d icount:%d skipcount:%d hbits:%d",
186                    &rce->pict_type, &rce->qscale, &rce->i_tex_bits, &rce->p_tex_bits, &rce->mv_bits, &rce->misc_bits,
187                    &rce->f_code, &rce->b_code, &rce->mc_mb_var_sum, &rce->mb_var_sum, &rce->i_count, &rce->skip_count, &rce->header_bits);
188             if(e!=14){
189                 av_log(s->avctx, AV_LOG_ERROR, "statistics are damaged at line %d, parser out=%d\n", i, e);
190                 return -1;
191             }
192
193             p= next;
194         }
195
196         if(init_pass2(s) < 0) return -1;
197
198         //FIXME maybe move to end
199         if((s->flags&CODEC_FLAG_PASS2) && s->avctx->rc_strategy == FF_RC_STRATEGY_XVID) {
200 #if CONFIG_LIBXVID
201             return ff_xvid_rate_control_init(s);
202 #else
203             av_log(s->avctx, AV_LOG_ERROR, "Xvid ratecontrol requires libavcodec compiled with Xvid support.\n");
204             return -1;
205 #endif
206         }
207     }
208
209     if(!(s->flags&CODEC_FLAG_PASS2)){
210
211         rcc->short_term_qsum=0.001;
212         rcc->short_term_qcount=0.001;
213
214         rcc->pass1_rc_eq_output_sum= 0.001;
215         rcc->pass1_wanted_bits=0.001;
216
217         if(s->avctx->qblur > 1.0){
218             av_log(s->avctx, AV_LOG_ERROR, "qblur too large\n");
219             return -1;
220         }
221         /* init stuff with the user specified complexity */
222         if(s->avctx->rc_initial_cplx){
223             for(i=0; i<60*30; i++){
224                 double bits= s->avctx->rc_initial_cplx * (i/10000.0 + 1.0)*s->mb_num;
225                 RateControlEntry rce;
226
227                 if     (i%((s->gop_size+3)/4)==0) rce.pict_type= AV_PICTURE_TYPE_I;
228                 else if(i%(s->max_b_frames+1))    rce.pict_type= AV_PICTURE_TYPE_B;
229                 else                              rce.pict_type= AV_PICTURE_TYPE_P;
230
231                 rce.new_pict_type= rce.pict_type;
232                 rce.mc_mb_var_sum= bits*s->mb_num/100000;
233                 rce.mb_var_sum   = s->mb_num;
234                 rce.qscale   = FF_QP2LAMBDA * 2;
235                 rce.f_code   = 2;
236                 rce.b_code   = 1;
237                 rce.misc_bits= 1;
238
239                 if(s->pict_type== AV_PICTURE_TYPE_I){
240                     rce.i_count   = s->mb_num;
241                     rce.i_tex_bits= bits;
242                     rce.p_tex_bits= 0;
243                     rce.mv_bits= 0;
244                 }else{
245                     rce.i_count   = 0; //FIXME we do know this approx
246                     rce.i_tex_bits= 0;
247                     rce.p_tex_bits= bits*0.9;
248                     rce.mv_bits= bits*0.1;
249                 }
250                 rcc->i_cplx_sum [rce.pict_type] += rce.i_tex_bits*rce.qscale;
251                 rcc->p_cplx_sum [rce.pict_type] += rce.p_tex_bits*rce.qscale;
252                 rcc->mv_bits_sum[rce.pict_type] += rce.mv_bits;
253                 rcc->frame_count[rce.pict_type] ++;
254
255                 get_qscale(s, &rce, rcc->pass1_wanted_bits/rcc->pass1_rc_eq_output_sum, i);
256                 rcc->pass1_wanted_bits+= s->bit_rate/get_fps(s->avctx); //FIXME misbehaves a little for variable fps
257             }
258         }
259
260     }
261
262     return 0;
263 }
264
265 void ff_rate_control_uninit(MpegEncContext *s)
266 {
267     RateControlContext *rcc= &s->rc_context;
268     emms_c();
269
270     av_expr_free(rcc->rc_eq_eval);
271     av_freep(&rcc->entry);
272
273 #if CONFIG_LIBXVID
274     if((s->flags&CODEC_FLAG_PASS2) && s->avctx->rc_strategy == FF_RC_STRATEGY_XVID)
275         ff_xvid_rate_control_uninit(s);
276 #endif
277 }
278
279 int ff_vbv_update(MpegEncContext *s, int frame_size){
280     RateControlContext *rcc= &s->rc_context;
281     const double fps= get_fps(s->avctx);
282     const int buffer_size= s->avctx->rc_buffer_size;
283     const double min_rate= s->avctx->rc_min_rate/fps;
284     const double max_rate= s->avctx->rc_max_rate/fps;
285
286     av_dlog(s, "%d %f %d %f %f\n",
287             buffer_size, rcc->buffer_index, frame_size, min_rate, max_rate);
288     if(buffer_size){
289         int left;
290
291         rcc->buffer_index-= frame_size;
292         if(rcc->buffer_index < 0){
293             av_log(s->avctx, AV_LOG_ERROR, "rc buffer underflow\n");
294             rcc->buffer_index= 0;
295         }
296
297         left= buffer_size - rcc->buffer_index - 1;
298         rcc->buffer_index += av_clip(left, min_rate, max_rate);
299
300         if(rcc->buffer_index > buffer_size){
301             int stuffing= ceil((rcc->buffer_index - buffer_size)/8);
302
303             if(stuffing < 4 && s->codec_id == AV_CODEC_ID_MPEG4)
304                 stuffing=4;
305             rcc->buffer_index -= 8*stuffing;
306
307             if(s->avctx->debug & FF_DEBUG_RC)
308                 av_log(s->avctx, AV_LOG_DEBUG, "stuffing %d bytes\n", stuffing);
309
310             return stuffing;
311         }
312     }
313     return 0;
314 }
315
316 /**
317  * Modify the bitrate curve from pass1 for one frame.
318  */
319 static double get_qscale(MpegEncContext *s, RateControlEntry *rce, double rate_factor, int frame_num){
320     RateControlContext *rcc= &s->rc_context;
321     AVCodecContext *a= s->avctx;
322     double q, bits;
323     const int pict_type= rce->new_pict_type;
324     const double mb_num= s->mb_num;
325     int i;
326
327     double const_values[]={
328         M_PI,
329         M_E,
330         rce->i_tex_bits*rce->qscale,
331         rce->p_tex_bits*rce->qscale,
332         (rce->i_tex_bits + rce->p_tex_bits)*(double)rce->qscale,
333         rce->mv_bits/mb_num,
334         rce->pict_type == AV_PICTURE_TYPE_B ? (rce->f_code + rce->b_code)*0.5 : rce->f_code,
335         rce->i_count/mb_num,
336         rce->mc_mb_var_sum/mb_num,
337         rce->mb_var_sum/mb_num,
338         rce->pict_type == AV_PICTURE_TYPE_I,
339         rce->pict_type == AV_PICTURE_TYPE_P,
340         rce->pict_type == AV_PICTURE_TYPE_B,
341         rcc->qscale_sum[pict_type] / (double)rcc->frame_count[pict_type],
342         a->qcompress,
343 /*        rcc->last_qscale_for[AV_PICTURE_TYPE_I],
344         rcc->last_qscale_for[AV_PICTURE_TYPE_P],
345         rcc->last_qscale_for[AV_PICTURE_TYPE_B],
346         rcc->next_non_b_qscale,*/
347         rcc->i_cplx_sum[AV_PICTURE_TYPE_I] / (double)rcc->frame_count[AV_PICTURE_TYPE_I],
348         rcc->i_cplx_sum[AV_PICTURE_TYPE_P] / (double)rcc->frame_count[AV_PICTURE_TYPE_P],
349         rcc->p_cplx_sum[AV_PICTURE_TYPE_P] / (double)rcc->frame_count[AV_PICTURE_TYPE_P],
350         rcc->p_cplx_sum[AV_PICTURE_TYPE_B] / (double)rcc->frame_count[AV_PICTURE_TYPE_B],
351         (rcc->i_cplx_sum[pict_type] + rcc->p_cplx_sum[pict_type]) / (double)rcc->frame_count[pict_type],
352         0
353     };
354
355     bits = av_expr_eval(rcc->rc_eq_eval, const_values, rce);
356     if (isnan(bits)) {
357         av_log(s->avctx, AV_LOG_ERROR, "Error evaluating rc_eq \"%s\"\n", s->avctx->rc_eq);
358         return -1;
359     }
360
361     rcc->pass1_rc_eq_output_sum+= bits;
362     bits*=rate_factor;
363     if(bits<0.0) bits=0.0;
364     bits+= 1.0; //avoid 1/0 issues
365
366     /* user override */
367     for(i=0; i<s->avctx->rc_override_count; i++){
368         RcOverride *rco= s->avctx->rc_override;
369         if(rco[i].start_frame > frame_num) continue;
370         if(rco[i].end_frame   < frame_num) continue;
371
372         if(rco[i].qscale)
373             bits= qp2bits(rce, rco[i].qscale); //FIXME move at end to really force it?
374         else
375             bits*= rco[i].quality_factor;
376     }
377
378     q= bits2qp(rce, bits);
379
380     /* I/B difference */
381     if     (pict_type==AV_PICTURE_TYPE_I && s->avctx->i_quant_factor<0.0)
382         q= -q*s->avctx->i_quant_factor + s->avctx->i_quant_offset;
383     else if(pict_type==AV_PICTURE_TYPE_B && s->avctx->b_quant_factor<0.0)
384         q= -q*s->avctx->b_quant_factor + s->avctx->b_quant_offset;
385     if(q<1) q=1;
386
387     return q;
388 }
389
390 static double get_diff_limited_q(MpegEncContext *s, RateControlEntry *rce, double q){
391     RateControlContext *rcc= &s->rc_context;
392     AVCodecContext *a= s->avctx;
393     const int pict_type= rce->new_pict_type;
394     const double last_p_q    = rcc->last_qscale_for[AV_PICTURE_TYPE_P];
395     const double last_non_b_q= rcc->last_qscale_for[rcc->last_non_b_pict_type];
396
397     if     (pict_type==AV_PICTURE_TYPE_I && (a->i_quant_factor>0.0 || rcc->last_non_b_pict_type==AV_PICTURE_TYPE_P))
398         q= last_p_q    *FFABS(a->i_quant_factor) + a->i_quant_offset;
399     else if(pict_type==AV_PICTURE_TYPE_B && a->b_quant_factor>0.0)
400         q= last_non_b_q*    a->b_quant_factor  + a->b_quant_offset;
401     if(q<1) q=1;
402
403     /* last qscale / qdiff stuff */
404     if(rcc->last_non_b_pict_type==pict_type || pict_type!=AV_PICTURE_TYPE_I){
405         double last_q= rcc->last_qscale_for[pict_type];
406         const int maxdiff= FF_QP2LAMBDA * a->max_qdiff;
407
408         if     (q > last_q + maxdiff) q= last_q + maxdiff;
409         else if(q < last_q - maxdiff) q= last_q - maxdiff;
410     }
411
412     rcc->last_qscale_for[pict_type]= q; //Note we cannot do that after blurring
413
414     if(pict_type!=AV_PICTURE_TYPE_B)
415         rcc->last_non_b_pict_type= pict_type;
416
417     return q;
418 }
419
420 /**
421  * Get the qmin & qmax for pict_type.
422  */
423 static void get_qminmax(int *qmin_ret, int *qmax_ret, MpegEncContext *s, int pict_type){
424     int qmin= s->avctx->lmin;
425     int qmax= s->avctx->lmax;
426
427     assert(qmin <= qmax);
428
429     if(pict_type==AV_PICTURE_TYPE_B){
430         qmin= (int)(qmin*FFABS(s->avctx->b_quant_factor)+s->avctx->b_quant_offset + 0.5);
431         qmax= (int)(qmax*FFABS(s->avctx->b_quant_factor)+s->avctx->b_quant_offset + 0.5);
432     }else if(pict_type==AV_PICTURE_TYPE_I){
433         qmin= (int)(qmin*FFABS(s->avctx->i_quant_factor)+s->avctx->i_quant_offset + 0.5);
434         qmax= (int)(qmax*FFABS(s->avctx->i_quant_factor)+s->avctx->i_quant_offset + 0.5);
435     }
436
437     qmin= av_clip(qmin, 1, FF_LAMBDA_MAX);
438     qmax= av_clip(qmax, 1, FF_LAMBDA_MAX);
439
440     if(qmax<qmin) qmax= qmin;
441
442     *qmin_ret= qmin;
443     *qmax_ret= qmax;
444 }
445
446 static double modify_qscale(MpegEncContext *s, RateControlEntry *rce, double q, int frame_num){
447     RateControlContext *rcc= &s->rc_context;
448     int qmin, qmax;
449     const int pict_type= rce->new_pict_type;
450     const double buffer_size= s->avctx->rc_buffer_size;
451     const double fps= get_fps(s->avctx);
452     const double min_rate= s->avctx->rc_min_rate / fps;
453     const double max_rate= s->avctx->rc_max_rate / fps;
454
455     get_qminmax(&qmin, &qmax, s, pict_type);
456
457     /* modulation */
458     if(s->avctx->rc_qmod_freq && frame_num%s->avctx->rc_qmod_freq==0 && pict_type==AV_PICTURE_TYPE_P)
459         q*= s->avctx->rc_qmod_amp;
460
461     /* buffer overflow/underflow protection */
462     if(buffer_size){
463         double expected_size= rcc->buffer_index;
464         double q_limit;
465
466         if(min_rate){
467             double d= 2*(buffer_size - expected_size)/buffer_size;
468             if(d>1.0) d=1.0;
469             else if(d<0.0001) d=0.0001;
470             q*= pow(d, 1.0/s->avctx->rc_buffer_aggressivity);
471
472             q_limit= bits2qp(rce, FFMAX((min_rate - buffer_size + rcc->buffer_index) * s->avctx->rc_min_vbv_overflow_use, 1));
473             if(q > q_limit){
474                 if(s->avctx->debug&FF_DEBUG_RC){
475                     av_log(s->avctx, AV_LOG_DEBUG, "limiting QP %f -> %f\n", q, q_limit);
476                 }
477                 q= q_limit;
478             }
479         }
480
481         if(max_rate){
482             double d= 2*expected_size/buffer_size;
483             if(d>1.0) d=1.0;
484             else if(d<0.0001) d=0.0001;
485             q/= pow(d, 1.0/s->avctx->rc_buffer_aggressivity);
486
487             q_limit= bits2qp(rce, FFMAX(rcc->buffer_index * s->avctx->rc_max_available_vbv_use, 1));
488             if(q < q_limit){
489                 if(s->avctx->debug&FF_DEBUG_RC){
490                     av_log(s->avctx, AV_LOG_DEBUG, "limiting QP %f -> %f\n", q, q_limit);
491                 }
492                 q= q_limit;
493             }
494         }
495     }
496     av_dlog(s, "q:%f max:%f min:%f size:%f index:%f agr:%f\n",
497             q, max_rate, min_rate, buffer_size, rcc->buffer_index,
498             s->avctx->rc_buffer_aggressivity);
499     if(s->avctx->rc_qsquish==0.0 || qmin==qmax){
500         if     (q<qmin) q=qmin;
501         else if(q>qmax) q=qmax;
502     }else{
503         double min2= log(qmin);
504         double max2= log(qmax);
505
506         q= log(q);
507         q= (q - min2)/(max2-min2) - 0.5;
508         q*= -4.0;
509         q= 1.0/(1.0 + exp(q));
510         q= q*(max2-min2) + min2;
511
512         q= exp(q);
513     }
514
515     return q;
516 }
517
518 //----------------------------------
519 // 1 Pass Code
520
521 static double predict_size(Predictor *p, double q, double var)
522 {
523      return p->coeff*var / (q*p->count);
524 }
525
526 static void update_predictor(Predictor *p, double q, double var, double size)
527 {
528     double new_coeff= size*q / (var + 1);
529     if(var<10) return;
530
531     p->count*= p->decay;
532     p->coeff*= p->decay;
533     p->count++;
534     p->coeff+= new_coeff;
535 }
536
537 static void adaptive_quantization(MpegEncContext *s, double q){
538     int i;
539     const float lumi_masking= s->avctx->lumi_masking / (128.0*128.0);
540     const float dark_masking= s->avctx->dark_masking / (128.0*128.0);
541     const float temp_cplx_masking= s->avctx->temporal_cplx_masking;
542     const float spatial_cplx_masking = s->avctx->spatial_cplx_masking;
543     const float p_masking = s->avctx->p_masking;
544     const float border_masking = s->avctx->border_masking;
545     float bits_sum= 0.0;
546     float cplx_sum= 0.0;
547     float *cplx_tab = s->cplx_tab;
548     float *bits_tab = s->bits_tab;
549     const int qmin= s->avctx->mb_lmin;
550     const int qmax= s->avctx->mb_lmax;
551     Picture * const pic= &s->current_picture;
552     const int mb_width = s->mb_width;
553     const int mb_height = s->mb_height;
554
555     for(i=0; i<s->mb_num; i++){
556         const int mb_xy= s->mb_index2xy[i];
557         float temp_cplx= sqrt(pic->mc_mb_var[mb_xy]); //FIXME merge in pow()
558         float spat_cplx= sqrt(pic->mb_var[mb_xy]);
559         const int lumi= pic->mb_mean[mb_xy];
560         float bits, cplx, factor;
561         int mb_x = mb_xy % s->mb_stride;
562         int mb_y = mb_xy / s->mb_stride;
563         int mb_distance;
564         float mb_factor = 0.0;
565         if(spat_cplx < 4) spat_cplx= 4; //FIXME finetune
566         if(temp_cplx < 4) temp_cplx= 4; //FIXME finetune
567
568         if((s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_INTRA)){//FIXME hq mode
569             cplx= spat_cplx;
570             factor= 1.0 + p_masking;
571         }else{
572             cplx= temp_cplx;
573             factor= pow(temp_cplx, - temp_cplx_masking);
574         }
575         factor*=pow(spat_cplx, - spatial_cplx_masking);
576
577         if(lumi>127)
578             factor*= (1.0 - (lumi-128)*(lumi-128)*lumi_masking);
579         else
580             factor*= (1.0 - (lumi-128)*(lumi-128)*dark_masking);
581
582         if(mb_x < mb_width/5){
583             mb_distance = mb_width/5 - mb_x;
584             mb_factor = (float)mb_distance / (float)(mb_width/5);
585         }else if(mb_x > 4*mb_width/5){
586             mb_distance = mb_x - 4*mb_width/5;
587             mb_factor = (float)mb_distance / (float)(mb_width/5);
588         }
589         if(mb_y < mb_height/5){
590             mb_distance = mb_height/5 - mb_y;
591             mb_factor = FFMAX(mb_factor, (float)mb_distance / (float)(mb_height/5));
592         }else if(mb_y > 4*mb_height/5){
593             mb_distance = mb_y - 4*mb_height/5;
594             mb_factor = FFMAX(mb_factor, (float)mb_distance / (float)(mb_height/5));
595         }
596
597         factor*= 1.0 - border_masking*mb_factor;
598
599         if(factor<0.00001) factor= 0.00001;
600
601         bits= cplx*factor;
602         cplx_sum+= cplx;
603         bits_sum+= bits;
604         cplx_tab[i]= cplx;
605         bits_tab[i]= bits;
606     }
607
608     /* handle qmin/qmax clipping */
609     if(s->flags&CODEC_FLAG_NORMALIZE_AQP){
610         float factor= bits_sum/cplx_sum;
611         for(i=0; i<s->mb_num; i++){
612             float newq= q*cplx_tab[i]/bits_tab[i];
613             newq*= factor;
614
615             if     (newq > qmax){
616                 bits_sum -= bits_tab[i];
617                 cplx_sum -= cplx_tab[i]*q/qmax;
618             }
619             else if(newq < qmin){
620                 bits_sum -= bits_tab[i];
621                 cplx_sum -= cplx_tab[i]*q/qmin;
622             }
623         }
624         if(bits_sum < 0.001) bits_sum= 0.001;
625         if(cplx_sum < 0.001) cplx_sum= 0.001;
626     }
627
628     for(i=0; i<s->mb_num; i++){
629         const int mb_xy= s->mb_index2xy[i];
630         float newq= q*cplx_tab[i]/bits_tab[i];
631         int intq;
632
633         if(s->flags&CODEC_FLAG_NORMALIZE_AQP){
634             newq*= bits_sum/cplx_sum;
635         }
636
637         intq= (int)(newq + 0.5);
638
639         if     (intq > qmax) intq= qmax;
640         else if(intq < qmin) intq= qmin;
641         s->lambda_table[mb_xy]= intq;
642     }
643 }
644
645 void ff_get_2pass_fcode(MpegEncContext *s){
646     RateControlContext *rcc= &s->rc_context;
647     int picture_number= s->picture_number;
648     RateControlEntry *rce;
649
650     rce= &rcc->entry[picture_number];
651     s->f_code= rce->f_code;
652     s->b_code= rce->b_code;
653 }
654
655 //FIXME rd or at least approx for dquant
656
657 float ff_rate_estimate_qscale(MpegEncContext *s, int dry_run)
658 {
659     float q;
660     int qmin, qmax;
661     float br_compensation;
662     double diff;
663     double short_term_q;
664     double fps;
665     int picture_number= s->picture_number;
666     int64_t wanted_bits;
667     RateControlContext *rcc= &s->rc_context;
668     AVCodecContext *a= s->avctx;
669     RateControlEntry local_rce, *rce;
670     double bits;
671     double rate_factor;
672     int var;
673     const int pict_type= s->pict_type;
674     Picture * const pic= &s->current_picture;
675     emms_c();
676
677 #if CONFIG_LIBXVID
678     if((s->flags&CODEC_FLAG_PASS2) && s->avctx->rc_strategy == FF_RC_STRATEGY_XVID)
679         return ff_xvid_rate_estimate_qscale(s, dry_run);
680 #endif
681
682     get_qminmax(&qmin, &qmax, s, pict_type);
683
684     fps= get_fps(s->avctx);
685         /* update predictors */
686     if(picture_number>2 && !dry_run){
687         const int last_var= s->last_pict_type == AV_PICTURE_TYPE_I ? rcc->last_mb_var_sum : rcc->last_mc_mb_var_sum;
688         av_assert1(s->frame_bits >= s->stuffing_bits);
689         update_predictor(&rcc->pred[s->last_pict_type], rcc->last_qscale, sqrt(last_var), s->frame_bits - s->stuffing_bits);
690     }
691
692     if(s->flags&CODEC_FLAG_PASS2){
693         assert(picture_number>=0);
694         if(picture_number >= rcc->num_entries) {
695             av_log(s, AV_LOG_ERROR, "Input is longer than 2-pass log file\n");
696             return -1;
697         }
698         rce= &rcc->entry[picture_number];
699         wanted_bits= rce->expected_bits;
700     }else{
701         Picture *dts_pic;
702         rce= &local_rce;
703
704         //FIXME add a dts field to AVFrame and ensure its set and use it here instead of reordering
705         //but the reordering is simpler for now until h.264 b pyramid must be handeld
706         if(s->pict_type == AV_PICTURE_TYPE_B || s->low_delay)
707             dts_pic= s->current_picture_ptr;
708         else
709             dts_pic= s->last_picture_ptr;
710
711         if (!dts_pic || dts_pic->f.pts == AV_NOPTS_VALUE)
712             wanted_bits= (uint64_t)(s->bit_rate*(double)picture_number/fps);
713         else
714             wanted_bits = (uint64_t)(s->bit_rate*(double)dts_pic->f.pts / fps);
715     }
716
717     diff= s->total_bits - wanted_bits;
718     br_compensation= (a->bit_rate_tolerance - diff)/a->bit_rate_tolerance;
719     if(br_compensation<=0.0) br_compensation=0.001;
720
721     var= pict_type == AV_PICTURE_TYPE_I ? pic->mb_var_sum : pic->mc_mb_var_sum;
722
723     short_term_q = 0; /* avoid warning */
724     if(s->flags&CODEC_FLAG_PASS2){
725         if(pict_type!=AV_PICTURE_TYPE_I)
726             assert(pict_type == rce->new_pict_type);
727
728         q= rce->new_qscale / br_compensation;
729         av_dlog(s, "%f %f %f last:%d var:%d type:%d//\n", q, rce->new_qscale,
730                 br_compensation, s->frame_bits, var, pict_type);
731     }else{
732         rce->pict_type=
733         rce->new_pict_type= pict_type;
734         rce->mc_mb_var_sum= pic->mc_mb_var_sum;
735         rce->mb_var_sum   = pic->   mb_var_sum;
736         rce->qscale   = FF_QP2LAMBDA * 2;
737         rce->f_code   = s->f_code;
738         rce->b_code   = s->b_code;
739         rce->misc_bits= 1;
740
741         bits= predict_size(&rcc->pred[pict_type], rce->qscale, sqrt(var));
742         if(pict_type== AV_PICTURE_TYPE_I){
743             rce->i_count   = s->mb_num;
744             rce->i_tex_bits= bits;
745             rce->p_tex_bits= 0;
746             rce->mv_bits= 0;
747         }else{
748             rce->i_count   = 0; //FIXME we do know this approx
749             rce->i_tex_bits= 0;
750             rce->p_tex_bits= bits*0.9;
751
752             rce->mv_bits= bits*0.1;
753         }
754         rcc->i_cplx_sum [pict_type] += rce->i_tex_bits*rce->qscale;
755         rcc->p_cplx_sum [pict_type] += rce->p_tex_bits*rce->qscale;
756         rcc->mv_bits_sum[pict_type] += rce->mv_bits;
757         rcc->frame_count[pict_type] ++;
758
759         bits= rce->i_tex_bits + rce->p_tex_bits;
760         rate_factor= rcc->pass1_wanted_bits/rcc->pass1_rc_eq_output_sum * br_compensation;
761
762         q= get_qscale(s, rce, rate_factor, picture_number);
763         if (q < 0)
764             return -1;
765
766         assert(q>0.0);
767         q= get_diff_limited_q(s, rce, q);
768         assert(q>0.0);
769
770         if(pict_type==AV_PICTURE_TYPE_P || s->intra_only){ //FIXME type dependent blur like in 2-pass
771             rcc->short_term_qsum*=a->qblur;
772             rcc->short_term_qcount*=a->qblur;
773
774             rcc->short_term_qsum+= q;
775             rcc->short_term_qcount++;
776             q= short_term_q= rcc->short_term_qsum/rcc->short_term_qcount;
777         }
778         assert(q>0.0);
779
780         q= modify_qscale(s, rce, q, picture_number);
781
782         rcc->pass1_wanted_bits+= s->bit_rate/fps;
783
784         assert(q>0.0);
785     }
786
787     if(s->avctx->debug&FF_DEBUG_RC){
788         av_log(s->avctx, AV_LOG_DEBUG, "%c qp:%d<%2.1f<%d %d want:%d total:%d comp:%f st_q:%2.2f size:%d var:%d/%d br:%d fps:%d\n",
789         av_get_picture_type_char(pict_type), qmin, q, qmax, picture_number, (int)wanted_bits/1000, (int)s->total_bits/1000,
790         br_compensation, short_term_q, s->frame_bits, pic->mb_var_sum, pic->mc_mb_var_sum, s->bit_rate/1000, (int)fps
791         );
792     }
793
794     if     (q<qmin) q=qmin;
795     else if(q>qmax) q=qmax;
796
797     if(s->adaptive_quant)
798         adaptive_quantization(s, q);
799     else
800         q= (int)(q + 0.5);
801
802     if(!dry_run){
803         rcc->last_qscale= q;
804         rcc->last_mc_mb_var_sum= pic->mc_mb_var_sum;
805         rcc->last_mb_var_sum= pic->mb_var_sum;
806     }
807     return q;
808 }
809
810 //----------------------------------------------
811 // 2-Pass code
812
813 static int init_pass2(MpegEncContext *s)
814 {
815     RateControlContext *rcc= &s->rc_context;
816     AVCodecContext *a= s->avctx;
817     int i, toobig;
818     double fps= get_fps(s->avctx);
819     double complexity[5]={0,0,0,0,0};   // aproximate bits at quant=1
820     uint64_t const_bits[5]={0,0,0,0,0}; // quantizer independent bits
821     uint64_t all_const_bits;
822     uint64_t all_available_bits= (uint64_t)(s->bit_rate*(double)rcc->num_entries/fps);
823     double rate_factor=0;
824     double step;
825     //int last_i_frame=-10000000;
826     const int filter_size= (int)(a->qblur*4) | 1;
827     double expected_bits;
828     double *qscale, *blurred_qscale, qscale_sum;
829
830     /* find complexity & const_bits & decide the pict_types */
831     for(i=0; i<rcc->num_entries; i++){
832         RateControlEntry *rce= &rcc->entry[i];
833
834         rce->new_pict_type= rce->pict_type;
835         rcc->i_cplx_sum [rce->pict_type] += rce->i_tex_bits*rce->qscale;
836         rcc->p_cplx_sum [rce->pict_type] += rce->p_tex_bits*rce->qscale;
837         rcc->mv_bits_sum[rce->pict_type] += rce->mv_bits;
838         rcc->frame_count[rce->pict_type] ++;
839
840         complexity[rce->new_pict_type]+= (rce->i_tex_bits+ rce->p_tex_bits)*(double)rce->qscale;
841         const_bits[rce->new_pict_type]+= rce->mv_bits + rce->misc_bits;
842     }
843     all_const_bits= const_bits[AV_PICTURE_TYPE_I] + const_bits[AV_PICTURE_TYPE_P] + const_bits[AV_PICTURE_TYPE_B];
844
845     if(all_available_bits < all_const_bits){
846         av_log(s->avctx, AV_LOG_ERROR, "requested bitrate is too low\n");
847         return -1;
848     }
849
850     qscale= av_malloc(sizeof(double)*rcc->num_entries);
851     blurred_qscale= av_malloc(sizeof(double)*rcc->num_entries);
852     toobig = 0;
853
854     for(step=256*256; step>0.0000001; step*=0.5){
855         expected_bits=0;
856         rate_factor+= step;
857
858         rcc->buffer_index= s->avctx->rc_buffer_size/2;
859
860         /* find qscale */
861         for(i=0; i<rcc->num_entries; i++){
862             RateControlEntry *rce= &rcc->entry[i];
863             qscale[i]= get_qscale(s, &rcc->entry[i], rate_factor, i);
864             rcc->last_qscale_for[rce->pict_type] = qscale[i];
865         }
866         assert(filter_size%2==1);
867
868         /* fixed I/B QP relative to P mode */
869         for(i=FFMAX(0, rcc->num_entries-300); i<rcc->num_entries; i++){
870             RateControlEntry *rce= &rcc->entry[i];
871
872             qscale[i]= get_diff_limited_q(s, rce, qscale[i]);
873         }
874
875         for(i=rcc->num_entries-1; i>=0; i--){
876             RateControlEntry *rce= &rcc->entry[i];
877
878             qscale[i]= get_diff_limited_q(s, rce, qscale[i]);
879         }
880
881         /* smooth curve */
882         for(i=0; i<rcc->num_entries; i++){
883             RateControlEntry *rce= &rcc->entry[i];
884             const int pict_type= rce->new_pict_type;
885             int j;
886             double q=0.0, sum=0.0;
887
888             for(j=0; j<filter_size; j++){
889                 int index= i+j-filter_size/2;
890                 double d= index-i;
891                 double coeff= a->qblur==0 ? 1.0 : exp(-d*d/(a->qblur * a->qblur));
892
893                 if(index < 0 || index >= rcc->num_entries) continue;
894                 if(pict_type != rcc->entry[index].new_pict_type) continue;
895                 q+= qscale[index] * coeff;
896                 sum+= coeff;
897             }
898             blurred_qscale[i]= q/sum;
899         }
900
901         /* find expected bits */
902         for(i=0; i<rcc->num_entries; i++){
903             RateControlEntry *rce= &rcc->entry[i];
904             double bits;
905             rce->new_qscale= modify_qscale(s, rce, blurred_qscale[i], i);
906             bits= qp2bits(rce, rce->new_qscale) + rce->mv_bits + rce->misc_bits;
907             bits += 8*ff_vbv_update(s, bits);
908
909             rce->expected_bits= expected_bits;
910             expected_bits += bits;
911         }
912
913         av_dlog(s->avctx,
914                 "expected_bits: %f all_available_bits: %d rate_factor: %f\n",
915                 expected_bits, (int)all_available_bits, rate_factor);
916         if(expected_bits > all_available_bits) {
917             rate_factor-= step;
918             ++toobig;
919         }
920     }
921     av_free(qscale);
922     av_free(blurred_qscale);
923
924     /* check bitrate calculations and print info */
925     qscale_sum = 0.0;
926     for(i=0; i<rcc->num_entries; i++){
927         av_dlog(s, "[lavc rc] entry[%d].new_qscale = %.3f  qp = %.3f\n",
928                 i,
929                 rcc->entry[i].new_qscale,
930                 rcc->entry[i].new_qscale / FF_QP2LAMBDA);
931         qscale_sum += av_clip(rcc->entry[i].new_qscale / FF_QP2LAMBDA, s->avctx->qmin, s->avctx->qmax);
932     }
933     assert(toobig <= 40);
934     av_log(s->avctx, AV_LOG_DEBUG,
935         "[lavc rc] requested bitrate: %d bps  expected bitrate: %d bps\n",
936         s->bit_rate,
937         (int)(expected_bits / ((double)all_available_bits/s->bit_rate)));
938     av_log(s->avctx, AV_LOG_DEBUG,
939         "[lavc rc] estimated target average qp: %.3f\n",
940         (float)qscale_sum / rcc->num_entries);
941     if (toobig == 0) {
942         av_log(s->avctx, AV_LOG_INFO,
943             "[lavc rc] Using all of requested bitrate is not "
944             "necessary for this video with these parameters.\n");
945     } else if (toobig == 40) {
946         av_log(s->avctx, AV_LOG_ERROR,
947             "[lavc rc] Error: bitrate too low for this video "
948             "with these parameters.\n");
949         return -1;
950     } else if (fabs(expected_bits/all_available_bits - 1.0) > 0.01) {
951         av_log(s->avctx, AV_LOG_ERROR,
952             "[lavc rc] Error: 2pass curve failed to converge\n");
953         return -1;
954     }
955
956     return 0;
957 }