ratecontrol: fix get_fps() argument
[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     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/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 //printf("%d %f %d %f %f\n", buffer_size, rcc->buffer_index, frame_size, min_rate, max_rate);
287     if(buffer_size){
288         int left;
289
290         rcc->buffer_index-= frame_size;
291         if(rcc->buffer_index < 0){
292             av_log(s->avctx, AV_LOG_ERROR, "rc buffer underflow\n");
293             rcc->buffer_index= 0;
294         }
295
296         left= buffer_size - rcc->buffer_index - 1;
297         rcc->buffer_index += av_clip(left, min_rate, max_rate);
298
299         if(rcc->buffer_index > buffer_size){
300             int stuffing= ceil((rcc->buffer_index - buffer_size)/8);
301
302             if(stuffing < 4 && s->codec_id == AV_CODEC_ID_MPEG4)
303                 stuffing=4;
304             rcc->buffer_index -= 8*stuffing;
305
306             if(s->avctx->debug & FF_DEBUG_RC)
307                 av_log(s->avctx, AV_LOG_DEBUG, "stuffing %d bytes\n", stuffing);
308
309             return stuffing;
310         }
311     }
312     return 0;
313 }
314
315 /**
316  * Modify the bitrate curve from pass1 for one frame.
317  */
318 static double get_qscale(MpegEncContext *s, RateControlEntry *rce, double rate_factor, int frame_num){
319     RateControlContext *rcc= &s->rc_context;
320     AVCodecContext *a= s->avctx;
321     double q, bits;
322     const int pict_type= rce->new_pict_type;
323     const double mb_num= s->mb_num;
324     int i;
325
326     double const_values[]={
327         M_PI,
328         M_E,
329         rce->i_tex_bits*rce->qscale,
330         rce->p_tex_bits*rce->qscale,
331         (rce->i_tex_bits + rce->p_tex_bits)*(double)rce->qscale,
332         rce->mv_bits/mb_num,
333         rce->pict_type == AV_PICTURE_TYPE_B ? (rce->f_code + rce->b_code)*0.5 : rce->f_code,
334         rce->i_count/mb_num,
335         rce->mc_mb_var_sum/mb_num,
336         rce->mb_var_sum/mb_num,
337         rce->pict_type == AV_PICTURE_TYPE_I,
338         rce->pict_type == AV_PICTURE_TYPE_P,
339         rce->pict_type == AV_PICTURE_TYPE_B,
340         rcc->qscale_sum[pict_type] / (double)rcc->frame_count[pict_type],
341         a->qcompress,
342 /*        rcc->last_qscale_for[AV_PICTURE_TYPE_I],
343         rcc->last_qscale_for[AV_PICTURE_TYPE_P],
344         rcc->last_qscale_for[AV_PICTURE_TYPE_B],
345         rcc->next_non_b_qscale,*/
346         rcc->i_cplx_sum[AV_PICTURE_TYPE_I] / (double)rcc->frame_count[AV_PICTURE_TYPE_I],
347         rcc->i_cplx_sum[AV_PICTURE_TYPE_P] / (double)rcc->frame_count[AV_PICTURE_TYPE_P],
348         rcc->p_cplx_sum[AV_PICTURE_TYPE_P] / (double)rcc->frame_count[AV_PICTURE_TYPE_P],
349         rcc->p_cplx_sum[AV_PICTURE_TYPE_B] / (double)rcc->frame_count[AV_PICTURE_TYPE_B],
350         (rcc->i_cplx_sum[pict_type] + rcc->p_cplx_sum[pict_type]) / (double)rcc->frame_count[pict_type],
351         0
352     };
353
354     bits = av_expr_eval(rcc->rc_eq_eval, const_values, rce);
355     if (isnan(bits)) {
356         av_log(s->avctx, AV_LOG_ERROR, "Error evaluating rc_eq \"%s\"\n", s->avctx->rc_eq);
357         return -1;
358     }
359
360     rcc->pass1_rc_eq_output_sum+= bits;
361     bits*=rate_factor;
362     if(bits<0.0) bits=0.0;
363     bits+= 1.0; //avoid 1/0 issues
364
365     /* user override */
366     for(i=0; i<s->avctx->rc_override_count; i++){
367         RcOverride *rco= s->avctx->rc_override;
368         if(rco[i].start_frame > frame_num) continue;
369         if(rco[i].end_frame   < frame_num) continue;
370
371         if(rco[i].qscale)
372             bits= qp2bits(rce, rco[i].qscale); //FIXME move at end to really force it?
373         else
374             bits*= rco[i].quality_factor;
375     }
376
377     q= bits2qp(rce, bits);
378
379     /* I/B difference */
380     if     (pict_type==AV_PICTURE_TYPE_I && s->avctx->i_quant_factor<0.0)
381         q= -q*s->avctx->i_quant_factor + s->avctx->i_quant_offset;
382     else if(pict_type==AV_PICTURE_TYPE_B && s->avctx->b_quant_factor<0.0)
383         q= -q*s->avctx->b_quant_factor + s->avctx->b_quant_offset;
384     if(q<1) q=1;
385
386     return q;
387 }
388
389 static double get_diff_limited_q(MpegEncContext *s, RateControlEntry *rce, double q){
390     RateControlContext *rcc= &s->rc_context;
391     AVCodecContext *a= s->avctx;
392     const int pict_type= rce->new_pict_type;
393     const double last_p_q    = rcc->last_qscale_for[AV_PICTURE_TYPE_P];
394     const double last_non_b_q= rcc->last_qscale_for[rcc->last_non_b_pict_type];
395
396     if     (pict_type==AV_PICTURE_TYPE_I && (a->i_quant_factor>0.0 || rcc->last_non_b_pict_type==AV_PICTURE_TYPE_P))
397         q= last_p_q    *FFABS(a->i_quant_factor) + a->i_quant_offset;
398     else if(pict_type==AV_PICTURE_TYPE_B && a->b_quant_factor>0.0)
399         q= last_non_b_q*    a->b_quant_factor  + a->b_quant_offset;
400     if(q<1) q=1;
401
402     /* last qscale / qdiff stuff */
403     if(rcc->last_non_b_pict_type==pict_type || pict_type!=AV_PICTURE_TYPE_I){
404         double last_q= rcc->last_qscale_for[pict_type];
405         const int maxdiff= FF_QP2LAMBDA * a->max_qdiff;
406
407         if     (q > last_q + maxdiff) q= last_q + maxdiff;
408         else if(q < last_q - maxdiff) q= last_q - maxdiff;
409     }
410
411     rcc->last_qscale_for[pict_type]= q; //Note we cannot do that after blurring
412
413     if(pict_type!=AV_PICTURE_TYPE_B)
414         rcc->last_non_b_pict_type= pict_type;
415
416     return q;
417 }
418
419 /**
420  * Get the qmin & qmax for pict_type.
421  */
422 static void get_qminmax(int *qmin_ret, int *qmax_ret, MpegEncContext *s, int pict_type){
423     int qmin= s->avctx->lmin;
424     int qmax= s->avctx->lmax;
425
426     assert(qmin <= qmax);
427
428     if(pict_type==AV_PICTURE_TYPE_B){
429         qmin= (int)(qmin*FFABS(s->avctx->b_quant_factor)+s->avctx->b_quant_offset + 0.5);
430         qmax= (int)(qmax*FFABS(s->avctx->b_quant_factor)+s->avctx->b_quant_offset + 0.5);
431     }else if(pict_type==AV_PICTURE_TYPE_I){
432         qmin= (int)(qmin*FFABS(s->avctx->i_quant_factor)+s->avctx->i_quant_offset + 0.5);
433         qmax= (int)(qmax*FFABS(s->avctx->i_quant_factor)+s->avctx->i_quant_offset + 0.5);
434     }
435
436     qmin= av_clip(qmin, 1, FF_LAMBDA_MAX);
437     qmax= av_clip(qmax, 1, FF_LAMBDA_MAX);
438
439     if(qmax<qmin) qmax= qmin;
440
441     *qmin_ret= qmin;
442     *qmax_ret= qmax;
443 }
444
445 static double modify_qscale(MpegEncContext *s, RateControlEntry *rce, double q, int frame_num){
446     RateControlContext *rcc= &s->rc_context;
447     int qmin, qmax;
448     const int pict_type= rce->new_pict_type;
449     const double buffer_size= s->avctx->rc_buffer_size;
450     const double fps= get_fps(s->avctx);
451     const double min_rate= s->avctx->rc_min_rate / fps;
452     const double max_rate= s->avctx->rc_max_rate / fps;
453
454     get_qminmax(&qmin, &qmax, s, pict_type);
455
456     /* modulation */
457     if(s->avctx->rc_qmod_freq && frame_num%s->avctx->rc_qmod_freq==0 && pict_type==AV_PICTURE_TYPE_P)
458         q*= s->avctx->rc_qmod_amp;
459
460 //printf("q:%f\n", q);
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 //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);
497     if(s->avctx->rc_qsquish==0.0 || qmin==qmax){
498         if     (q<qmin) q=qmin;
499         else if(q>qmax) q=qmax;
500     }else{
501         double min2= log(qmin);
502         double max2= log(qmax);
503
504         q= log(q);
505         q= (q - min2)/(max2-min2) - 0.5;
506         q*= -4.0;
507         q= 1.0/(1.0 + exp(q));
508         q= q*(max2-min2) + min2;
509
510         q= exp(q);
511     }
512
513     return q;
514 }
515
516 //----------------------------------
517 // 1 Pass Code
518
519 static double predict_size(Predictor *p, double q, double var)
520 {
521      return p->coeff*var / (q*p->count);
522 }
523
524 static void update_predictor(Predictor *p, double q, double var, double size)
525 {
526     double new_coeff= size*q / (var + 1);
527     if(var<10) return;
528
529     p->count*= p->decay;
530     p->coeff*= p->decay;
531     p->count++;
532     p->coeff+= new_coeff;
533 }
534
535 static void adaptive_quantization(MpegEncContext *s, double q){
536     int i;
537     const float lumi_masking= s->avctx->lumi_masking / (128.0*128.0);
538     const float dark_masking= s->avctx->dark_masking / (128.0*128.0);
539     const float temp_cplx_masking= s->avctx->temporal_cplx_masking;
540     const float spatial_cplx_masking = s->avctx->spatial_cplx_masking;
541     const float p_masking = s->avctx->p_masking;
542     const float border_masking = s->avctx->border_masking;
543     float bits_sum= 0.0;
544     float cplx_sum= 0.0;
545     float *cplx_tab = s->cplx_tab;
546     float *bits_tab = s->bits_tab;
547     const int qmin= s->avctx->mb_lmin;
548     const int qmax= s->avctx->mb_lmax;
549     Picture * const pic= &s->current_picture;
550     const int mb_width = s->mb_width;
551     const int mb_height = s->mb_height;
552
553     for(i=0; i<s->mb_num; i++){
554         const int mb_xy= s->mb_index2xy[i];
555         float temp_cplx= sqrt(pic->mc_mb_var[mb_xy]); //FIXME merge in pow()
556         float spat_cplx= sqrt(pic->mb_var[mb_xy]);
557         const int lumi= pic->mb_mean[mb_xy];
558         float bits, cplx, factor;
559         int mb_x = mb_xy % s->mb_stride;
560         int mb_y = mb_xy / s->mb_stride;
561         int mb_distance;
562         float mb_factor = 0.0;
563         if(spat_cplx < 4) spat_cplx= 4; //FIXME finetune
564         if(temp_cplx < 4) temp_cplx= 4; //FIXME finetune
565
566         if((s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_INTRA)){//FIXME hq mode
567             cplx= spat_cplx;
568             factor= 1.0 + p_masking;
569         }else{
570             cplx= temp_cplx;
571             factor= pow(temp_cplx, - temp_cplx_masking);
572         }
573         factor*=pow(spat_cplx, - spatial_cplx_masking);
574
575         if(lumi>127)
576             factor*= (1.0 - (lumi-128)*(lumi-128)*lumi_masking);
577         else
578             factor*= (1.0 - (lumi-128)*(lumi-128)*dark_masking);
579
580         if(mb_x < mb_width/5){
581             mb_distance = mb_width/5 - mb_x;
582             mb_factor = (float)mb_distance / (float)(mb_width/5);
583         }else if(mb_x > 4*mb_width/5){
584             mb_distance = mb_x - 4*mb_width/5;
585             mb_factor = (float)mb_distance / (float)(mb_width/5);
586         }
587         if(mb_y < mb_height/5){
588             mb_distance = mb_height/5 - mb_y;
589             mb_factor = FFMAX(mb_factor, (float)mb_distance / (float)(mb_height/5));
590         }else if(mb_y > 4*mb_height/5){
591             mb_distance = mb_y - 4*mb_height/5;
592             mb_factor = FFMAX(mb_factor, (float)mb_distance / (float)(mb_height/5));
593         }
594
595         factor*= 1.0 - border_masking*mb_factor;
596
597         if(factor<0.00001) factor= 0.00001;
598
599         bits= cplx*factor;
600         cplx_sum+= cplx;
601         bits_sum+= bits;
602         cplx_tab[i]= cplx;
603         bits_tab[i]= bits;
604     }
605
606     /* handle qmin/qmax clipping */
607     if(s->flags&CODEC_FLAG_NORMALIZE_AQP){
608         float factor= bits_sum/cplx_sum;
609         for(i=0; i<s->mb_num; i++){
610             float newq= q*cplx_tab[i]/bits_tab[i];
611             newq*= factor;
612
613             if     (newq > qmax){
614                 bits_sum -= bits_tab[i];
615                 cplx_sum -= cplx_tab[i]*q/qmax;
616             }
617             else if(newq < qmin){
618                 bits_sum -= bits_tab[i];
619                 cplx_sum -= cplx_tab[i]*q/qmin;
620             }
621         }
622         if(bits_sum < 0.001) bits_sum= 0.001;
623         if(cplx_sum < 0.001) cplx_sum= 0.001;
624     }
625
626     for(i=0; i<s->mb_num; i++){
627         const int mb_xy= s->mb_index2xy[i];
628         float newq= q*cplx_tab[i]/bits_tab[i];
629         int intq;
630
631         if(s->flags&CODEC_FLAG_NORMALIZE_AQP){
632             newq*= bits_sum/cplx_sum;
633         }
634
635         intq= (int)(newq + 0.5);
636
637         if     (intq > qmax) intq= qmax;
638         else if(intq < qmin) intq= qmin;
639 //if(i%s->mb_width==0) printf("\n");
640 //printf("%2d%3d ", intq, ff_sqrt(s->mc_mb_var[i]));
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 //printf("input_pic_num:%d pic_num:%d frame_rate:%d\n", s->input_picture_number, s->picture_number, s->frame_rate);
686         /* update predictors */
687     if(picture_number>2 && !dry_run){
688         const int last_var= s->last_pict_type == AV_PICTURE_TYPE_I ? rcc->last_mb_var_sum : rcc->last_mc_mb_var_sum;
689         av_assert1(s->frame_bits >= s->stuffing_bits);
690         update_predictor(&rcc->pred[s->last_pict_type], rcc->last_qscale, sqrt(last_var), s->frame_bits - s->stuffing_bits);
691     }
692
693     if(s->flags&CODEC_FLAG_PASS2){
694         assert(picture_number>=0);
695         assert(picture_number<rcc->num_entries);
696         rce= &rcc->entry[picture_number];
697         wanted_bits= rce->expected_bits;
698     }else{
699         Picture *dts_pic;
700         rce= &local_rce;
701
702         //FIXME add a dts field to AVFrame and ensure its set and use it here instead of reordering
703         //but the reordering is simpler for now until h.264 b pyramid must be handeld
704         if(s->pict_type == AV_PICTURE_TYPE_B || s->low_delay)
705             dts_pic= s->current_picture_ptr;
706         else
707             dts_pic= s->last_picture_ptr;
708
709 //if(dts_pic)
710 //            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);
711
712         if (!dts_pic || dts_pic->f.pts == AV_NOPTS_VALUE)
713             wanted_bits= (uint64_t)(s->bit_rate*(double)picture_number/fps);
714         else
715             wanted_bits = (uint64_t)(s->bit_rate*(double)dts_pic->f.pts / fps);
716     }
717
718     diff= s->total_bits - wanted_bits;
719     br_compensation= (a->bit_rate_tolerance - diff)/a->bit_rate_tolerance;
720     if(br_compensation<=0.0) br_compensation=0.001;
721
722     var= pict_type == AV_PICTURE_TYPE_I ? pic->mb_var_sum : pic->mc_mb_var_sum;
723
724     short_term_q = 0; /* avoid warning */
725     if(s->flags&CODEC_FLAG_PASS2){
726         if(pict_type!=AV_PICTURE_TYPE_I)
727             assert(pict_type == rce->new_pict_type);
728
729         q= rce->new_qscale / br_compensation;
730 //printf("%f %f %f last:%d var:%d type:%d//\n", q, rce->new_qscale, 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 //printf("%f ", q);
768         q= get_diff_limited_q(s, rce, q);
769 //printf("%f ", q);
770         assert(q>0.0);
771
772         if(pict_type==AV_PICTURE_TYPE_P || s->intra_only){ //FIXME type dependent blur like in 2-pass
773             rcc->short_term_qsum*=a->qblur;
774             rcc->short_term_qcount*=a->qblur;
775
776             rcc->short_term_qsum+= q;
777             rcc->short_term_qcount++;
778 //printf("%f ", q);
779             q= short_term_q= rcc->short_term_qsum/rcc->short_term_qcount;
780 //printf("%f ", q);
781         }
782         assert(q>0.0);
783
784         q= modify_qscale(s, rce, q, picture_number);
785
786         rcc->pass1_wanted_bits+= s->bit_rate/fps;
787
788         assert(q>0.0);
789     }
790
791     if(s->avctx->debug&FF_DEBUG_RC){
792         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",
793         av_get_picture_type_char(pict_type), qmin, q, qmax, picture_number, (int)wanted_bits/1000, (int)s->total_bits/1000,
794         br_compensation, short_term_q, s->frame_bits, pic->mb_var_sum, pic->mc_mb_var_sum, s->bit_rate/1000, (int)fps
795         );
796     }
797
798     if     (q<qmin) q=qmin;
799     else if(q>qmax) q=qmax;
800
801     if(s->adaptive_quant)
802         adaptive_quantization(s, q);
803     else
804         q= (int)(q + 0.5);
805
806     if(!dry_run){
807         rcc->last_qscale= q;
808         rcc->last_mc_mb_var_sum= pic->mc_mb_var_sum;
809         rcc->last_mb_var_sum= pic->mb_var_sum;
810     }
811     return q;
812 }
813
814 //----------------------------------------------
815 // 2-Pass code
816
817 static int init_pass2(MpegEncContext *s)
818 {
819     RateControlContext *rcc= &s->rc_context;
820     AVCodecContext *a= s->avctx;
821     int i, toobig;
822     double fps= get_fps(s->avctx);
823     double complexity[5]={0,0,0,0,0};   // aproximate bits at quant=1
824     uint64_t const_bits[5]={0,0,0,0,0}; // quantizer independent bits
825     uint64_t all_const_bits;
826     uint64_t all_available_bits= (uint64_t)(s->bit_rate*(double)rcc->num_entries/fps);
827     double rate_factor=0;
828     double step;
829     //int last_i_frame=-10000000;
830     const int filter_size= (int)(a->qblur*4) | 1;
831     double expected_bits;
832     double *qscale, *blurred_qscale, qscale_sum;
833
834     /* find complexity & const_bits & decide the pict_types */
835     for(i=0; i<rcc->num_entries; i++){
836         RateControlEntry *rce= &rcc->entry[i];
837
838         rce->new_pict_type= rce->pict_type;
839         rcc->i_cplx_sum [rce->pict_type] += rce->i_tex_bits*rce->qscale;
840         rcc->p_cplx_sum [rce->pict_type] += rce->p_tex_bits*rce->qscale;
841         rcc->mv_bits_sum[rce->pict_type] += rce->mv_bits;
842         rcc->frame_count[rce->pict_type] ++;
843
844         complexity[rce->new_pict_type]+= (rce->i_tex_bits+ rce->p_tex_bits)*(double)rce->qscale;
845         const_bits[rce->new_pict_type]+= rce->mv_bits + rce->misc_bits;
846     }
847     all_const_bits= const_bits[AV_PICTURE_TYPE_I] + const_bits[AV_PICTURE_TYPE_P] + const_bits[AV_PICTURE_TYPE_B];
848
849     if(all_available_bits < all_const_bits){
850         av_log(s->avctx, AV_LOG_ERROR, "requested bitrate is too low\n");
851         return -1;
852     }
853
854     qscale= av_malloc(sizeof(double)*rcc->num_entries);
855     blurred_qscale= av_malloc(sizeof(double)*rcc->num_entries);
856     toobig = 0;
857
858     for(step=256*256; step>0.0000001; step*=0.5){
859         expected_bits=0;
860         rate_factor+= step;
861
862         rcc->buffer_index= s->avctx->rc_buffer_size/2;
863
864         /* find qscale */
865         for(i=0; i<rcc->num_entries; i++){
866             RateControlEntry *rce= &rcc->entry[i];
867             qscale[i]= get_qscale(s, &rcc->entry[i], rate_factor, i);
868             rcc->last_qscale_for[rce->pict_type] = qscale[i];
869         }
870         assert(filter_size%2==1);
871
872         /* fixed I/B QP relative to P mode */
873         for(i=FFMAX(0, rcc->num_entries-300); i<rcc->num_entries; i++){
874             RateControlEntry *rce= &rcc->entry[i];
875
876             qscale[i]= get_diff_limited_q(s, rce, qscale[i]);
877         }
878
879         for(i=rcc->num_entries-1; i>=0; i--){
880             RateControlEntry *rce= &rcc->entry[i];
881
882             qscale[i]= get_diff_limited_q(s, rce, qscale[i]);
883         }
884
885         /* smooth curve */
886         for(i=0; i<rcc->num_entries; i++){
887             RateControlEntry *rce= &rcc->entry[i];
888             const int pict_type= rce->new_pict_type;
889             int j;
890             double q=0.0, sum=0.0;
891
892             for(j=0; j<filter_size; j++){
893                 int index= i+j-filter_size/2;
894                 double d= index-i;
895                 double coeff= a->qblur==0 ? 1.0 : exp(-d*d/(a->qblur * a->qblur));
896
897                 if(index < 0 || index >= rcc->num_entries) continue;
898                 if(pict_type != rcc->entry[index].new_pict_type) continue;
899                 q+= qscale[index] * coeff;
900                 sum+= coeff;
901             }
902             blurred_qscale[i]= q/sum;
903         }
904
905         /* find expected bits */
906         for(i=0; i<rcc->num_entries; i++){
907             RateControlEntry *rce= &rcc->entry[i];
908             double bits;
909             rce->new_qscale= modify_qscale(s, rce, blurred_qscale[i], i);
910             bits= qp2bits(rce, rce->new_qscale) + rce->mv_bits + rce->misc_bits;
911 //printf("%d %f\n", rce->new_bits, blurred_qscale[i]);
912             bits += 8*ff_vbv_update(s, bits);
913
914             rce->expected_bits= expected_bits;
915             expected_bits += bits;
916         }
917
918         /*
919         av_log(s->avctx, AV_LOG_INFO,
920             "expected_bits: %f all_available_bits: %d rate_factor: %f\n",
921             expected_bits, (int)all_available_bits, rate_factor);
922         */
923         if(expected_bits > all_available_bits) {
924             rate_factor-= step;
925             ++toobig;
926         }
927     }
928     av_free(qscale);
929     av_free(blurred_qscale);
930
931     /* check bitrate calculations and print info */
932     qscale_sum = 0.0;
933     for(i=0; i<rcc->num_entries; i++){
934         /* av_log(s->avctx, AV_LOG_DEBUG, "[lavc rc] entry[%d].new_qscale = %.3f  qp = %.3f\n",
935             i, rcc->entry[i].new_qscale, rcc->entry[i].new_qscale / FF_QP2LAMBDA); */
936         qscale_sum += av_clip(rcc->entry[i].new_qscale / FF_QP2LAMBDA, s->avctx->qmin, s->avctx->qmax);
937     }
938     assert(toobig <= 40);
939     av_log(s->avctx, AV_LOG_DEBUG,
940         "[lavc rc] requested bitrate: %d bps  expected bitrate: %d bps\n",
941         s->bit_rate,
942         (int)(expected_bits / ((double)all_available_bits/s->bit_rate)));
943     av_log(s->avctx, AV_LOG_DEBUG,
944         "[lavc rc] estimated target average qp: %.3f\n",
945         (float)qscale_sum / rcc->num_entries);
946     if (toobig == 0) {
947         av_log(s->avctx, AV_LOG_INFO,
948             "[lavc rc] Using all of requested bitrate is not "
949             "necessary for this video with these parameters.\n");
950     } else if (toobig == 40) {
951         av_log(s->avctx, AV_LOG_ERROR,
952             "[lavc rc] Error: bitrate too low for this video "
953             "with these parameters.\n");
954         return -1;
955     } else if (fabs(expected_bits/all_available_bits - 1.0) > 0.01) {
956         av_log(s->avctx, AV_LOG_ERROR,
957             "[lavc rc] Error: 2pass curve failed to converge\n");
958         return -1;
959     }
960
961     return 0;
962 }