Change the order of parameters for ff_eval_expr() and
[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 "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->display_picture_number, s->current_picture_ptr->coded_picture_number, s->pict_type,
48             s->current_picture.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 inline double qp2bits(RateControlEntry *rce, double qp){
53     if(qp<=0.0){
54         av_log(NULL, AV_LOG_ERROR, "qp<=0.0\n");
55     }
56     return rce->qscale * (double)(rce->i_tex_bits + rce->p_tex_bits+1)/ qp;
57 }
58
59 static inline double bits2qp(RateControlEntry *rce, double bits){
60     if(bits<0.9){
61         av_log(NULL, AV_LOG_ERROR, "bits<0.9\n");
62     }
63     return rce->qscale * (double)(rce->i_tex_bits + rce->p_tex_bits+1)/ bits;
64 }
65
66 int ff_rate_control_init(MpegEncContext *s)
67 {
68     RateControlContext *rcc= &s->rc_context;
69     int i;
70     const char *error = NULL;
71     static const char * const const_names[]={
72         "PI",
73         "E",
74         "iTex",
75         "pTex",
76         "tex",
77         "mv",
78         "fCode",
79         "iCount",
80         "mcVar",
81         "var",
82         "isI",
83         "isP",
84         "isB",
85         "avgQP",
86         "qComp",
87 /*        "lastIQP",
88         "lastPQP",
89         "lastBQP",
90         "nextNonBQP",*/
91         "avgIITex",
92         "avgPITex",
93         "avgPPTex",
94         "avgBPTex",
95         "avgTex",
96         NULL
97     };
98     static double (* const func1[])(void *, double)={
99         (void *)bits2qp,
100         (void *)qp2bits,
101         NULL
102     };
103     static const char * const func1_names[]={
104         "bits2qp",
105         "qp2bits",
106         NULL
107     };
108     emms_c();
109
110     rcc->rc_eq_eval = ff_parse_expr(s->avctx->rc_eq ? s->avctx->rc_eq : "tex^qComp", const_names, func1_names, func1, NULL, NULL, &error);
111     if (!rcc->rc_eq_eval) {
112         av_log(s->avctx, AV_LOG_ERROR, "Error parsing rc_eq \"%s\": %s\n", s->avctx->rc_eq, error? error : "");
113         return -1;
114     }
115
116     for(i=0; i<5; i++){
117         rcc->pred[i].coeff= FF_QP2LAMBDA * 7.0;
118         rcc->pred[i].count= 1.0;
119
120         rcc->pred[i].decay= 0.4;
121         rcc->i_cplx_sum [i]=
122         rcc->p_cplx_sum [i]=
123         rcc->mv_bits_sum[i]=
124         rcc->qscale_sum [i]=
125         rcc->frame_count[i]= 1; // 1 is better because of 1/0 and such
126         rcc->last_qscale_for[i]=FF_QP2LAMBDA * 5;
127     }
128     rcc->buffer_index= s->avctx->rc_initial_buffer_occupancy;
129
130     if(s->flags&CODEC_FLAG_PASS2){
131         int i;
132         char *p;
133
134         /* find number of pics */
135         p= s->avctx->stats_in;
136         for(i=-1; p; i++){
137             p= strchr(p+1, ';');
138         }
139         i+= s->max_b_frames;
140         if(i<=0 || i>=INT_MAX / sizeof(RateControlEntry))
141             return -1;
142         rcc->entry = av_mallocz(i*sizeof(RateControlEntry));
143         rcc->num_entries= i;
144
145         /* init all to skipped p frames (with b frames we might have a not encoded frame at the end FIXME) */
146         for(i=0; i<rcc->num_entries; i++){
147             RateControlEntry *rce= &rcc->entry[i];
148             rce->pict_type= rce->new_pict_type=FF_P_TYPE;
149             rce->qscale= rce->new_qscale=FF_QP2LAMBDA * 2;
150             rce->misc_bits= s->mb_num + 10;
151             rce->mb_var_sum= s->mb_num*100;
152         }
153
154         /* read stats */
155         p= s->avctx->stats_in;
156         for(i=0; i<rcc->num_entries - s->max_b_frames; i++){
157             RateControlEntry *rce;
158             int picture_number;
159             int e;
160             char *next;
161
162             next= strchr(p, ';');
163             if(next){
164                 (*next)=0; //sscanf in unbelievably slow on looong strings //FIXME copy / do not write
165                 next++;
166             }
167             e= sscanf(p, " in:%d ", &picture_number);
168
169             assert(picture_number >= 0);
170             assert(picture_number < rcc->num_entries);
171             rce= &rcc->entry[picture_number];
172
173             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",
174                    &rce->pict_type, &rce->qscale, &rce->i_tex_bits, &rce->p_tex_bits, &rce->mv_bits, &rce->misc_bits,
175                    &rce->f_code, &rce->b_code, &rce->mc_mb_var_sum, &rce->mb_var_sum, &rce->i_count, &rce->skip_count, &rce->header_bits);
176             if(e!=14){
177                 av_log(s->avctx, AV_LOG_ERROR, "statistics are damaged at line %d, parser out=%d\n", i, e);
178                 return -1;
179             }
180
181             p= next;
182         }
183
184         if(init_pass2(s) < 0) return -1;
185
186         //FIXME maybe move to end
187         if((s->flags&CODEC_FLAG_PASS2) && s->avctx->rc_strategy == FF_RC_STRATEGY_XVID) {
188 #if CONFIG_LIBXVID
189             return ff_xvid_rate_control_init(s);
190 #else
191             av_log(s->avctx, AV_LOG_ERROR, "Xvid ratecontrol requires libavcodec compiled with Xvid support.\n");
192             return -1;
193 #endif
194         }
195     }
196
197     if(!(s->flags&CODEC_FLAG_PASS2)){
198
199         rcc->short_term_qsum=0.001;
200         rcc->short_term_qcount=0.001;
201
202         rcc->pass1_rc_eq_output_sum= 0.001;
203         rcc->pass1_wanted_bits=0.001;
204
205         if(s->avctx->qblur > 1.0){
206             av_log(s->avctx, AV_LOG_ERROR, "qblur too large\n");
207             return -1;
208         }
209         /* init stuff with the user specified complexity */
210         if(s->avctx->rc_initial_cplx){
211             for(i=0; i<60*30; i++){
212                 double bits= s->avctx->rc_initial_cplx * (i/10000.0 + 1.0)*s->mb_num;
213                 RateControlEntry rce;
214
215                 if     (i%((s->gop_size+3)/4)==0) rce.pict_type= FF_I_TYPE;
216                 else if(i%(s->max_b_frames+1))    rce.pict_type= FF_B_TYPE;
217                 else                              rce.pict_type= FF_P_TYPE;
218
219                 rce.new_pict_type= rce.pict_type;
220                 rce.mc_mb_var_sum= bits*s->mb_num/100000;
221                 rce.mb_var_sum   = s->mb_num;
222                 rce.qscale   = FF_QP2LAMBDA * 2;
223                 rce.f_code   = 2;
224                 rce.b_code   = 1;
225                 rce.misc_bits= 1;
226
227                 if(s->pict_type== FF_I_TYPE){
228                     rce.i_count   = s->mb_num;
229                     rce.i_tex_bits= bits;
230                     rce.p_tex_bits= 0;
231                     rce.mv_bits= 0;
232                 }else{
233                     rce.i_count   = 0; //FIXME we do know this approx
234                     rce.i_tex_bits= 0;
235                     rce.p_tex_bits= bits*0.9;
236                     rce.mv_bits= bits*0.1;
237                 }
238                 rcc->i_cplx_sum [rce.pict_type] += rce.i_tex_bits*rce.qscale;
239                 rcc->p_cplx_sum [rce.pict_type] += rce.p_tex_bits*rce.qscale;
240                 rcc->mv_bits_sum[rce.pict_type] += rce.mv_bits;
241                 rcc->frame_count[rce.pict_type] ++;
242
243                 get_qscale(s, &rce, rcc->pass1_wanted_bits/rcc->pass1_rc_eq_output_sum, i);
244                 rcc->pass1_wanted_bits+= s->bit_rate/(1/av_q2d(s->avctx->time_base)); //FIXME misbehaves a little for variable fps
245             }
246         }
247
248     }
249
250     return 0;
251 }
252
253 void ff_rate_control_uninit(MpegEncContext *s)
254 {
255     RateControlContext *rcc= &s->rc_context;
256     emms_c();
257
258     ff_free_expr(rcc->rc_eq_eval);
259     av_freep(&rcc->entry);
260
261 #if CONFIG_LIBXVID
262     if((s->flags&CODEC_FLAG_PASS2) && s->avctx->rc_strategy == FF_RC_STRATEGY_XVID)
263         ff_xvid_rate_control_uninit(s);
264 #endif
265 }
266
267 int ff_vbv_update(MpegEncContext *s, int frame_size){
268     RateControlContext *rcc= &s->rc_context;
269     const double fps= 1/av_q2d(s->avctx->time_base);
270     const int buffer_size= s->avctx->rc_buffer_size;
271     const double min_rate= s->avctx->rc_min_rate/fps;
272     const double max_rate= s->avctx->rc_max_rate/fps;
273
274 //printf("%d %f %d %f %f\n", buffer_size, rcc->buffer_index, frame_size, min_rate, max_rate);
275     if(buffer_size){
276         int left;
277
278         rcc->buffer_index-= frame_size;
279         if(rcc->buffer_index < 0){
280             av_log(s->avctx, AV_LOG_ERROR, "rc buffer underflow\n");
281             rcc->buffer_index= 0;
282         }
283
284         left= buffer_size - rcc->buffer_index - 1;
285         rcc->buffer_index += av_clip(left, min_rate, max_rate);
286
287         if(rcc->buffer_index > buffer_size){
288             int stuffing= ceil((rcc->buffer_index - buffer_size)/8);
289
290             if(stuffing < 4 && s->codec_id == CODEC_ID_MPEG4)
291                 stuffing=4;
292             rcc->buffer_index -= 8*stuffing;
293
294             if(s->avctx->debug & FF_DEBUG_RC)
295                 av_log(s->avctx, AV_LOG_DEBUG, "stuffing %d bytes\n", stuffing);
296
297             return stuffing;
298         }
299     }
300     return 0;
301 }
302
303 /**
304  * modifies the bitrate curve from pass1 for one frame
305  */
306 static double get_qscale(MpegEncContext *s, RateControlEntry *rce, double rate_factor, int frame_num){
307     RateControlContext *rcc= &s->rc_context;
308     AVCodecContext *a= s->avctx;
309     double q, bits;
310     const int pict_type= rce->new_pict_type;
311     const double mb_num= s->mb_num;
312     int i;
313
314     double const_values[]={
315         M_PI,
316         M_E,
317         rce->i_tex_bits*rce->qscale,
318         rce->p_tex_bits*rce->qscale,
319         (rce->i_tex_bits + rce->p_tex_bits)*(double)rce->qscale,
320         rce->mv_bits/mb_num,
321         rce->pict_type == FF_B_TYPE ? (rce->f_code + rce->b_code)*0.5 : rce->f_code,
322         rce->i_count/mb_num,
323         rce->mc_mb_var_sum/mb_num,
324         rce->mb_var_sum/mb_num,
325         rce->pict_type == FF_I_TYPE,
326         rce->pict_type == FF_P_TYPE,
327         rce->pict_type == FF_B_TYPE,
328         rcc->qscale_sum[pict_type] / (double)rcc->frame_count[pict_type],
329         a->qcompress,
330 /*        rcc->last_qscale_for[FF_I_TYPE],
331         rcc->last_qscale_for[FF_P_TYPE],
332         rcc->last_qscale_for[FF_B_TYPE],
333         rcc->next_non_b_qscale,*/
334         rcc->i_cplx_sum[FF_I_TYPE] / (double)rcc->frame_count[FF_I_TYPE],
335         rcc->i_cplx_sum[FF_P_TYPE] / (double)rcc->frame_count[FF_P_TYPE],
336         rcc->p_cplx_sum[FF_P_TYPE] / (double)rcc->frame_count[FF_P_TYPE],
337         rcc->p_cplx_sum[FF_B_TYPE] / (double)rcc->frame_count[FF_B_TYPE],
338         (rcc->i_cplx_sum[pict_type] + rcc->p_cplx_sum[pict_type]) / (double)rcc->frame_count[pict_type],
339         0
340     };
341
342     bits= ff_eval_expr(rcc->rc_eq_eval, const_values, rce);
343     if (isnan(bits)) {
344         av_log(s->avctx, AV_LOG_ERROR, "Error evaluating rc_eq \"%s\"\n", s->avctx->rc_eq);
345         return -1;
346     }
347
348     rcc->pass1_rc_eq_output_sum+= bits;
349     bits*=rate_factor;
350     if(bits<0.0) bits=0.0;
351     bits+= 1.0; //avoid 1/0 issues
352
353     /* user override */
354     for(i=0; i<s->avctx->rc_override_count; i++){
355         RcOverride *rco= s->avctx->rc_override;
356         if(rco[i].start_frame > frame_num) continue;
357         if(rco[i].end_frame   < frame_num) continue;
358
359         if(rco[i].qscale)
360             bits= qp2bits(rce, rco[i].qscale); //FIXME move at end to really force it?
361         else
362             bits*= rco[i].quality_factor;
363     }
364
365     q= bits2qp(rce, bits);
366
367     /* I/B difference */
368     if     (pict_type==FF_I_TYPE && s->avctx->i_quant_factor<0.0)
369         q= -q*s->avctx->i_quant_factor + s->avctx->i_quant_offset;
370     else if(pict_type==FF_B_TYPE && s->avctx->b_quant_factor<0.0)
371         q= -q*s->avctx->b_quant_factor + s->avctx->b_quant_offset;
372     if(q<1) q=1;
373
374     return q;
375 }
376
377 static double get_diff_limited_q(MpegEncContext *s, RateControlEntry *rce, double q){
378     RateControlContext *rcc= &s->rc_context;
379     AVCodecContext *a= s->avctx;
380     const int pict_type= rce->new_pict_type;
381     const double last_p_q    = rcc->last_qscale_for[FF_P_TYPE];
382     const double last_non_b_q= rcc->last_qscale_for[rcc->last_non_b_pict_type];
383
384     if     (pict_type==FF_I_TYPE && (a->i_quant_factor>0.0 || rcc->last_non_b_pict_type==FF_P_TYPE))
385         q= last_p_q    *FFABS(a->i_quant_factor) + a->i_quant_offset;
386     else if(pict_type==FF_B_TYPE && a->b_quant_factor>0.0)
387         q= last_non_b_q*    a->b_quant_factor  + a->b_quant_offset;
388     if(q<1) q=1;
389
390     /* last qscale / qdiff stuff */
391     if(rcc->last_non_b_pict_type==pict_type || pict_type!=FF_I_TYPE){
392         double last_q= rcc->last_qscale_for[pict_type];
393         const int maxdiff= FF_QP2LAMBDA * a->max_qdiff;
394
395         if     (q > last_q + maxdiff) q= last_q + maxdiff;
396         else if(q < last_q - maxdiff) q= last_q - maxdiff;
397     }
398
399     rcc->last_qscale_for[pict_type]= q; //Note we cannot do that after blurring
400
401     if(pict_type!=FF_B_TYPE)
402         rcc->last_non_b_pict_type= pict_type;
403
404     return q;
405 }
406
407 /**
408  * gets the qmin & qmax for pict_type
409  */
410 static void get_qminmax(int *qmin_ret, int *qmax_ret, MpegEncContext *s, int pict_type){
411     int qmin= s->avctx->lmin;
412     int qmax= s->avctx->lmax;
413
414     assert(qmin <= qmax);
415
416     if(pict_type==FF_B_TYPE){
417         qmin= (int)(qmin*FFABS(s->avctx->b_quant_factor)+s->avctx->b_quant_offset + 0.5);
418         qmax= (int)(qmax*FFABS(s->avctx->b_quant_factor)+s->avctx->b_quant_offset + 0.5);
419     }else if(pict_type==FF_I_TYPE){
420         qmin= (int)(qmin*FFABS(s->avctx->i_quant_factor)+s->avctx->i_quant_offset + 0.5);
421         qmax= (int)(qmax*FFABS(s->avctx->i_quant_factor)+s->avctx->i_quant_offset + 0.5);
422     }
423
424     qmin= av_clip(qmin, 1, FF_LAMBDA_MAX);
425     qmax= av_clip(qmax, 1, FF_LAMBDA_MAX);
426
427     if(qmax<qmin) qmax= qmin;
428
429     *qmin_ret= qmin;
430     *qmax_ret= qmax;
431 }
432
433 static double modify_qscale(MpegEncContext *s, RateControlEntry *rce, double q, int frame_num){
434     RateControlContext *rcc= &s->rc_context;
435     int qmin, qmax;
436     const int pict_type= rce->new_pict_type;
437     const double buffer_size= s->avctx->rc_buffer_size;
438     const double fps= 1/av_q2d(s->avctx->time_base);
439     const double min_rate= s->avctx->rc_min_rate / fps;
440     const double max_rate= s->avctx->rc_max_rate / fps;
441
442     get_qminmax(&qmin, &qmax, s, pict_type);
443
444     /* modulation */
445     if(s->avctx->rc_qmod_freq && frame_num%s->avctx->rc_qmod_freq==0 && pict_type==FF_P_TYPE)
446         q*= s->avctx->rc_qmod_amp;
447
448 //printf("q:%f\n", q);
449     /* buffer overflow/underflow protection */
450     if(buffer_size){
451         double expected_size= rcc->buffer_index;
452         double q_limit;
453
454         if(min_rate){
455             double d= 2*(buffer_size - expected_size)/buffer_size;
456             if(d>1.0) d=1.0;
457             else if(d<0.0001) d=0.0001;
458             q*= pow(d, 1.0/s->avctx->rc_buffer_aggressivity);
459
460             q_limit= bits2qp(rce, FFMAX((min_rate - buffer_size + rcc->buffer_index) * s->avctx->rc_min_vbv_overflow_use, 1));
461             if(q > q_limit){
462                 if(s->avctx->debug&FF_DEBUG_RC){
463                     av_log(s->avctx, AV_LOG_DEBUG, "limiting QP %f -> %f\n", q, q_limit);
464                 }
465                 q= q_limit;
466             }
467         }
468
469         if(max_rate){
470             double d= 2*expected_size/buffer_size;
471             if(d>1.0) d=1.0;
472             else if(d<0.0001) d=0.0001;
473             q/= pow(d, 1.0/s->avctx->rc_buffer_aggressivity);
474
475             q_limit= bits2qp(rce, FFMAX(rcc->buffer_index * s->avctx->rc_max_available_vbv_use, 1));
476             if(q < q_limit){
477                 if(s->avctx->debug&FF_DEBUG_RC){
478                     av_log(s->avctx, AV_LOG_DEBUG, "limiting QP %f -> %f\n", q, q_limit);
479                 }
480                 q= q_limit;
481             }
482         }
483     }
484 //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);
485     if(s->avctx->rc_qsquish==0.0 || qmin==qmax){
486         if     (q<qmin) q=qmin;
487         else if(q>qmax) q=qmax;
488     }else{
489         double min2= log(qmin);
490         double max2= log(qmax);
491
492         q= log(q);
493         q= (q - min2)/(max2-min2) - 0.5;
494         q*= -4.0;
495         q= 1.0/(1.0 + exp(q));
496         q= q*(max2-min2) + min2;
497
498         q= exp(q);
499     }
500
501     return q;
502 }
503
504 //----------------------------------
505 // 1 Pass Code
506
507 static double predict_size(Predictor *p, double q, double var)
508 {
509      return p->coeff*var / (q*p->count);
510 }
511
512 /*
513 static double predict_qp(Predictor *p, double size, double var)
514 {
515 //printf("coeff:%f, count:%f, var:%f, size:%f//\n", p->coeff, p->count, var, size);
516      return p->coeff*var / (size*p->count);
517 }
518 */
519
520 static void update_predictor(Predictor *p, double q, double var, double size)
521 {
522     double new_coeff= size*q / (var + 1);
523     if(var<10) return;
524
525     p->count*= p->decay;
526     p->coeff*= p->decay;
527     p->count++;
528     p->coeff+= new_coeff;
529 }
530
531 static void adaptive_quantization(MpegEncContext *s, double q){
532     int i;
533     const float lumi_masking= s->avctx->lumi_masking / (128.0*128.0);
534     const float dark_masking= s->avctx->dark_masking / (128.0*128.0);
535     const float temp_cplx_masking= s->avctx->temporal_cplx_masking;
536     const float spatial_cplx_masking = s->avctx->spatial_cplx_masking;
537     const float p_masking = s->avctx->p_masking;
538     const float border_masking = s->avctx->border_masking;
539     float bits_sum= 0.0;
540     float cplx_sum= 0.0;
541     float cplx_tab[s->mb_num];
542     float bits_tab[s->mb_num];
543     const int qmin= s->avctx->mb_lmin;
544     const int qmax= s->avctx->mb_lmax;
545     Picture * const pic= &s->current_picture;
546     const int mb_width = s->mb_width;
547     const int mb_height = s->mb_height;
548
549     for(i=0; i<s->mb_num; i++){
550         const int mb_xy= s->mb_index2xy[i];
551         float temp_cplx= sqrt(pic->mc_mb_var[mb_xy]); //FIXME merge in pow()
552         float spat_cplx= sqrt(pic->mb_var[mb_xy]);
553         const int lumi= pic->mb_mean[mb_xy];
554         float bits, cplx, factor;
555         int mb_x = mb_xy % s->mb_stride;
556         int mb_y = mb_xy / s->mb_stride;
557         int mb_distance;
558         float mb_factor = 0.0;
559 #if 0
560         if(spat_cplx < q/3) spat_cplx= q/3; //FIXME finetune
561         if(temp_cplx < q/3) temp_cplx= q/3; //FIXME finetune
562 #endif
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= 1/av_q2d(s->avctx->time_base);
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 == FF_I_TYPE ? rcc->last_mb_var_sum : rcc->last_mc_mb_var_sum;
689         update_predictor(&rcc->pred[s->last_pict_type], rcc->last_qscale, sqrt(last_var), s->frame_bits);
690     }
691
692     if(s->flags&CODEC_FLAG_PASS2){
693         assert(picture_number>=0);
694         assert(picture_number<rcc->num_entries);
695         rce= &rcc->entry[picture_number];
696         wanted_bits= rce->expected_bits;
697     }else{
698         Picture *dts_pic;
699         rce= &local_rce;
700
701         //FIXME add a dts field to AVFrame and ensure its set and use it here instead of reordering
702         //but the reordering is simpler for now until h.264 b pyramid must be handeld
703         if(s->pict_type == FF_B_TYPE || s->low_delay)
704             dts_pic= s->current_picture_ptr;
705         else
706             dts_pic= s->last_picture_ptr;
707
708 //if(dts_pic)
709 //            av_log(NULL, AV_LOG_ERROR, "%Ld %Ld %Ld %d\n", s->current_picture_ptr->pts, s->user_specified_pts, dts_pic->pts, picture_number);
710
711         if(!dts_pic || dts_pic->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->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 == FF_I_TYPE ? 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!=FF_I_TYPE)
726             assert(pict_type == rce->new_pict_type);
727
728         q= rce->new_qscale / br_compensation;
729 //printf("%f %f %f last:%d var:%d type:%d//\n", q, rce->new_qscale, br_compensation, s->frame_bits, var, pict_type);
730     }else{
731         rce->pict_type=
732         rce->new_pict_type= pict_type;
733         rce->mc_mb_var_sum= pic->mc_mb_var_sum;
734         rce->mb_var_sum   = pic->   mb_var_sum;
735         rce->qscale   = FF_QP2LAMBDA * 2;
736         rce->f_code   = s->f_code;
737         rce->b_code   = s->b_code;
738         rce->misc_bits= 1;
739
740         bits= predict_size(&rcc->pred[pict_type], rce->qscale, sqrt(var));
741         if(pict_type== FF_I_TYPE){
742             rce->i_count   = s->mb_num;
743             rce->i_tex_bits= bits;
744             rce->p_tex_bits= 0;
745             rce->mv_bits= 0;
746         }else{
747             rce->i_count   = 0; //FIXME we do know this approx
748             rce->i_tex_bits= 0;
749             rce->p_tex_bits= bits*0.9;
750
751             rce->mv_bits= bits*0.1;
752         }
753         rcc->i_cplx_sum [pict_type] += rce->i_tex_bits*rce->qscale;
754         rcc->p_cplx_sum [pict_type] += rce->p_tex_bits*rce->qscale;
755         rcc->mv_bits_sum[pict_type] += rce->mv_bits;
756         rcc->frame_count[pict_type] ++;
757
758         bits= rce->i_tex_bits + rce->p_tex_bits;
759         rate_factor= rcc->pass1_wanted_bits/rcc->pass1_rc_eq_output_sum * br_compensation;
760
761         q= get_qscale(s, rce, rate_factor, picture_number);
762         if (q < 0)
763             return -1;
764
765         assert(q>0.0);
766 //printf("%f ", q);
767         q= get_diff_limited_q(s, rce, q);
768 //printf("%f ", q);
769         assert(q>0.0);
770
771         if(pict_type==FF_P_TYPE || s->intra_only){ //FIXME type dependent blur like in 2-pass
772             rcc->short_term_qsum*=a->qblur;
773             rcc->short_term_qcount*=a->qblur;
774
775             rcc->short_term_qsum+= q;
776             rcc->short_term_qcount++;
777 //printf("%f ", q);
778             q= short_term_q= rcc->short_term_qsum/rcc->short_term_qcount;
779 //printf("%f ", q);
780         }
781         assert(q>0.0);
782
783         q= modify_qscale(s, rce, q, picture_number);
784
785         rcc->pass1_wanted_bits+= s->bit_rate/fps;
786
787         assert(q>0.0);
788     }
789
790     if(s->avctx->debug&FF_DEBUG_RC){
791         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",
792         av_get_pict_type_char(pict_type), qmin, q, qmax, picture_number, (int)wanted_bits/1000, (int)s->total_bits/1000,
793         br_compensation, short_term_q, s->frame_bits, pic->mb_var_sum, pic->mc_mb_var_sum, s->bit_rate/1000, (int)fps
794         );
795     }
796
797     if     (q<qmin) q=qmin;
798     else if(q>qmax) q=qmax;
799
800     if(s->adaptive_quant)
801         adaptive_quantization(s, q);
802     else
803         q= (int)(q + 0.5);
804
805     if(!dry_run){
806         rcc->last_qscale= q;
807         rcc->last_mc_mb_var_sum= pic->mc_mb_var_sum;
808         rcc->last_mb_var_sum= pic->mb_var_sum;
809     }
810 #if 0
811 {
812     static int mvsum=0, texsum=0;
813     mvsum += s->mv_bits;
814     texsum += s->i_tex_bits + s->p_tex_bits;
815     printf("%d %d//\n\n", mvsum, texsum);
816 }
817 #endif
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= 1/av_q2d(s->avctx->time_base);
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[FF_I_TYPE] + const_bits[FF_P_TYPE] + const_bits[FF_B_TYPE];
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             qscale[i]= get_qscale(s, &rcc->entry[i], rate_factor, i);
874         }
875         assert(filter_size%2==1);
876
877         /* fixed I/B QP relative to P mode */
878         for(i=rcc->num_entries-1; i>=0; i--){
879             RateControlEntry *rce= &rcc->entry[i];
880
881             qscale[i]= get_diff_limited_q(s, rce, qscale[i]);
882         }
883
884         /* smooth curve */
885         for(i=0; i<rcc->num_entries; i++){
886             RateControlEntry *rce= &rcc->entry[i];
887             const int pict_type= rce->new_pict_type;
888             int j;
889             double q=0.0, sum=0.0;
890
891             for(j=0; j<filter_size; j++){
892                 int index= i+j-filter_size/2;
893                 double d= index-i;
894                 double coeff= a->qblur==0 ? 1.0 : exp(-d*d/(a->qblur * a->qblur));
895
896                 if(index < 0 || index >= rcc->num_entries) continue;
897                 if(pict_type != rcc->entry[index].new_pict_type) continue;
898                 q+= qscale[index] * coeff;
899                 sum+= coeff;
900             }
901             blurred_qscale[i]= q/sum;
902         }
903
904         /* find expected bits */
905         for(i=0; i<rcc->num_entries; i++){
906             RateControlEntry *rce= &rcc->entry[i];
907             double bits;
908             rce->new_qscale= modify_qscale(s, rce, blurred_qscale[i], i);
909             bits= qp2bits(rce, rce->new_qscale) + rce->mv_bits + rce->misc_bits;
910 //printf("%d %f\n", rce->new_bits, blurred_qscale[i]);
911             bits += 8*ff_vbv_update(s, bits);
912
913             rce->expected_bits= expected_bits;
914             expected_bits += bits;
915         }
916
917         /*
918         av_log(s->avctx, AV_LOG_INFO,
919             "expected_bits: %f all_available_bits: %d rate_factor: %f\n",
920             expected_bits, (int)all_available_bits, rate_factor);
921         */
922         if(expected_bits > all_available_bits) {
923             rate_factor-= step;
924             ++toobig;
925         }
926     }
927     av_free(qscale);
928     av_free(blurred_qscale);
929
930     /* check bitrate calculations and print info */
931     qscale_sum = 0.0;
932     for(i=0; i<rcc->num_entries; i++){
933         /* av_log(s->avctx, AV_LOG_DEBUG, "[lavc rc] entry[%d].new_qscale = %.3f  qp = %.3f\n",
934             i, rcc->entry[i].new_qscale, rcc->entry[i].new_qscale / FF_QP2LAMBDA); */
935         qscale_sum += av_clip(rcc->entry[i].new_qscale / FF_QP2LAMBDA, s->avctx->qmin, s->avctx->qmax);
936     }
937     assert(toobig <= 40);
938     av_log(s->avctx, AV_LOG_DEBUG,
939         "[lavc rc] requested bitrate: %d bps  expected bitrate: %d bps\n",
940         s->bit_rate,
941         (int)(expected_bits / ((double)all_available_bits/s->bit_rate)));
942     av_log(s->avctx, AV_LOG_DEBUG,
943         "[lavc rc] estimated target average qp: %.3f\n",
944         (float)qscale_sum / rcc->num_entries);
945     if (toobig == 0) {
946         av_log(s->avctx, AV_LOG_INFO,
947             "[lavc rc] Using all of requested bitrate is not "
948             "necessary for this video with these parameters.\n");
949     } else if (toobig == 40) {
950         av_log(s->avctx, AV_LOG_ERROR,
951             "[lavc rc] Error: bitrate too low for this video "
952             "with these parameters.\n");
953         return -1;
954     } else if (fabs(expected_bits/all_available_bits - 1.0) > 0.01) {
955         av_log(s->avctx, AV_LOG_ERROR,
956             "[lavc rc] Error: 2pass curve failed to converge\n");
957         return -1;
958     }
959
960     return 0;
961 }