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 static void update_predictor(Predictor *p, double q, double var, double size)
518 {
519     double new_coeff= size*q / (var + 1);
520     if(var<10) return;
521
522     p->count*= p->decay;
523     p->coeff*= p->decay;
524     p->count++;
525     p->coeff+= new_coeff;
526 }
527
528 static void adaptive_quantization(MpegEncContext *s, double q){
529     int i;
530     const float lumi_masking= s->avctx->lumi_masking / (128.0*128.0);
531     const float dark_masking= s->avctx->dark_masking / (128.0*128.0);
532     const float temp_cplx_masking= s->avctx->temporal_cplx_masking;
533     const float spatial_cplx_masking = s->avctx->spatial_cplx_masking;
534     const float p_masking = s->avctx->p_masking;
535     const float border_masking = s->avctx->border_masking;
536     float bits_sum= 0.0;
537     float cplx_sum= 0.0;
538     float *cplx_tab = av_malloc(s->mb_num * sizeof(*cplx_tab));
539     float *bits_tab = av_malloc(s->mb_num * sizeof(*bits_tab));
540     const int qmin= s->avctx->mb_lmin;
541     const int qmax= s->avctx->mb_lmax;
542     Picture * const pic= &s->current_picture;
543     const int mb_width = s->mb_width;
544     const int mb_height = s->mb_height;
545
546     for(i=0; i<s->mb_num; i++){
547         const int mb_xy= s->mb_index2xy[i];
548         float temp_cplx= sqrt(pic->mc_mb_var[mb_xy]); //FIXME merge in pow()
549         float spat_cplx= sqrt(pic->mb_var[mb_xy]);
550         const int lumi= pic->mb_mean[mb_xy];
551         float bits, cplx, factor;
552         int mb_x = mb_xy % s->mb_stride;
553         int mb_y = mb_xy / s->mb_stride;
554         int mb_distance;
555         float mb_factor = 0.0;
556         if(spat_cplx < 4) spat_cplx= 4; //FIXME finetune
557         if(temp_cplx < 4) temp_cplx= 4; //FIXME finetune
558
559         if((s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_INTRA)){//FIXME hq mode
560             cplx= spat_cplx;
561             factor= 1.0 + p_masking;
562         }else{
563             cplx= temp_cplx;
564             factor= pow(temp_cplx, - temp_cplx_masking);
565         }
566         factor*=pow(spat_cplx, - spatial_cplx_masking);
567
568         if(lumi>127)
569             factor*= (1.0 - (lumi-128)*(lumi-128)*lumi_masking);
570         else
571             factor*= (1.0 - (lumi-128)*(lumi-128)*dark_masking);
572
573         if(mb_x < mb_width/5){
574             mb_distance = mb_width/5 - mb_x;
575             mb_factor = (float)mb_distance / (float)(mb_width/5);
576         }else if(mb_x > 4*mb_width/5){
577             mb_distance = mb_x - 4*mb_width/5;
578             mb_factor = (float)mb_distance / (float)(mb_width/5);
579         }
580         if(mb_y < mb_height/5){
581             mb_distance = mb_height/5 - mb_y;
582             mb_factor = FFMAX(mb_factor, (float)mb_distance / (float)(mb_height/5));
583         }else if(mb_y > 4*mb_height/5){
584             mb_distance = mb_y - 4*mb_height/5;
585             mb_factor = FFMAX(mb_factor, (float)mb_distance / (float)(mb_height/5));
586         }
587
588         factor*= 1.0 - border_masking*mb_factor;
589
590         if(factor<0.00001) factor= 0.00001;
591
592         bits= cplx*factor;
593         cplx_sum+= cplx;
594         bits_sum+= bits;
595         cplx_tab[i]= cplx;
596         bits_tab[i]= bits;
597     }
598
599     /* handle qmin/qmax clipping */
600     if(s->flags&CODEC_FLAG_NORMALIZE_AQP){
601         float factor= bits_sum/cplx_sum;
602         for(i=0; i<s->mb_num; i++){
603             float newq= q*cplx_tab[i]/bits_tab[i];
604             newq*= factor;
605
606             if     (newq > qmax){
607                 bits_sum -= bits_tab[i];
608                 cplx_sum -= cplx_tab[i]*q/qmax;
609             }
610             else if(newq < qmin){
611                 bits_sum -= bits_tab[i];
612                 cplx_sum -= cplx_tab[i]*q/qmin;
613             }
614         }
615         if(bits_sum < 0.001) bits_sum= 0.001;
616         if(cplx_sum < 0.001) cplx_sum= 0.001;
617     }
618
619     for(i=0; i<s->mb_num; i++){
620         const int mb_xy= s->mb_index2xy[i];
621         float newq= q*cplx_tab[i]/bits_tab[i];
622         int intq;
623
624         if(s->flags&CODEC_FLAG_NORMALIZE_AQP){
625             newq*= bits_sum/cplx_sum;
626         }
627
628         intq= (int)(newq + 0.5);
629
630         if     (intq > qmax) intq= qmax;
631         else if(intq < qmin) intq= qmin;
632 //if(i%s->mb_width==0) printf("\n");
633 //printf("%2d%3d ", intq, ff_sqrt(s->mc_mb_var[i]));
634         s->lambda_table[mb_xy]= intq;
635     }
636
637     av_free(cplx_tab);
638     av_free(bits_tab);
639 }
640
641 void ff_get_2pass_fcode(MpegEncContext *s){
642     RateControlContext *rcc= &s->rc_context;
643     int picture_number= s->picture_number;
644     RateControlEntry *rce;
645
646     rce= &rcc->entry[picture_number];
647     s->f_code= rce->f_code;
648     s->b_code= rce->b_code;
649 }
650
651 //FIXME rd or at least approx for dquant
652
653 float ff_rate_estimate_qscale(MpegEncContext *s, int dry_run)
654 {
655     float q;
656     int qmin, qmax;
657     float br_compensation;
658     double diff;
659     double short_term_q;
660     double fps;
661     int picture_number= s->picture_number;
662     int64_t wanted_bits;
663     RateControlContext *rcc= &s->rc_context;
664     AVCodecContext *a= s->avctx;
665     RateControlEntry local_rce, *rce;
666     double bits;
667     double rate_factor;
668     int var;
669     const int pict_type= s->pict_type;
670     Picture * const pic= &s->current_picture;
671     emms_c();
672
673 #if CONFIG_LIBXVID
674     if((s->flags&CODEC_FLAG_PASS2) && s->avctx->rc_strategy == FF_RC_STRATEGY_XVID)
675         return ff_xvid_rate_estimate_qscale(s, dry_run);
676 #endif
677
678     get_qminmax(&qmin, &qmax, s, pict_type);
679
680     fps= get_fps(s->avctx);
681 //printf("input_pic_num:%d pic_num:%d frame_rate:%d\n", s->input_picture_number, s->picture_number, s->frame_rate);
682         /* update predictors */
683     if(picture_number>2 && !dry_run){
684         const int last_var= s->last_pict_type == AV_PICTURE_TYPE_I ? rcc->last_mb_var_sum : rcc->last_mc_mb_var_sum;
685         update_predictor(&rcc->pred[s->last_pict_type], rcc->last_qscale, sqrt(last_var), s->frame_bits);
686     }
687
688     if(s->flags&CODEC_FLAG_PASS2){
689         assert(picture_number>=0);
690         assert(picture_number<rcc->num_entries);
691         rce= &rcc->entry[picture_number];
692         wanted_bits= rce->expected_bits;
693     }else{
694         Picture *dts_pic;
695         rce= &local_rce;
696
697         //FIXME add a dts field to AVFrame and ensure its set and use it here instead of reordering
698         //but the reordering is simpler for now until h.264 b pyramid must be handeld
699         if(s->pict_type == AV_PICTURE_TYPE_B || s->low_delay)
700             dts_pic= s->current_picture_ptr;
701         else
702             dts_pic= s->last_picture_ptr;
703
704 //if(dts_pic)
705 //            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);
706
707         if (!dts_pic || dts_pic->f.pts == AV_NOPTS_VALUE)
708             wanted_bits= (uint64_t)(s->bit_rate*(double)picture_number/fps);
709         else
710             wanted_bits = (uint64_t)(s->bit_rate*(double)dts_pic->f.pts / fps);
711     }
712
713     diff= s->total_bits - wanted_bits;
714     br_compensation= (a->bit_rate_tolerance - diff)/a->bit_rate_tolerance;
715     if(br_compensation<=0.0) br_compensation=0.001;
716
717     var= pict_type == AV_PICTURE_TYPE_I ? pic->mb_var_sum : pic->mc_mb_var_sum;
718
719     short_term_q = 0; /* avoid warning */
720     if(s->flags&CODEC_FLAG_PASS2){
721         if(pict_type!=AV_PICTURE_TYPE_I)
722             assert(pict_type == rce->new_pict_type);
723
724         q= rce->new_qscale / br_compensation;
725 //printf("%f %f %f last:%d var:%d type:%d//\n", q, rce->new_qscale, br_compensation, s->frame_bits, var, pict_type);
726     }else{
727         rce->pict_type=
728         rce->new_pict_type= pict_type;
729         rce->mc_mb_var_sum= pic->mc_mb_var_sum;
730         rce->mb_var_sum   = pic->   mb_var_sum;
731         rce->qscale   = FF_QP2LAMBDA * 2;
732         rce->f_code   = s->f_code;
733         rce->b_code   = s->b_code;
734         rce->misc_bits= 1;
735
736         bits= predict_size(&rcc->pred[pict_type], rce->qscale, sqrt(var));
737         if(pict_type== AV_PICTURE_TYPE_I){
738             rce->i_count   = s->mb_num;
739             rce->i_tex_bits= bits;
740             rce->p_tex_bits= 0;
741             rce->mv_bits= 0;
742         }else{
743             rce->i_count   = 0; //FIXME we do know this approx
744             rce->i_tex_bits= 0;
745             rce->p_tex_bits= bits*0.9;
746
747             rce->mv_bits= bits*0.1;
748         }
749         rcc->i_cplx_sum [pict_type] += rce->i_tex_bits*rce->qscale;
750         rcc->p_cplx_sum [pict_type] += rce->p_tex_bits*rce->qscale;
751         rcc->mv_bits_sum[pict_type] += rce->mv_bits;
752         rcc->frame_count[pict_type] ++;
753
754         bits= rce->i_tex_bits + rce->p_tex_bits;
755         rate_factor= rcc->pass1_wanted_bits/rcc->pass1_rc_eq_output_sum * br_compensation;
756
757         q= get_qscale(s, rce, rate_factor, picture_number);
758         if (q < 0)
759             return -1;
760
761         assert(q>0.0);
762 //printf("%f ", q);
763         q= get_diff_limited_q(s, rce, q);
764 //printf("%f ", q);
765         assert(q>0.0);
766
767         if(pict_type==AV_PICTURE_TYPE_P || s->intra_only){ //FIXME type dependent blur like in 2-pass
768             rcc->short_term_qsum*=a->qblur;
769             rcc->short_term_qcount*=a->qblur;
770
771             rcc->short_term_qsum+= q;
772             rcc->short_term_qcount++;
773 //printf("%f ", q);
774             q= short_term_q= rcc->short_term_qsum/rcc->short_term_qcount;
775 //printf("%f ", q);
776         }
777         assert(q>0.0);
778
779         q= modify_qscale(s, rce, q, picture_number);
780
781         rcc->pass1_wanted_bits+= s->bit_rate/fps;
782
783         assert(q>0.0);
784     }
785
786     if(s->avctx->debug&FF_DEBUG_RC){
787         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",
788         av_get_picture_type_char(pict_type), qmin, q, qmax, picture_number, (int)wanted_bits/1000, (int)s->total_bits/1000,
789         br_compensation, short_term_q, s->frame_bits, pic->mb_var_sum, pic->mc_mb_var_sum, s->bit_rate/1000, (int)fps
790         );
791     }
792
793     if     (q<qmin) q=qmin;
794     else if(q>qmax) q=qmax;
795
796     if(s->adaptive_quant)
797         adaptive_quantization(s, q);
798     else
799         q= (int)(q + 0.5);
800
801     if(!dry_run){
802         rcc->last_qscale= q;
803         rcc->last_mc_mb_var_sum= pic->mc_mb_var_sum;
804         rcc->last_mb_var_sum= pic->mb_var_sum;
805     }
806     return q;
807 }
808
809 //----------------------------------------------
810 // 2-Pass code
811
812 static int init_pass2(MpegEncContext *s)
813 {
814     RateControlContext *rcc= &s->rc_context;
815     AVCodecContext *a= s->avctx;
816     int i, toobig;
817     double fps= get_fps(s->avctx);
818     double complexity[5]={0,0,0,0,0};   // aproximate bits at quant=1
819     uint64_t const_bits[5]={0,0,0,0,0}; // quantizer independent bits
820     uint64_t all_const_bits;
821     uint64_t all_available_bits= (uint64_t)(s->bit_rate*(double)rcc->num_entries/fps);
822     double rate_factor=0;
823     double step;
824     //int last_i_frame=-10000000;
825     const int filter_size= (int)(a->qblur*4) | 1;
826     double expected_bits;
827     double *qscale, *blurred_qscale, qscale_sum;
828
829     /* find complexity & const_bits & decide the pict_types */
830     for(i=0; i<rcc->num_entries; i++){
831         RateControlEntry *rce= &rcc->entry[i];
832
833         rce->new_pict_type= rce->pict_type;
834         rcc->i_cplx_sum [rce->pict_type] += rce->i_tex_bits*rce->qscale;
835         rcc->p_cplx_sum [rce->pict_type] += rce->p_tex_bits*rce->qscale;
836         rcc->mv_bits_sum[rce->pict_type] += rce->mv_bits;
837         rcc->frame_count[rce->pict_type] ++;
838
839         complexity[rce->new_pict_type]+= (rce->i_tex_bits+ rce->p_tex_bits)*(double)rce->qscale;
840         const_bits[rce->new_pict_type]+= rce->mv_bits + rce->misc_bits;
841     }
842     all_const_bits= const_bits[AV_PICTURE_TYPE_I] + const_bits[AV_PICTURE_TYPE_P] + const_bits[AV_PICTURE_TYPE_B];
843
844     if(all_available_bits < all_const_bits){
845         av_log(s->avctx, AV_LOG_ERROR, "requested bitrate is too low\n");
846         return -1;
847     }
848
849     qscale= av_malloc(sizeof(double)*rcc->num_entries);
850     blurred_qscale= av_malloc(sizeof(double)*rcc->num_entries);
851     toobig = 0;
852
853     for(step=256*256; step>0.0000001; step*=0.5){
854         expected_bits=0;
855         rate_factor+= step;
856
857         rcc->buffer_index= s->avctx->rc_buffer_size/2;
858
859         /* find qscale */
860         for(i=0; i<rcc->num_entries; i++){
861             RateControlEntry *rce= &rcc->entry[i];
862             qscale[i]= get_qscale(s, &rcc->entry[i], rate_factor, i);
863             rcc->last_qscale_for[rce->pict_type] = qscale[i];
864         }
865         assert(filter_size%2==1);
866
867         /* fixed I/B QP relative to P mode */
868         for(i=FFMAX(0, rcc->num_entries-300); i<rcc->num_entries; i++){
869             RateControlEntry *rce= &rcc->entry[i];
870
871             qscale[i]= get_diff_limited_q(s, rce, qscale[i]);
872         }
873
874         for(i=rcc->num_entries-1; i>=0; i--){
875             RateControlEntry *rce= &rcc->entry[i];
876
877             qscale[i]= get_diff_limited_q(s, rce, qscale[i]);
878         }
879
880         /* smooth curve */
881         for(i=0; i<rcc->num_entries; i++){
882             RateControlEntry *rce= &rcc->entry[i];
883             const int pict_type= rce->new_pict_type;
884             int j;
885             double q=0.0, sum=0.0;
886
887             for(j=0; j<filter_size; j++){
888                 int index= i+j-filter_size/2;
889                 double d= index-i;
890                 double coeff= a->qblur==0 ? 1.0 : exp(-d*d/(a->qblur * a->qblur));
891
892                 if(index < 0 || index >= rcc->num_entries) continue;
893                 if(pict_type != rcc->entry[index].new_pict_type) continue;
894                 q+= qscale[index] * coeff;
895                 sum+= coeff;
896             }
897             blurred_qscale[i]= q/sum;
898         }
899
900         /* find expected bits */
901         for(i=0; i<rcc->num_entries; i++){
902             RateControlEntry *rce= &rcc->entry[i];
903             double bits;
904             rce->new_qscale= modify_qscale(s, rce, blurred_qscale[i], i);
905             bits= qp2bits(rce, rce->new_qscale) + rce->mv_bits + rce->misc_bits;
906 //printf("%d %f\n", rce->new_bits, blurred_qscale[i]);
907             bits += 8*ff_vbv_update(s, bits);
908
909             rce->expected_bits= expected_bits;
910             expected_bits += bits;
911         }
912
913         /*
914         av_log(s->avctx, AV_LOG_INFO,
915             "expected_bits: %f all_available_bits: %d rate_factor: %f\n",
916             expected_bits, (int)all_available_bits, rate_factor);
917         */
918         if(expected_bits > all_available_bits) {
919             rate_factor-= step;
920             ++toobig;
921         }
922     }
923     av_free(qscale);
924     av_free(blurred_qscale);
925
926     /* check bitrate calculations and print info */
927     qscale_sum = 0.0;
928     for(i=0; i<rcc->num_entries; i++){
929         /* av_log(s->avctx, AV_LOG_DEBUG, "[lavc rc] entry[%d].new_qscale = %.3f  qp = %.3f\n",
930             i, rcc->entry[i].new_qscale, rcc->entry[i].new_qscale / FF_QP2LAMBDA); */
931         qscale_sum += av_clip(rcc->entry[i].new_qscale / FF_QP2LAMBDA, s->avctx->qmin, s->avctx->qmax);
932     }
933     assert(toobig <= 40);
934     av_log(s->avctx, AV_LOG_DEBUG,
935         "[lavc rc] requested bitrate: %d bps  expected bitrate: %d bps\n",
936         s->bit_rate,
937         (int)(expected_bits / ((double)all_available_bits/s->bit_rate)));
938     av_log(s->avctx, AV_LOG_DEBUG,
939         "[lavc rc] estimated target average qp: %.3f\n",
940         (float)qscale_sum / rcc->num_entries);
941     if (toobig == 0) {
942         av_log(s->avctx, AV_LOG_INFO,
943             "[lavc rc] Using all of requested bitrate is not "
944             "necessary for this video with these parameters.\n");
945     } else if (toobig == 40) {
946         av_log(s->avctx, AV_LOG_ERROR,
947             "[lavc rc] Error: bitrate too low for this video "
948             "with these parameters.\n");
949         return -1;
950     } else if (fabs(expected_bits/all_available_bits - 1.0) > 0.01) {
951         av_log(s->avctx, AV_LOG_ERROR,
952             "[lavc rc] Error: 2pass curve failed to converge\n");
953         return -1;
954     }
955
956     return 0;
957 }