ratecontrol.c 10 KB
Newer Older
1
/***************************************************-*- coding: iso-8859-1 -*-
Laurent Aimar's avatar
Laurent Aimar committed
2 3 4 5 6
 * ratecontrol.c: h264 encoder library (Rate Control)
 *****************************************************************************
 * Copyright (C) 2003 Laurent Aimar
 * $Id: ratecontrol.c,v 1.1 2004/06/03 19:27:08 fenrir Exp $
 *
7
 * Authors: Mns Rullgrd <mru@mru.ath.cx>
Laurent Aimar's avatar
Laurent Aimar committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
 *****************************************************************************/

24 25
#define _ISOC99_SOURCE

Laurent Aimar's avatar
Laurent Aimar committed
26 27 28
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
29 30
#include <math.h>
#include <limits.h>
Laurent Aimar's avatar
Laurent Aimar committed
31 32

#include "../core/common.h"
33
#include "../core/cpu.h"
Laurent Aimar's avatar
Laurent Aimar committed
34 35
#include "ratecontrol.h"

Eric Petit's avatar
Eric Petit committed
36 37 38 39
#ifdef SYS_MACOSX
#define exp2f(x) ( (float) exp2( (x) ) )
#endif

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
struct x264_ratecontrol_t
{
    /* constants */
    float fps;
    int gop_size;
    int bitrate;
    int nmb;                    /* number of MBs */
    int buffer_size;
    int rcbufrate;
    int init_qp;

    int gop_qp;
    int buffer_fullness;
    int frames;                 /* frames in current gop */
    int pframes;
    int slice_type;
    int mb;                     /* MBs processed in current frame */
    int bits_gop;               /* allocated bits current gop */
    int bits_last_gop;          /* bits consumed in gop */
    int qp;                     /* qp for current frame */
    int qpm;                    /* qp for next MB */
    int qpa;                    /* average qp for last frame */
    int qps;
    int qp_avg_p;               /* average QP for P frames */
    int qp_last_p;
    int fbits;                  /* bits allocated for current frame */
    int ufbits;                 /* bits used for current frame */
    int nzcoeffs;               /* # of 0-quantized coefficients */
    int ncoeffs;                /* total # of coefficients */
    int overhead;
};
Laurent Aimar's avatar
Laurent Aimar committed
71

72
int x264_ratecontrol_new( x264_t *h )
Laurent Aimar's avatar
Laurent Aimar committed
73 74
{
    x264_ratecontrol_t *rc = x264_malloc( sizeof( x264_ratecontrol_t ) );
75 76 77 78
    float bpp;

    memset(rc, 0, sizeof(*rc));

Måns Rullgård's avatar
Måns Rullgård committed
79 80 81 82 83 84
    /* FIXME: use integers */
    if(h->param.i_fps_num > 0 && h->param.i_fps_den > 0)
        rc->fps = (float) h->param.i_fps_num / h->param.i_fps_den;
    else
        rc->fps = 25.0;

85 86 87 88 89 90 91
    rc->gop_size = h->param.i_iframe;
    rc->bitrate = h->param.i_bitrate * 1000;
    rc->nmb = ((h->param.i_width + 15) / 16) * ((h->param.i_height + 15) / 16);

    rc->qp = h->param.i_qp_constant;
    rc->qpa = rc->qp;
    rc->qpm = rc->qp;
Laurent Aimar's avatar
Laurent Aimar committed
92

93
    rc->buffer_size = h->param.i_rc_buffer_size * 1000;
94 95
    rc->buffer_fullness = h->param.i_rc_init_buffer;
    rc->rcbufrate = rc->bitrate / rc->fps;
Laurent Aimar's avatar
Laurent Aimar committed
96

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
    if(rc->buffer_size < rc->rcbufrate){
        x264_log(h, X264_LOG_WARNING, "rc buffer size %i too small\n",
                 rc->buffer_size);
        rc->buffer_size = 0;
    }

    if(rc->buffer_size <= 0)
        rc->buffer_size = rc->bitrate / 2;

    if(rc->buffer_fullness > rc->buffer_size || rc->buffer_fullness < 0){
        x264_log(h, X264_LOG_WARNING, "invalid initial buffer fullness %i\n",
                 rc->buffer_fullness);
        rc->buffer_fullness = 0;
    }

112 113 114 115 116 117 118 119 120 121
    bpp = rc->bitrate / (rc->fps * h->param.i_width * h->param.i_height);
    if(bpp <= 0.6)
        rc->init_qp = 31;
    else if(bpp <= 1.4)
        rc->init_qp = 25;
    else if(bpp <= 2.4)
        rc->init_qp = 20;
    else
        rc->init_qp = 10;
    rc->gop_qp = rc->init_qp;
Laurent Aimar's avatar
Laurent Aimar committed
122

123
    rc->bits_last_gop = 0;
Laurent Aimar's avatar
Laurent Aimar committed
124

125 126
    x264_log(h, X264_LOG_DEBUG, "%f fps, %i bps, bufsize %i\n",
             rc->fps, rc->bitrate, rc->buffer_size);
127 128 129 130

    h->rc = rc;

    return 0;
Laurent Aimar's avatar
Laurent Aimar committed
131 132
}

