Statistics
| Branch: | Revision:

ffmpeg / libavcodec / ratecontrol.c @ 1235429c

History | View | Annotate | Download (32 KB)

1 8b4c7dbc Michael Niedermayer
/*
2 2ef0f2b2 Fabrice Bellard
 * Rate control for video encoders
3
 *
4 8f2ab833 Michael Niedermayer
 * Copyright (c) 2002-2004 Michael Niedermayer <michaelni@gmx.at>
5 2ef0f2b2 Fabrice Bellard
 *
6 b78e7197 Diego Biurrun
 * This file is part of FFmpeg.
7
 *
8
 * FFmpeg is free software; you can redistribute it and/or
9 2ef0f2b2 Fabrice Bellard
 * modify it under the terms of the GNU Lesser General Public
10
 * License as published by the Free Software Foundation; either
11 b78e7197 Diego Biurrun
 * version 2.1 of the License, or (at your option) any later version.
12 2ef0f2b2 Fabrice Bellard
 *
13 b78e7197 Diego Biurrun
 * FFmpeg is distributed in the hope that it will be useful,
14 2ef0f2b2 Fabrice Bellard
 * 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 b78e7197 Diego Biurrun
 * License along with FFmpeg; if not, write to the Free Software
20 5509bffa Diego Biurrun
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 2ef0f2b2 Fabrice Bellard
 */
22 983e3246 Michael Niedermayer
23
/**
24 bad5537e Diego Biurrun
 * @file libavcodec/ratecontrol.c
25 983e3246 Michael Niedermayer
 * Rate control for video encoders.
26 115329f1 Diego Biurrun
 */
