Merge commit '36ef5369ee9b336febc2c270f8718cec4476cb85'
[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 == AV_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 = s->cplx_tab;
539     float *bits_tab = s->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
638 void ff_get_2pass_fcode(MpegEncContext *s){
639     RateControlContext *rcc= &s->rc_context;
640     int picture_number= s->picture_number;
641     RateControlEntry *rce;
642
643     rce= &rcc->entry[picture_number];
644     s->f_code= rce->f_code;
645     s->b_code= rce->b_code;
646 }
647
648 //FIXME rd or at least approx for dquant
649
650 float ff_rate_estimate_qscale(MpegEncContext *s, int dry_run)
651 {
652     float q;
653     int qmin, qmax;
654     float br_compensation;
655     double diff;
656     double short_term_q;
657     double fps;
658     int picture_number= s->picture_number;
659     int64_t wanted_bits;
660     RateControlContext *rcc= &s->rc_context;
661     AVCodecContext *a= s->avctx;
662     RateControlEntry local_rce, *rce;
663     double bits;
664     double rate_factor;
665     int var;
666     const int pict_type= s->pict_type;
667     Picture * const pic= &s->current_picture;
668     emms_c();
669
670 #if CONFIG_LIBXVID
671     if((s->flags&CODEC_FLAG_PASS2) && s->avctx->rc_strategy == FF_RC_STRATEGY_XVID)
672         return ff_xvid_rate_estimate_qscale(s, dry_run);
673 #endif
674
675     get_qminmax(&qmin, &qmax, s, pict_type);
676
677     fps= get_fps(s->avctx);
678 //printf("input_pic_num:%d pic_num:%d frame_rate:%d\n", s->input_picture_number, s->picture_number, s->frame_rate);
679         /* update predictors */
680     if(picture_number>2 && !dry_run){
681         const int last_var= s->last_pict_type == AV_PICTURE_TYPE_I ? rcc->last_mb_var_sum : rcc->last_mc_mb_var_sum;
682         update_predictor(&rcc->pred[s->last_pict_type], rcc->last_qscale, sqrt(last_var), s->frame_bits);
683     }
684
685     if(s->flags&CODEC_FLAG_PASS2){
686         assert(picture_number>=0);
687         assert(picture_number<rcc->num_entries);
688         rce= &rcc->entry[picture_number];
689         wanted_bits= rce->expected_bits;
690     }else{
691         Picture *dts_pic;
692         rce= &local_rce;
693
694         //FIXME add a dts field to AVFrame and ensure its set and use it here instead of reordering
695         //but the reordering is simpler for now until h.264 b pyramid must be handeld
696         if(s->pict_type == AV_PICTURE_TYPE_B || s->low_delay)
697             dts_pic= s->current_picture_ptr;
698         else
699             dts_pic= s->last_picture_ptr;
700
701 //if(dts_pic)
702 //            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);
703
704         if (!dts_pic || dts_pic->f.pts == AV_NOPTS_VALUE)
705             wanted_bits= (uint64_t)(s->bit_rate*(double)picture_number/fps);
706         else
707             wanted_bits = (uint64_t)(s->bit_rate*(double)dts_pic->f.pts / fps);
708     }
709
710     diff= s->total_bits - wanted_bits;
711     br_compensation= (a->bit_rate_tolerance - diff)/a->bit_rate_tolerance;
712     if(br_compensation<=0.0) br_compensation=0.001;
713
714     var= pict_type == AV_PICTURE_TYPE_I ? pic->mb_var_sum : pic->mc_mb_var_sum;
715
716     short_term_q = 0; /* avoid warning */
717     if(s->flags&CODEC_FLAG_PASS2){
718         if(pict_type!=AV_PICTURE_TYPE_I)
719             assert(pict_type == rce->new_pict_type);
720
721         q= rce->new_qscale / br_compensation;
722 //printf("%f %f %f last:%d var:%d type:%d//\n", q, rce->new_qscale, br_compensation, s->frame_bits, var, pict_type);
723     }else{
724         rce->pict_type=
725         rce->new_pict_type= pict_type;
726         rce->mc_mb_var_sum= pic->mc_mb_var_sum;
727         rce->mb_var_sum   = pic->   mb_var_sum;
728         rce->qscale   = FF_QP2LAMBDA * 2;
729         rce->f_code   = s->f_code;
730         rce->b_code   = s->b_code;
731         rce->misc_bits= 1;
732
733         bits= predict_size(&rcc->pred[pict_type], rce->qscale, sqrt(var));
734         if(pict_type== AV_PICTURE_TYPE_I){
735             rce->i_count   = s->mb_num;
736             rce->i_tex_bits= bits;
737             rce->p_tex_bits= 0;
738             rce->mv_bits= 0;
739         }else{
740             rce->i_count   = 0; //FIXME we do know this approx
741             rce->i_tex_bits= 0;
742             rce->p_tex_bits= bits*0.9;
743
744             rce->mv_bits= bits*0.1;
745         }
746         rcc->i_cplx_sum [pict_type] += rce->i_tex_bits*rce->qscale;
747         rcc->p_cplx_sum [pict_type] += rce->p_tex_bits*rce->qscale;
748         rcc->mv_bits_sum[pict_type] += rce->mv_bits;
749         rcc->frame_count[pict_type] ++;
750
751         bits= rce->i_tex_bits + rce->p_tex_bits;
752         rate_factor= rcc->pass1_wanted_bits/rcc->pass1_rc_eq_output_sum * br_compensation;
753
754         q= get_qscale(s, rce, rate_factor, picture_number);
755         if (q < 0)
756             return -1;
757
758         assert(q>0.0);
759 //printf("%f ", q);
760         q= get_diff_limited_q(s, rce, q);
761 //printf("%f ", q);
762         assert(q>0.0);
763
764         if(pict_type==AV_PICTURE_TYPE_P || s->intra_only){ //FIXME type dependent blur like in 2-pass
765             rcc->short_term_qsum*=a->qblur;
766             rcc->short_term_qcount*=a->qblur;
767
768             rcc->short_term_qsum+= q;
769             rcc->short_term_qcount++;
770 //printf("%f ", q);
771             q= short_term_q= rcc->short_term_qsum/rcc->short_term_qcount;
772 //printf("%f ", q);
773         }
774         assert(q>0.0);
775
776         q= modify_qscale(s, rce, q, picture_number);
777
778         rcc->pass1_wanted_bits+= s->bit_rate/fps;
779
780         assert(q>0.0);
781     }
782
783     if(s->avctx->debug&FF_DEBUG_RC){
784         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",
785         av_get_picture_type_char(pict_type), qmin, q, qmax, picture_number, (int)wanted_bits/1000, (int)s->total_bits/1000,
786         br_compensation, short_term_q, s->frame_bits, pic->mb_var_sum, pic->mc_mb_var_sum, s->bit_rate/1000, (int)fps
787         );
788     }
789
790     if     (q<qmin) q=qmin;
791     else if(q>qmax) q=qmax;
792
793     if(s->adaptive_quant)
794         adaptive_quantization(s, q);
795     else
796         q= (int)(q + 0.5);
797
798     if(!dry_run){
799         rcc->last_qscale= q;
800         rcc->last_mc_mb_var_sum= pic->mc_mb_var_sum;
801         rcc->last_mb_var_sum= pic->mb_var_sum;
802     }
803     return q;
804 }
805
806 //----------------------------------------------
807 // 2-Pass code
808
809 static int init_pass2(MpegEncContext *s)
810 {
811     RateControlContext *rcc= &s->rc_context;
812     AVCodecContext *a= s->avctx;
813     int i, toobig;
814     double fps= get_fps(s->avctx);
815     double complexity[5]={0,0,0,0,0};   // aproximate bits at quant=1
816     uint64_t const_bits[5]={0,0,0,0,0}; // quantizer independent bits
817     uint64_t all_const_bits;
818     uint64_t all_available_bits= (uint64_t)(s->bit_rate*(double)rcc->num_entries/fps);
819     double rate_factor=0;
820     double step;
821     //int last_i_frame=-10000000;
822     const int filter_size= (int)(a->qblur*4) | 1;
823     double expected_bits;
824     double *qscale, *blurred_qscale, qscale_sum;
825
826     /* find complexity & const_bits & decide the pict_types */
827     for(i=0; i<rcc->num_entries; i++){
828         RateControlEntry *rce= &rcc->entry[i];
829
830         rce->new_pict_type= rce->pict_type;
831         rcc->i_cplx_sum [rce->pict_type] += rce->i_tex_bits*rce->qscale;
832         rcc->p_cplx_sum [rce->pict_type] += rce->p_tex_bits*rce->qscale;
833         rcc->mv_bits_sum[rce->pict_type] += rce->mv_bits;
834         rcc->frame_count[rce->pict_type] ++;
835
836         complexity[rce->new_pict_type]+= (rce->i_tex_bits+ rce->p_tex_bits)*(double)rce->qscale;
837         const_bits[rce->new_pict_type]+= rce->mv_bits + rce->misc_bits;
838     }
839     all_const_bits= const_bits[AV_PICTURE_TYPE_I] + const_bits[AV_PICTURE_TYPE_P] + const_bits[AV_PICTURE_TYPE_B];
840
841     if(all_available_bits < all_const_bits){
842         av_log(s->avctx, AV_LOG_ERROR, "requested bitrate is too low\n");
843         return -1;
844     }
845
846     qscale= av_malloc(sizeof(double)*rcc->num_entries);
847     blurred_qscale= av_malloc(sizeof(double)*rcc->num_entries);
848     toobig = 0;
849
850     for(step=256*256; step>0.0000001; step*=0.5){
851         expected_bits=0;
852         rate_factor+= step;
853
854         rcc->buffer_index= s->avctx->rc_buffer_size/2;
855
856         /* find qscale */
857         for(i=0; i<rcc->num_entries; i++){
858             RateControlEntry *rce= &rcc->entry[i];
859             qscale[i]= get_qscale(s, &rcc->entry[i], rate_factor, i);
860             rcc->last_qscale_for[rce->pict_type] = qscale[i];
861         }
862         assert(filter_size%2==1);
863
864         /* fixed I/B QP relative to P mode */
865         for(i=FFMAX(0, rcc->num_entries-300); i<rcc->num_entries; i++){
866             RateControlEntry *rce= &rcc->entry[i];
867
868             qscale[i]= get_diff_limited_q(s, rce, qscale[i]);
869         }
870
871         for(i=rcc->num_entries-1; i>=0; i--){
872             RateControlEntry *rce= &rcc->entry[i];
873
874             qscale[i]= get_diff_limited_q(s, rce, qscale[i]);
875         }
876
877         /* smooth curve */
878         for(i=0; i<rcc->num_entries; i++){
879             RateControlEntry *rce= &rcc->entry[i];
880             const int pict_type= rce->new_pict_type;
881             int j;
882             double q=0.0, sum=0.0;
883
884             for(j=0; j<filter_size; j++){
885                 int index= i+j-filter_size/2;
886                 double d= index-i;
887                 double coeff= a->qblur==0 ? 1.0 : exp(-d*d/(a->qblur * a->qblur));
888
889                 if(index < 0 || index >= rcc->num_entries) continue;
890                 if(pict_type != rcc->entry[index].new_pict_type) continue;
891                 q+= qscale[index] * coeff;
892                 sum+= coeff;
893             }
894             blurred_qscale[i]= q/sum;
895         }
896
897         /* find expected bits */
898         for(i=0; i<rcc->num_entries; i++){
899             RateControlEntry *rce= &rcc->entry[i];
900             double bits;
901             rce->new_qscale= modify_qscale(s, rce, blurred_qscale[i], i);
902             bits= qp2bits(rce, rce->new_qscale) + rce->mv_bits + rce->misc_bits;
903 //printf("%d %f\n", rce->new_bits, blurred_qscale[i]);
904             bits += 8*ff_vbv_update(s, bits);
905
906             rce->expected_bits= expected_bits;
907             expected_bits += bits;
908         }
909
910         /*
911         av_log(s->avctx, AV_LOG_INFO,
912             "expected_bits: %f all_available_bits: %d rate_factor: %f\n",
913             expected_bits, (int)all_available_bits, rate_factor);
914         */
915         if(expected_bits > all_available_bits) {
916             rate_factor-= step;
917             ++toobig;
918         }
919     }
920     av_free(qscale);
921     av_free(blurred_qscale);
922
923     /* check bitrate calculations and print info */
924     qscale_sum = 0.0;
925     for(i=0; i<rcc->num_entries; i++){
926         /* av_log(s->avctx, AV_LOG_DEBUG, "[lavc rc] entry[%d].new_qscale = %.3f  qp = %.3f\n",
927             i, rcc->entry[i].new_qscale, rcc->entry[i].new_qscale / FF_QP2LAMBDA); */
928         qscale_sum += av_clip(rcc->entry[i].new_qscale / FF_QP2LAMBDA, s->avctx->qmin, s->avctx->qmax);
929     }
930     assert(toobig <= 40);
931     av_log(s->avctx, AV_LOG_DEBUG,
932         "[lavc rc] requested bitrate: %d bps  expected bitrate: %d bps\n",
933         s->bit_rate,
934         (int)(expected_bits / ((double)all_available_bits/s->bit_rate)));
935     av_log(s->avctx, AV_LOG_DEBUG,
936         "[lavc rc] estimated target average qp: %.3f\n",
937         (float)qscale_sum / rcc->num_entries);
938     if (toobig == 0) {
939         av_log(s->avctx, AV_LOG_INFO,
940             "[lavc rc] Using all of requested bitrate is not "
941             "necessary for this video with these parameters.\n");
942     } else if (toobig == 40) {
943         av_log(s->avctx, AV_LOG_ERROR,
944             "[lavc rc] Error: bitrate too low for this video "
945             "with these parameters.\n");
946         return -1;
947     } else if (fabs(expected_bits/all_available_bits - 1.0) > 0.01) {
948         av_log(s->avctx, AV_LOG_ERROR,
949             "[lavc rc] Error: 2pass curve failed to converge\n");
950         return -1;
951     }
952
953     return 0;
954 }