133
void x264_ratecontrol_delete( x264_t *h )
Laurent Aimar's avatar
Laurent Aimar committed
134
{
135
    x264_ratecontrol_t *rc = h->rc;
Laurent Aimar's avatar
Laurent Aimar committed
136 137 138
    x264_free( rc );
}

139
void x264_ratecontrol_start( x264_t *h, int i_slice_type )
Laurent Aimar's avatar
Laurent Aimar committed
140
{
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    x264_ratecontrol_t *rc = h->rc;
    int gframes, iframes, pframes, bframes;
    int minbits, maxbits;
    int gbits, fbits;
    int zn = 0;
    float kp;
    int gbuf;

    if(!h->param.b_cbr)
        return;

    x264_cpu_restore( h->param.cpu );

    rc->slice_type = i_slice_type;

    switch(i_slice_type){
    case SLICE_TYPE_I:
        gbuf = rc->buffer_fullness + (rc->gop_size-1) * rc->rcbufrate;
        rc->bits_gop = gbuf - rc->buffer_size / 2;

        if(!rc->mb && rc->pframes){
            int qp = (float) rc->qp_avg_p / rc->pframes + 0.5;
#if 0 /* JM does this without explaining why */
            int gdq = (float) rc->gop_size / 15 + 0.5;
            if(gdq > 2)
                gdq = 2;
            qp -= gdq;
            if(qp > rc->qp_last_p - 2)
                qp--;
#endif
            qp = x264_clip3(qp, rc->gop_qp - 4, rc->gop_qp + 4);
            qp =
                x264_clip3(qp, h->param.i_qp_min, h->param.i_qp_max);
            rc->gop_qp = qp;
175
        } else if(rc->frames > 4){
176 177 178 179 180
            rc->gop_qp = rc->init_qp;
        }

        kp = h->param.f_ip_factor * h->param.f_pb_factor;

181 182
        x264_log(h, X264_LOG_DEBUG,"gbuf=%i bits_gop=%i frames=%i gop_qp=%i\n",
                 gbuf, rc->bits_gop, rc->frames, rc->gop_qp);
183

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
        rc->bits_last_gop = 0;
        rc->frames = 0;
        rc->pframes = 0;
        rc->qp_avg_p = 0;
        break;

    case SLICE_TYPE_P:
        kp = h->param.f_pb_factor;
        break;

    case SLICE_TYPE_B:
        kp = 1.0;
        break;

    default:
199 200
        x264_log(h, X264_LOG_WARNING, "ratecontrol: unknown slice type %i\n",
                 i_slice_type);
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
        kp = 1.0;
        break;
    }

    gframes = rc->gop_size - rc->frames;
    iframes = gframes / rc->gop_size;
    pframes = gframes / (h->param.i_bframe + 1) - iframes;
    bframes = gframes - pframes - iframes;

    gbits = rc->bits_gop - rc->bits_last_gop;
    fbits = kp * gbits /
        (h->param.f_ip_factor * h->param.f_pb_factor * iframes +
         h->param.f_pb_factor * pframes + bframes);

    minbits = rc->buffer_fullness + rc->rcbufrate - rc->buffer_size;
    if(minbits < 0)
        minbits = 0;
    maxbits = rc->buffer_fullness;
    rc->fbits = x264_clip3(fbits, minbits, maxbits);

    if(i_slice_type == SLICE_TYPE_I){
        rc->qp = rc->gop_qp;
223
    } else if(rc->ncoeffs && rc->ufbits){
224 225 226 227 228 229 230 231 232 233
        int dqp, nonzc;

        nonzc = (rc->ncoeffs - rc->nzcoeffs);
        if(nonzc == 0)
            zn = rc->ncoeffs;
        else if(rc->fbits < INT_MAX / nonzc)
            zn = rc->ncoeffs - rc->fbits * nonzc / rc->ufbits;
        else
            zn = 0;
        zn = x264_clip3(zn, 0, rc->ncoeffs);
234 235 236 237 238 239
        dqp = h->param.i_rc_sens * exp2f((float) rc->qpa / 6) *
            (zn - rc->nzcoeffs) / rc->nzcoeffs;
        dqp = x264_clip3(dqp, -h->param.i_qp_step, h->param.i_qp_step);
        rc->qp = rc->qpa + dqp;
    }

240
    if(rc->fbits > 0.9 * maxbits)
241
        rc->qp += 2;
242 243
    else if(rc->fbits > 0.8 * maxbits)
        rc->qp += 1;
244 245
    else if(rc->fbits < 1.1 * minbits)
        rc->qp -= 2;
246 247
    else if(rc->fbits < 1.2 * minbits)
        rc->qp -= 1;
248 249 250 251

    rc->qp = x264_clip3(rc->qp, h->param.i_qp_min, h->param.i_qp_max);
    rc->qpm = rc->qp;

252 253
    x264_log(h, X264_LOG_DEBUG, "fbits=%i, qp=%i, z=%i, min=%i, max=%i\n",
             rc->fbits, rc->qpm, zn, minbits, maxbits);
254 255 256 257 258 259 260

    rc->fbits -= rc->overhead;
    rc->ufbits = 0;
    rc->ncoeffs = 0;
    rc->nzcoeffs = 0;
    rc->mb = 0;
    rc->qps = 0;
Laurent Aimar's avatar
Laurent Aimar committed
261 262
}

