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