27 983e3246 Michael Niedermayer
28 94ca624f Måns Rullgård
#include "libavutil/intmath.h"
29 8b4c7dbc Michael Niedermayer
#include "avcodec.h"
30 2ef0f2b2 Fabrice Bellard
#include "dsputil.h"
31 0de9926f Panagiotis Issaris
#include "ratecontrol.h"
32 8b4c7dbc Michael Niedermayer
#include "mpegvideo.h"
33 4d7b4613 Panagiotis Issaris
#include "eval.h"
34 8b4c7dbc Michael Niedermayer
35 e42dba48 Diego Biurrun
#undef NDEBUG // Always check asserts, the speed effect is far too small to disable them.
36 3aa102be Michael Niedermayer
#include <assert.h>
37 8b4c7dbc Michael Niedermayer
38 471d7dc3 Michael Niedermayer
#ifndef M_E
39
#define M_E 2.718281828
40
#endif
41
42 8b4c7dbc Michael Niedermayer
static int init_pass2(MpegEncContext *s);
43 3aa102be Michael Niedermayer
static double get_qscale(MpegEncContext *s, RateControlEntry *rce, double rate_factor, int frame_num);
44 8b4c7dbc Michael Niedermayer
45
void ff_write_pass1_stats(MpegEncContext *s){
46 64b7c5b6 Michael Niedermayer
    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 115329f1 Diego Biurrun
            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 64b7c5b6 Michael Niedermayer
            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 8b4c7dbc Michael Niedermayer
}
51
52 bb0f1ea7 Oded Shimon
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 8b4c7dbc Michael Niedermayer
int ff_rate_control_init(MpegEncContext *s)
67
{
68
    RateControlContext *rcc= &s->rc_context;
69 3aa102be Michael Niedermayer
    int i;
70 e3cb2c4a Reimar Döffinger
    const char *error = NULL;
71 cf2baeb3 Stefan Gehrer
    static const char * const const_names[]={
72 bb0f1ea7 Oded Shimon
        "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 9b5ede5b Reimar Döffinger
    static double (* const func1[])(void *, double)={
99 bb0f1ea7 Oded Shimon
        (void *)bits2qp,
100
        (void *)qp2bits,
101
        NULL
102
    };
103 cf2baeb3 Stefan Gehrer
    static const char * const func1_names[]={
104 bb0f1ea7 Oded Shimon
        "bits2qp",
105
        "qp2bits",
106
        NULL
107
    };
108 8b4c7dbc Michael Niedermayer
    emms_c();
109
110 1235429c Stefano Sabatini
    rcc->rc_eq_eval = ff_parse_expr(s->avctx->rc_eq ? s->avctx->rc_eq : "tex^qComp", const_names, func1, func1_names, NULL, NULL, &error);
111 bb0f1ea7 Oded Shimon
    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 3aa102be Michael Niedermayer
    for(i=0; i<5; i++){
117 158c7f05 Michael Niedermayer
        rcc->pred[i].coeff= FF_QP2LAMBDA * 7.0;
118 3aa102be Michael Niedermayer
        rcc->pred[i].count= 1.0;
119 115329f1 Diego Biurrun
120 3aa102be Michael Niedermayer
        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 04932b0d Diego Biurrun
        rcc->frame_count[i]= 1; // 1 is better because of 1/0 and such
126 158c7f05 Michael Niedermayer
        rcc->last_qscale_for[i]=FF_QP2LAMBDA * 5;
127 3aa102be Michael Niedermayer
    }
128 fb066639 Michael Niedermayer
    rcc->buffer_index= s->avctx->rc_initial_buffer_occupancy;
129 3aa102be Michael Niedermayer
130
    if(s->flags&CODEC_FLAG_PASS2){
131 8b4c7dbc Michael Niedermayer
        int i;
132 3aa102be Michael Niedermayer
        char *p;
133 8b4c7dbc Michael Niedermayer
134 3aa102be Michael Niedermayer
        /* find number of pics */
135
        p= s->avctx->stats_in;
136
        for(i=-1; p; i++){
137
            p= strchr(p+1, ';');
138 8b4c7dbc Michael Niedermayer
        }
139 3aa102be Michael Niedermayer
        i+= s->max_b_frames;
140 0ecca7a4 Michael Niedermayer
        if(i<=0 || i>=INT_MAX / sizeof(RateControlEntry))
141
            return -1;
142 90901860 Michael Niedermayer
        rcc->entry = av_mallocz(i*sizeof(RateControlEntry));
143 3aa102be Michael Niedermayer
        rcc->num_entries= i;
144 115329f1 Diego Biurrun
145 160d679c Mike Melanson
        /* init all to skipped p frames (with b frames we might have a not encoded frame at the end FIXME) */
146 3aa102be Michael Niedermayer
        for(i=0; i<rcc->num_entries; i++){
147
            RateControlEntry *rce= &rcc->entry[i];
148 9701840b Aurelien Jacobs
            rce->pict_type= rce->new_pict_type=FF_P_TYPE;
149 158c7f05 Michael Niedermayer
            rce->qscale= rce->new_qscale=FF_QP2LAMBDA * 2;
150 3aa102be Michael Niedermayer
            rce->misc_bits= s->mb_num + 10;
151
            rce->mb_var_sum= s->mb_num*100;
152 115329f1 Diego Biurrun
        }
153
154 3aa102be Michael Niedermayer
        /* read stats */
155
        p= s->avctx->stats_in;
156
        for(i=0; i<rcc->num_entries - s->max_b_frames; i++){
157 8b4c7dbc Michael Niedermayer
            RateControlEntry *rce;
158
            int picture_number;
159
            int e;
160 3aa102be Michael Niedermayer
            char *next;
161
162
            next= strchr(p, ';');
163
            if(next){
164 755bfeab Diego Biurrun
                (*next)=0; //sscanf in unbelievably slow on looong strings //FIXME copy / do not write
165 3aa102be Michael Niedermayer
                next++;
166
            }
167
            e= sscanf(p, " in:%d ", &picture_number);
168
169
            assert(picture_number >= 0);
170
            assert(picture_number < rcc->num_entries);
171 8b4c7dbc Michael Niedermayer
            rce= &rcc->entry[picture_number];
172 3aa102be Michael Niedermayer
173 64b7c5b6 Michael Niedermayer
            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 115329f1 Diego Biurrun
                   &rce->pict_type, &rce->qscale, &rce->i_tex_bits, &rce->p_tex_bits, &rce->mv_bits, &rce->misc_bits,
175 64b7c5b6 Michael Niedermayer
                   &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 9b879566 Michel Bardiaux
                av_log(s->avctx, AV_LOG_ERROR, "statistics are damaged at line %d, parser out=%d\n", i, e);
178 8b4c7dbc Michael Niedermayer
                return -1;
179
            }
180 64b7c5b6 Michael Niedermayer
181 3aa102be Michael Niedermayer
            p= next;
182 8b4c7dbc Michael Niedermayer
        }
183 5fe4cf7b Michael Niedermayer
184
        if(init_pass2(s) < 0) return -1;
185
186 64b7c5b6 Michael Niedermayer
        //FIXME maybe move to end
187 022fad48 Corey Hickey
        if((s->flags&CODEC_FLAG_PASS2) && s->avctx->rc_strategy == FF_RC_STRATEGY_XVID) {
188 b250f9c6 Aurelien Jacobs
#if CONFIG_LIBXVID
189 64b7c5b6 Michael Niedermayer
            return ff_xvid_rate_control_init(s);
190 022fad48 Corey Hickey
#else
191 842eabc5 Diego Biurrun
            av_log(s->avctx, AV_LOG_ERROR, "Xvid ratecontrol requires libavcodec compiled with Xvid support.\n");
192 022fad48 Corey Hickey
            return -1;
193 19531051 Michael Niedermayer
#endif
194 022fad48 Corey Hickey
        }
195 8b4c7dbc Michael Niedermayer
    }
196 115329f1 Diego Biurrun
197 3aa102be Michael Niedermayer
    if(!(s->flags&CODEC_FLAG_PASS2)){
198
199
        rcc->short_term_qsum=0.001;
200
        rcc->short_term_qcount=0.001;
201 115329f1 Diego Biurrun
202 23e54f69 Michael Niedermayer
        rcc->pass1_rc_eq_output_sum= 0.001;
203 3aa102be Michael Niedermayer
        rcc->pass1_wanted_bits=0.001;
204 115329f1 Diego Biurrun
205 0fa9a5dd Michael Niedermayer
        if(s->avctx->qblur > 1.0){
206
            av_log(s->avctx, AV_LOG_ERROR, "qblur too large\n");
207
            return -1;
208
        }
209 3aa102be Michael Niedermayer
        /* 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 115329f1 Diego Biurrun
215 9701840b Aurelien Jacobs
                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 3aa102be Michael Niedermayer
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 158c7f05 Michael Niedermayer
                rce.qscale   = FF_QP2LAMBDA * 2;
223 3aa102be Michael Niedermayer
                rce.f_code   = 2;
224
                rce.b_code   = 1;
225
                rce.misc_bits= 1;
226
227 9701840b Aurelien Jacobs
                if(s->pict_type== FF_I_TYPE){
228 3aa102be Michael Niedermayer
                    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 8b4c7dbc Michael Niedermayer
243 25ef0072 Michael Niedermayer
                get_qscale(s, &rce, rcc->pass1_wanted_bits/rcc->pass1_rc_eq_output_sum, i);
244 df3a80b5 Diego Biurrun
                rcc->pass1_wanted_bits+= s->bit_rate/(1/av_q2d(s->avctx->time_base)); //FIXME misbehaves a little for variable fps
245 3aa102be Michael Niedermayer
            }
246
        }
247
248
    }
249 115329f1 Diego Biurrun
250 8b4c7dbc Michael Niedermayer
    return 0;
251
}
252
253
void ff_rate_control_uninit(MpegEncContext *s)
254
{
255
    RateControlContext *rcc= &s->rc_context;
256
    emms_c();
257
258 f8fea468 Stefano Sabatini
    ff_free_expr(rcc->rc_eq_eval);
259 6000abfa Fabrice Bellard
    av_freep(&rcc->entry);
260 64b7c5b6 Michael Niedermayer
261 b250f9c6 Aurelien Jacobs
#if CONFIG_LIBXVID
262 64b7c5b6 Michael Niedermayer
    if((s->flags&CODEC_FLAG_PASS2) && s->avctx->rc_strategy == FF_RC_STRATEGY_XVID)
263
        ff_xvid_rate_control_uninit(s);
264 19531051 Michael Niedermayer
#endif
265 8b4c7dbc Michael Niedermayer
}
266
267 11dffbe1 Michael Niedermayer
int ff_vbv_update(MpegEncContext *s, int frame_size){
268 3aa102be Michael Niedermayer
    RateControlContext *rcc= &s->rc_context;
269 c0df9d75 Michael Niedermayer
    const double fps= 1/av_q2d(s->avctx->time_base);
270 d60a8f85 Michael Niedermayer
    const int buffer_size= s->avctx->rc_buffer_size;
271 3aa102be Michael Niedermayer
    const double min_rate= s->avctx->rc_min_rate/fps;
272
    const double max_rate= s->avctx->rc_max_rate/fps;
273 115329f1 Diego Biurrun
274 d60a8f85 Michael Niedermayer
//printf("%d %f %d %f %f\n", buffer_size, rcc->buffer_index, frame_size, min_rate, max_rate);
275 3aa102be Michael Niedermayer
    if(buffer_size){
276 fb066639 Michael Niedermayer
        int left;
277
278 3aa102be Michael Niedermayer
        rcc->buffer_index-= frame_size;
279 fb066639 Michael Niedermayer
        if(rcc->buffer_index < 0){
280 9b879566 Michel Bardiaux
            av_log(s->avctx, AV_LOG_ERROR, "rc buffer underflow\n");
281 fb066639 Michael Niedermayer
            rcc->buffer_index= 0;
282
        }
283
284
        left= buffer_size - rcc->buffer_index - 1;
285 f66e4f5f Reimar Döffinger
        rcc->buffer_index += av_clip(left, min_rate, max_rate);
286 fb066639 Michael Niedermayer
287 d60a8f85 Michael Niedermayer
        if(rcc->buffer_index > buffer_size){
288
            int stuffing= ceil((rcc->buffer_index - buffer_size)/8);
289 115329f1 Diego Biurrun
290 11dffbe1 Michael Niedermayer
            if(stuffing < 4 && s->codec_id == CODEC_ID_MPEG4)
291
                stuffing=4;
292
            rcc->buffer_index -= 8*stuffing;
293 115329f1 Diego Biurrun
294 11dffbe1 Michael Niedermayer
            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 fb066639 Michael Niedermayer
        }
299 3aa102be Michael Niedermayer
    }
300 11dffbe1 Michael Niedermayer
    return 0;
301 3aa102be Michael Niedermayer
}
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 d55f7b65 Michael Niedermayer
    AVCodecContext *a= s->avctx;
309 3aa102be Michael Niedermayer
    double q, bits;
310
    const int pict_type= rce->new_pict_type;
311 115329f1 Diego Biurrun
    const double mb_num= s->mb_num;
312 3aa102be Michael Niedermayer
    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 9701840b Aurelien Jacobs
        rce->pict_type == FF_B_TYPE ? (rce->f_code + rce->b_code)*0.5 : rce->f_code,
322 3aa102be Michael Niedermayer
        rce->i_count/mb_num,
323
        rce->mc_mb_var_sum/mb_num,
324
        rce->mb_var_sum/mb_num,
325 9701840b Aurelien Jacobs
        rce->pict_type == FF_I_TYPE,
326
        rce->pict_type == FF_P_TYPE,
327
        rce->pict_type == FF_B_TYPE,
328 3aa102be Michael Niedermayer
        rcc->qscale_sum[pict_type] / (double)rcc->frame_count[pict_type],
329 d55f7b65 Michael Niedermayer
        a->qcompress,
330 9701840b Aurelien Jacobs
/*        rcc->last_qscale_for[FF_I_TYPE],
331
        rcc->last_qscale_for[FF_P_TYPE],
332
        rcc->last_qscale_for[FF_B_TYPE],
333 3aa102be Michael Niedermayer
        rcc->next_non_b_qscale,*/
334 9701840b Aurelien Jacobs
        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 3aa102be Michael Niedermayer
        (rcc->i_cplx_sum[pict_type] + rcc->p_cplx_sum[pict_type]) / (double)rcc->frame_count[pict_type],
339
        0
340
    };
341
342 4565caf1 Stefano Sabatini
    bits= ff_eval_expr(rcc->rc_eq_eval, const_values, rce);
343 4156a436 Panagiotis Issaris
    if (isnan(bits)) {
344 bb0f1ea7 Oded Shimon
        av_log(s->avctx, AV_LOG_ERROR, "Error evaluating rc_eq \"%s\"\n", s->avctx->rc_eq);
345 4156a436 Panagiotis Issaris
        return -1;
346
    }
347 115329f1 Diego Biurrun
348 23e54f69 Michael Niedermayer
    rcc->pass1_rc_eq_output_sum+= bits;
349 3aa102be Michael Niedermayer
    bits*=rate_factor;
350
    if(bits<0.0) bits=0.0;
351
    bits+= 1.0; //avoid 1/0 issues
352 115329f1 Diego Biurrun
353 3aa102be Michael Niedermayer
    /* 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 115329f1 Diego Biurrun
359
        if(rco[i].qscale)
360 3aa102be Michael Niedermayer
            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 115329f1 Diego Biurrun
367 3aa102be Michael Niedermayer
    /* I/B difference */
368 9701840b Aurelien Jacobs
    if     (pict_type==FF_I_TYPE && s->avctx->i_quant_factor<0.0)
369 3aa102be Michael Niedermayer
        q= -q*s->avctx->i_quant_factor + s->avctx->i_quant_offset;
370 9701840b Aurelien Jacobs
    else if(pict_type==FF_B_TYPE && s->avctx->b_quant_factor<0.0)
371 3aa102be Michael Niedermayer
        q= -q*s->avctx->b_quant_factor + s->avctx->b_quant_offset;
372 2711cb28 Michael Niedermayer
    if(q<1) q=1;
373 115329f1 Diego Biurrun
374 6a1f7e7b Michael Niedermayer
    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 9701840b Aurelien Jacobs
    const double last_p_q    = rcc->last_qscale_for[FF_P_TYPE];
382 6a1f7e7b Michael Niedermayer
    const double last_non_b_q= rcc->last_qscale_for[rcc->last_non_b_pict_type];
383 115329f1 Diego Biurrun
384 9701840b Aurelien Jacobs
    if     (pict_type==FF_I_TYPE && (a->i_quant_factor>0.0 || rcc->last_non_b_pict_type==FF_P_TYPE))
385 c26abfa5 Diego Biurrun
        q= last_p_q    *FFABS(a->i_quant_factor) + a->i_quant_offset;
386 9701840b Aurelien Jacobs
    else if(pict_type==FF_B_TYPE && a->b_quant_factor>0.0)
387 6a1f7e7b Michael Niedermayer
        q= last_non_b_q*    a->b_quant_factor  + a->b_quant_offset;
388 2711cb28 Michael Niedermayer
    if(q<1) q=1;
389 6a1f7e7b Michael Niedermayer
390 3aa102be Michael Niedermayer
    /* last qscale / qdiff stuff */
391 9701840b Aurelien Jacobs
    if(rcc->last_non_b_pict_type==pict_type || pict_type!=FF_I_TYPE){
392 6a1f7e7b Michael Niedermayer
        double last_q= rcc->last_qscale_for[pict_type];
393 158c7f05 Michael Niedermayer
        const int maxdiff= FF_QP2LAMBDA * a->max_qdiff;
394 59b571c1 Michael Niedermayer
395 158c7f05 Michael Niedermayer
        if     (q > last_q + maxdiff) q= last_q + maxdiff;
396
        else if(q < last_q - maxdiff) q= last_q - maxdiff;
397 6a1f7e7b Michael Niedermayer
    }
398 3aa102be Michael Niedermayer
399 755bfeab Diego Biurrun
    rcc->last_qscale_for[pict_type]= q; //Note we cannot do that after blurring
400 115329f1 Diego Biurrun
401 9701840b Aurelien Jacobs
    if(pict_type!=FF_B_TYPE)
402 6a1f7e7b Michael Niedermayer
        rcc->last_non_b_pict_type= pict_type;
403
404 3aa102be Michael Niedermayer
    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 115329f1 Diego Biurrun
    int qmin= s->avctx->lmin;
412 158c7f05 Michael Niedermayer
    int qmax= s->avctx->lmax;
413 115329f1 Diego Biurrun
414 fa12b546 Michael Niedermayer
    assert(qmin <= qmax);
415 3aa102be Michael Niedermayer
416 9701840b Aurelien Jacobs
    if(pict_type==FF_B_TYPE){
417 c26abfa5 Diego Biurrun
        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 9701840b Aurelien Jacobs
    }else if(pict_type==FF_I_TYPE){
420 c26abfa5 Diego Biurrun
        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 3aa102be Michael Niedermayer
    }
423
424 f66e4f5f Reimar Döffinger
    qmin= av_clip(qmin, 1, FF_LAMBDA_MAX);
425
    qmax= av_clip(qmax, 1, FF_LAMBDA_MAX);
426 3aa102be Michael Niedermayer
427 fa12b546 Michael Niedermayer
    if(qmax<qmin) qmax= qmin;
428 115329f1 Diego Biurrun
429 3aa102be Michael Niedermayer
    *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 c0df9d75 Michael Niedermayer
    const double fps= 1/av_q2d(s->avctx->time_base);
439 fb066639 Michael Niedermayer
    const double min_rate= s->avctx->rc_min_rate / fps;
440
    const double max_rate= s->avctx->rc_max_rate / fps;
441 115329f1 Diego Biurrun
442 3aa102be Michael Niedermayer
    get_qminmax(&qmin, &qmax, s, pict_type);
443
444
    /* modulation */
445 9701840b Aurelien Jacobs
    if(s->avctx->rc_qmod_freq && frame_num%s->avctx->rc_qmod_freq==0 && pict_type==FF_P_TYPE)
446 3aa102be Michael Niedermayer
        q*= s->avctx->rc_qmod_amp;
447
448 946c8a12 Michael Niedermayer
//printf("q:%f\n", q);
449 3aa102be Michael Niedermayer
    /* buffer overflow/underflow protection */
450
    if(buffer_size){
451 6a1f7e7b Michael Niedermayer
        double expected_size= rcc->buffer_index;
452 d60a8f85 Michael Niedermayer
        double q_limit;
453 3aa102be Michael Niedermayer
454
        if(min_rate){
455 6a1f7e7b Michael Niedermayer
            double d= 2*(buffer_size - expected_size)/buffer_size;
456 3aa102be Michael Niedermayer
            if(d>1.0) d=1.0;
457 946c8a12 Michael Niedermayer
            else if(d<0.0001) d=0.0001;
458
            q*= pow(d, 1.0/s->avctx->rc_buffer_aggressivity);
459 6a1f7e7b Michael Niedermayer
460 3bff4d8b Baptiste Coudurier
            q_limit= bits2qp(rce, FFMAX((min_rate - buffer_size + rcc->buffer_index) * s->avctx->rc_min_vbv_overflow_use, 1));
461 d60a8f85 Michael Niedermayer
            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 3aa102be Michael Niedermayer
        }
468
469
        if(max_rate){
470
            double d= 2*expected_size/buffer_size;
471
            if(d>1.0) d=1.0;
472 946c8a12 Michael Niedermayer
            else if(d<0.0001) d=0.0001;
473
            q/= pow(d, 1.0/s->avctx->rc_buffer_aggressivity);
474 6a1f7e7b Michael Niedermayer
475 3bff4d8b Baptiste Coudurier
            q_limit= bits2qp(rce, FFMAX(rcc->buffer_index * s->avctx->rc_max_available_vbv_use, 1));
476 d60a8f85 Michael Niedermayer
            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 3aa102be Michael Niedermayer
        }
483
    }
484 946c8a12 Michael Niedermayer
//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 c695ca3b Michael Niedermayer
    if(s->avctx->rc_qsquish==0.0 || qmin==qmax){
486 3aa102be Michael Niedermayer
        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 115329f1 Diego Biurrun
492 3aa102be Michael Niedermayer
        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 115329f1 Diego Biurrun
498 3aa102be Michael Niedermayer
        q= exp(q);
499
    }
500 115329f1 Diego Biurrun
501 3aa102be Michael Niedermayer
    return q;
502
}
503
504 8b4c7dbc Michael Niedermayer
//----------------------------------
505
// 1 Pass Code
506
507 3aa102be Michael Niedermayer
static double predict_size(Predictor *p, double q, double var)
508 8b4c7dbc Michael Niedermayer
{
509
     return p->coeff*var / (q*p->count);
510
}
511
512 ccfddafb bubu
/*
513 3aa102be Michael Niedermayer
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 ccfddafb bubu
*/
519 3aa102be Michael Niedermayer
520 8b4c7dbc Michael Niedermayer
static void update_predictor(Predictor *p, double q, double var, double size)
521
{
522
    double new_coeff= size*q / (var + 1);
523 3aa102be Michael Niedermayer
    if(var<10) return;
524 8b4c7dbc Michael Niedermayer
525
    p->count*= p->decay;
526
    p->coeff*= p->decay;
527
    p->count++;
528
    p->coeff+= new_coeff;
529
}
530
531 c5d309f2 Michael Niedermayer
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 5e746b99 Michael Niedermayer
    const float dark_masking= s->avctx->dark_masking / (128.0*128.0);