263
void x264_ratecontrol_mb( x264_t *h, int bits )
Laurent Aimar's avatar
Laurent Aimar committed
264
{
265 266
    x264_ratecontrol_t *rc = h->rc;
    int rbits;
267 268
    int zn, enz, nonz;
    int rcoeffs;
269 270 271
    int dqp;
    int i;

272 273 274
    if( !h->param.b_cbr )
        return;

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    x264_cpu_restore( h->param.cpu );

    rc->qps += rc->qpm;
    rc->ufbits += bits;
    rc->mb++;

    for(i = 0; i < 16 + 8; i++)
        rc->nzcoeffs += 16 - h->mb.cache.non_zero_count[x264_scan8[i]];
    rc->ncoeffs += 16 * (16 + 8);

    if(rc->mb < rc->nmb / 16)
        return;
    else if(rc->mb == rc->nmb)
        return;

290
    rcoeffs = (rc->nmb - rc->mb) * 16 * 24;
291 292 293 294
    rbits = rc->fbits - rc->ufbits;
/*     if(rbits < 0) */
/*      rbits = 0; */

295 296 297 298 299 300 301 302 303
/*     zn = (rc->nmb - rc->mb) * 16 * 24; */
    nonz = (rc->ncoeffs - rc->nzcoeffs);
    if(nonz == 0)
        zn = rcoeffs;
    else if(rc->ufbits && rbits < INT_MAX / nonz)
        zn = rcoeffs - rbits * nonz / rc->ufbits;
    else
        zn = 0;
    zn = x264_clip3(zn, 0, rcoeffs);
304 305 306 307 308 309 310
    enz = rc->nzcoeffs * (rc->nmb - rc->mb) / rc->mb;
    dqp = (float) 2*h->param.i_rc_sens * exp2f((float) rc->qps / rc->mb / 6) *
        (zn - enz) / enz;
    rc->qpm = x264_clip3(rc->qpm + dqp, rc->qp - 3, rc->qp + 3);
    if(rbits <= 0)
        rc->qpm++;
    rc->qpm = x264_clip3(rc->qpm, h->param.i_qp_min, h->param.i_qp_max);
Laurent Aimar's avatar
Laurent Aimar committed
311 312
}

313
int  x264_ratecontrol_qp( x264_t *h )
Laurent Aimar's avatar
Laurent Aimar committed
314
{
315 316
    return h->rc->qpm;
}
Laurent Aimar's avatar
Laurent Aimar committed
317

318 319 320
void x264_ratecontrol_end( x264_t *h, int bits )
{
    x264_ratecontrol_t *rc = h->rc;
Laurent Aimar's avatar
Laurent Aimar committed
321

322 323
    if(!h->param.b_cbr)
        return;
Laurent Aimar's avatar
Laurent Aimar committed
324

325 326
    rc->buffer_fullness += rc->rcbufrate - bits;
    if(rc->buffer_fullness < 0){
327 328
        x264_log(h, X264_LOG_WARNING, "buffer underflow %i\n",
                 rc->buffer_fullness);
329
        rc->buffer_fullness = 0;
Laurent Aimar's avatar
Laurent Aimar committed
330 331
    }

332 333 334 335 336
    rc->qpa = rc->qps / rc->mb;
    if(rc->slice_type == SLICE_TYPE_P){
        rc->qp_avg_p += rc->qpa;
        rc->qp_last_p = rc->qpa;
        rc->pframes++;
337 338 339 340 341 342
    } else if(rc->slice_type == SLICE_TYPE_I){
        float err = (float) rc->ufbits / rc->fbits;
        if(err > 1.1)
            rc->gop_qp++;
        else if(err < 0.9)
            rc->gop_qp--;
Laurent Aimar's avatar
Laurent Aimar committed
343 344
    }

345 346
    rc->overhead = bits - rc->ufbits;

347 348 349
    x264_log(h, X264_LOG_DEBUG, "bits=%i, qp=%i, z=%i, zr=%6.3f, buf=%i\n",
             bits, rc->qpa, rc->nzcoeffs, (float) rc->nzcoeffs / rc->ncoeffs,
             rc->buffer_fullness);
350 351 352 353

    rc->bits_last_gop += bits;
    rc->frames++;
    rc->mb = 0;
Laurent Aimar's avatar
Laurent Aimar committed
354
}