535 c5d309f2 Michael Niedermayer
    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 957c743a Christophe Massiot
    const float border_masking = s->avctx->border_masking;
539 c5d309f2 Michael Niedermayer
    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 6e0d8c06 Michael Niedermayer
    const int qmin= s->avctx->mb_lmin;
544
    const int qmax= s->avctx->mb_lmax;
545 1e491e29 Michael Niedermayer
    Picture * const pic= &s->current_picture;
546 957c743a Christophe Massiot
    const int mb_width = s->mb_width;
547
    const int mb_height = s->mb_height;
548 115329f1 Diego Biurrun
549 c5d309f2 Michael Niedermayer
    for(i=0; i<s->mb_num; i++){
550 2f5feea4 Michael Niedermayer
        const int mb_xy= s->mb_index2xy[i];
551 158c7f05 Michael Niedermayer
        float temp_cplx= sqrt(pic->mc_mb_var[mb_xy]); //FIXME merge in pow()
552 2f5feea4 Michael Niedermayer
        float spat_cplx= sqrt(pic->mb_var[mb_xy]);
553
        const int lumi= pic->mb_mean[mb_xy];
554 c5d309f2 Michael Niedermayer
        float bits, cplx, factor;
555 957c743a Christophe Massiot
        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 115329f1 Diego Biurrun
#if 0
560 c5d309f2 Michael Niedermayer
        if(spat_cplx < q/3) spat_cplx= q/3; //FIXME finetune
561
        if(temp_cplx < q/3) temp_cplx= q/3; //FIXME finetune
562 115329f1 Diego Biurrun
#endif
563 158c7f05 Michael Niedermayer
        if(spat_cplx < 4) spat_cplx= 4; //FIXME finetune
564
        if(temp_cplx < 4) temp_cplx= 4; //FIXME finetune
565
566 115329f1 Diego Biurrun
        if((s->mb_type[mb_xy]&CANDIDATE_MB_TYPE_INTRA)){//FIXME hq mode
567 c5d309f2 Michael Niedermayer
            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 5e746b99 Michael Niedermayer
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 957c743a Christophe Massiot
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 115329f1 Diego Biurrun
597 c5d309f2 Michael Niedermayer
        if(factor<0.00001) factor= 0.00001;
598 115329f1 Diego Biurrun
599 c5d309f2 Michael Niedermayer
        bits= cplx*factor;
600
        cplx_sum+= cplx;
601
        bits_sum+= bits;
602
        cplx_tab[i]= cplx;
603
        bits_tab[i]= bits;
604
    }
605
606 755bfeab Diego Biurrun
    /* handle qmin/qmax clipping */
607 c5d309f2 Michael Niedermayer
    if(s->flags&CODEC_FLAG_NORMALIZE_AQP){
608 e9a4834a Michael Niedermayer
        float factor= bits_sum/cplx_sum;
609 c5d309f2 Michael Niedermayer
        for(i=0; i<s->mb_num; i++){
610
            float newq= q*cplx_tab[i]/bits_tab[i];
611 e9a4834a Michael Niedermayer
            newq*= factor;
612 c5d309f2 Michael Niedermayer
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 e9a4834a Michael Niedermayer
        if(bits_sum < 0.001) bits_sum= 0.001;
623
        if(cplx_sum < 0.001) cplx_sum= 0.001;
624 c5d309f2 Michael Niedermayer
    }
625 115329f1 Diego Biurrun
626 c5d309f2 Michael Niedermayer
    for(i=0; i<s->mb_num; i++){
627 2f5feea4 Michael Niedermayer
        const int mb_xy= s->mb_index2xy[i];
628 c5d309f2 Michael Niedermayer
        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 158c7f05 Michael Niedermayer
        intq= (int)(newq + 0.5);
636 c5d309f2 Michael Niedermayer
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 158c7f05 Michael Niedermayer
        s->lambda_table[mb_xy]= intq;
642 c5d309f2 Michael Niedermayer
    }
643
}
644 82b019ce Michael Niedermayer
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 158c7f05 Michael Niedermayer
//FIXME rd or at least approx for dquant
656 c5d309f2 Michael Niedermayer
657 8ed9f9ab Michael Niedermayer
float ff_rate_estimate_qscale(MpegEncContext *s, int dry_run)
658 8b4c7dbc Michael Niedermayer
{
659
    float q;
660 c5d309f2 Michael Niedermayer
    int qmin, qmax;
661 8b4c7dbc Michael Niedermayer
    float br_compensation;
662
    double diff;
663
    double short_term_q;
664
    double fps;
665 3aa102be Michael Niedermayer
    int picture_number= s->picture_number;
666 8b4c7dbc Michael Niedermayer
    int64_t wanted_bits;
667 3aa102be Michael Niedermayer
    RateControlContext *rcc= &s->rc_context;
668 d55f7b65 Michael Niedermayer
    AVCodecContext *a= s->avctx;
669 3aa102be Michael Niedermayer
    RateControlEntry local_rce, *rce;
670
    double bits;
671
    double rate_factor;
672
    int var;
673
    const int pict_type= s->pict_type;
674 1e491e29 Michael Niedermayer
    Picture * const pic= &s->current_picture;
675 8b4c7dbc Michael Niedermayer
    emms_c();
676
677 b250f9c6 Aurelien Jacobs
#if CONFIG_LIBXVID
678 64b7c5b6 Michael Niedermayer
    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 19531051 Michael Niedermayer
#endif
681 64b7c5b6 Michael Niedermayer
682 3aa102be Michael Niedermayer
    get_qminmax(&qmin, &qmax, s, pict_type);
683 8b4c7dbc Michael Niedermayer
684 c0df9d75 Michael Niedermayer
    fps= 1/av_q2d(s->avctx->time_base);
685 946c8a12 Michael Niedermayer
//printf("input_pic_num:%d pic_num:%d frame_rate:%d\n", s->input_picture_number, s->picture_number, s->frame_rate);
686 8b4c7dbc Michael Niedermayer
        /* update predictors */
687 8ed9f9ab Michael Niedermayer
    if(picture_number>2 && !dry_run){
688 9701840b Aurelien Jacobs
        const int last_var= s->last_pict_type == FF_I_TYPE ? rcc->last_mb_var_sum : rcc->last_mc_mb_var_sum;
689 3aa102be Michael Niedermayer
        update_predictor(&rcc->pred[s->last_pict_type], rcc->last_qscale, sqrt(last_var), s->frame_bits);
690 8b4c7dbc Michael Niedermayer
    }
691
692 3aa102be Michael Niedermayer
    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 f6128014 Michael Niedermayer
        Picture *dts_pic;
699 3aa102be Michael Niedermayer
        rce= &local_rce;
700 f6128014 Michael Niedermayer
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 9701840b Aurelien Jacobs
        if(s->pict_type == FF_B_TYPE || s->low_delay)
704 f6128014 Michael Niedermayer
            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 3aa102be Michael Niedermayer
    }
716 8b4c7dbc Michael Niedermayer
717 3aa102be Michael Niedermayer
    diff= s->total_bits - wanted_bits;
718 d55f7b65 Michael Niedermayer
    br_compensation= (a->bit_rate_tolerance - diff)/a->bit_rate_tolerance;
719 3aa102be Michael Niedermayer
    if(br_compensation<=0.0) br_compensation=0.001;
720
721 9701840b Aurelien Jacobs
    var= pict_type == FF_I_TYPE ? pic->mb_var_sum : pic->mc_mb_var_sum;
722 115329f1 Diego Biurrun
723 b1609412 Fabrice Bellard
    short_term_q = 0; /* avoid warning */
724 3aa102be Michael Niedermayer
    if(s->flags&CODEC_FLAG_PASS2){
725 9701840b Aurelien Jacobs
        if(pict_type!=FF_I_TYPE)
726 3aa102be Michael Niedermayer
            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 115329f1 Diego Biurrun
        rce->pict_type=
732 3aa102be Michael Niedermayer
        rce->new_pict_type= pict_type;
733 1e491e29 Michael Niedermayer
        rce->mc_mb_var_sum= pic->mc_mb_var_sum;
734
        rce->mb_var_sum   = pic->   mb_var_sum;
735 158c7f05 Michael Niedermayer
        rce->qscale   = FF_QP2LAMBDA * 2;
736 3aa102be Michael Niedermayer
        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 9701840b Aurelien Jacobs
        if(pict_type== FF_I_TYPE){
742 3aa102be Michael Niedermayer
            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 115329f1 Diego Biurrun
751 3aa102be Michael Niedermayer
            rce->mv_bits= bits*0.1;
752 8b4c7dbc Michael Niedermayer
        }
753 3aa102be Michael Niedermayer
        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 8b4c7dbc Michael Niedermayer
758 3aa102be Michael Niedermayer
        bits= rce->i_tex_bits + rce->p_tex_bits;
759 23e54f69 Michael Niedermayer
        rate_factor= rcc->pass1_wanted_bits/rcc->pass1_rc_eq_output_sum * br_compensation;
760 115329f1 Diego Biurrun
761 3aa102be Michael Niedermayer
        q= get_qscale(s, rce, rate_factor, picture_number);
762 4156a436 Panagiotis Issaris
        if (q < 0)
763
            return -1;
764 8b4c7dbc Michael Niedermayer
765 c695ca3b Michael Niedermayer
        assert(q>0.0);
766 3aa102be Michael Niedermayer
//printf("%f ", q);
767 6a1f7e7b Michael Niedermayer
        q= get_diff_limited_q(s, rce, q);
768 3aa102be Michael Niedermayer
//printf("%f ", q);
769
        assert(q>0.0);
770
771 9701840b Aurelien Jacobs
        if(pict_type==FF_P_TYPE || s->intra_only){ //FIXME type dependent blur like in 2-pass
772 d55f7b65 Michael Niedermayer
            rcc->short_term_qsum*=a->qblur;
773
            rcc->short_term_qcount*=a->qblur;
774 3aa102be Michael Niedermayer
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 946c8a12 Michael Niedermayer
        assert(q>0.0);
782 115329f1 Diego Biurrun
783 3aa102be Michael Niedermayer
        q= modify_qscale(s, rce, q, picture_number);
784
785
        rcc->pass1_wanted_bits+= s->bit_rate/fps;
786
787 c695ca3b Michael Niedermayer
        assert(q>0.0);
788 8b4c7dbc Michael Niedermayer
    }
789 59b571c1 Michael Niedermayer
790
    if(s->avctx->debug&FF_DEBUG_RC){
791 9b879566 Michel Bardiaux
        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 d8085ea7 Michael Niedermayer
        av_get_pict_type_char(pict_type), qmin, q, qmax, picture_number, (int)wanted_bits/1000, (int)s->total_bits/1000,
793 59b571c1 Michael Niedermayer
        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 3aa102be Michael Niedermayer
797 115329f1 Diego Biurrun
    if     (q<qmin) q=qmin;
798 3aa102be Michael Niedermayer
    else if(q>qmax) q=qmax;
799
800 c5d309f2 Michael Niedermayer
    if(s->adaptive_quant)
801
        adaptive_quantization(s, q);
802
    else
803
        q= (int)(q + 0.5);
804 115329f1 Diego Biurrun
805 8ed9f9ab Michael Niedermayer
    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 1e491e29 Michael Niedermayer
#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 c5d309f2 Michael Niedermayer
    return q;
819 8b4c7dbc Michael Niedermayer
}
820
821
//----------------------------------------------
822
// 2-Pass code
823
824
static int init_pass2(MpegEncContext *s)
825
{
826
    RateControlContext *rcc= &s->rc_context;
827 d55f7b65 Michael Niedermayer
    AVCodecContext *a= s->avctx;
828 577cd173 Corey Hickey
    int i, toobig;
829 c0df9d75 Michael Niedermayer
    double fps= 1/av_q2d(s->avctx->time_base);
830 8b4c7dbc Michael Niedermayer
    double complexity[5]={0,0,0,0,0};   // aproximate bits at quant=1
831 eafcac6a Diego Biurrun
    uint64_t const_bits[5]={0,0,0,0,0}; // quantizer independent bits
832 8b4c7dbc Michael Niedermayer
    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 ccfddafb bubu
    //int last_i_frame=-10000000;
837 115329f1 Diego Biurrun
    const int filter_size= (int)(a->qblur*4) | 1;
838 3aa102be Michael Niedermayer
    double expected_bits;
839 170c0b45 Diego Biurrun
    double *qscale, *blurred_qscale, qscale_sum;
840 8b4c7dbc Michael Niedermayer
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 115329f1 Diego Biurrun
845 0d1e9246 Michael Niedermayer
        rce->new_pict_type= rce->pict_type;
846 3aa102be Michael Niedermayer
        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 8b4c7dbc Michael Niedermayer
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 9701840b Aurelien Jacobs
    all_const_bits= const_bits[FF_I_TYPE] + const_bits[FF_P_TYPE] + const_bits[FF_B_TYPE];
855 115329f1 Diego Biurrun
856 8b4c7dbc Michael Niedermayer
    if(all_available_bits < all_const_bits){
857 29b372b9 Corey Hickey
        av_log(s->avctx, AV_LOG_ERROR, "requested bitrate is too low\n");
858 8b4c7dbc Michael Niedermayer
        return -1;
859
    }
860 115329f1 Diego Biurrun
861 8e1e6f31 Fabrice Bellard
    qscale= av_malloc(sizeof(double)*rcc->num_entries);
862 170c0b45 Diego Biurrun
    blurred_qscale= av_malloc(sizeof(double)*rcc->num_entries);
863 577cd173 Corey Hickey
    toobig = 0;
864 3aa102be Michael Niedermayer
865 8b4c7dbc Michael Niedermayer
    for(step=256*256; step>0.0000001; step*=0.5){
866 3aa102be Michael Niedermayer
        expected_bits=0;
867 8b4c7dbc Michael Niedermayer
        rate_factor+= step;
868 115329f1 Diego Biurrun
869 3aa102be Michael Niedermayer
        rcc->buffer_index= s->avctx->rc_buffer_size/2;
870
871 8b4c7dbc Michael Niedermayer
        /* find qscale */
872
        for(i=0; i<rcc->num_entries; i++){
873 3aa102be Michael Niedermayer
            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 8b4c7dbc Michael Niedermayer
            RateControlEntry *rce= &rcc->entry[i];
880 115329f1 Diego Biurrun
881 6a1f7e7b Michael Niedermayer
            qscale[i]= get_diff_limited_q(s, rce, qscale[i]);
882 3aa102be Michael Niedermayer
        }
883 8b4c7dbc Michael Niedermayer
884 3aa102be Michael Niedermayer
        /* 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 115329f1 Diego Biurrun
891 3aa102be Michael Niedermayer
            for(j=0; j<filter_size; j++){
892
                int index= i+j-filter_size/2;
893
                double d= index-i;
894 d55f7b65 Michael Niedermayer
                double coeff= a->qblur==0 ? 1.0 : exp(-d*d/(a->qblur * a->qblur));
895 115329f1 Diego Biurrun
896 3aa102be Michael Niedermayer
                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 8b4c7dbc Michael Niedermayer
            }
901 170c0b45 Diego Biurrun
            blurred_qscale[i]= q/sum;
902 8b4c7dbc Michael Niedermayer
        }
903 115329f1 Diego Biurrun
904 8b4c7dbc Michael Niedermayer
        /* find expected bits */
905
        for(i=0; i<rcc->num_entries; i++){
906
            RateControlEntry *rce= &rcc->entry[i];
907 3aa102be Michael Niedermayer
            double bits;
908 170c0b45 Diego Biurrun
            rce->new_qscale= modify_qscale(s, rce, blurred_qscale[i], i);
909 405469ce Michael Niedermayer
            bits= qp2bits(rce, rce->new_qscale) + rce->mv_bits + rce->misc_bits;
910 170c0b45 Diego Biurrun
//printf("%d %f\n", rce->new_bits, blurred_qscale[i]);
911 11dffbe1 Michael Niedermayer
            bits += 8*ff_vbv_update(s, bits);
912 3aa102be Michael Niedermayer
913 8b4c7dbc Michael Niedermayer
            rce->expected_bits= expected_bits;
914 3aa102be Michael Niedermayer
            expected_bits += bits;
915 8b4c7dbc Michael Niedermayer
        }
916
917 577cd173 Corey Hickey
        /*
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 8b4c7dbc Michael Niedermayer
    }
927 8e1e6f31 Fabrice Bellard
    av_free(qscale);
928 170c0b45 Diego Biurrun
    av_free(blurred_qscale);
929 8b4c7dbc Michael Niedermayer
930 577cd173 Corey Hickey
    /* 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 f66e4f5f Reimar Döffinger
        qscale_sum += av_clip(rcc->entry[i].new_qscale / FF_QP2LAMBDA, s->avctx->qmin, s->avctx->qmax);
936 577cd173 Corey Hickey
    }
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 3aa102be Michael Niedermayer
        return -1;
958 8b4c7dbc Michael Niedermayer
    }
959
960 3aa102be Michael Niedermayer
    return 0;
961 8b4c7dbc Michael Niedermayer
}