1 /*****************************************************************************
2 * ratecontrol.c: h264 encoder library (Rate Control)
3 *****************************************************************************
4 * Copyright (C) 2003 Laurent Aimar
5 * $Id: ratecontrol.c,v 1.1 2004/06/03 19:27:08 fenrir Exp $
7 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
22 *****************************************************************************/
28 #include "../core/common.h"
29 #include "ratecontrol.h"
32 x264_ratecontrol_t *x264_ratecontrol_new( x264_param_t *param )
34 x264_ratecontrol_t *rc = x264_malloc( sizeof( x264_ratecontrol_t ) );
36 rc->fps = param->f_fps > 0.1 ? param->f_fps : 25.0f;
37 rc->i_iframe = param->i_iframe;
38 rc->i_bitrate = param->i_bitrate * 1000;
41 rc->i_qp = param->i_qp_constant;
49 void x264_ratecontrol_delete( x264_ratecontrol_t *rc )
54 void x264_ratecontrol_start( x264_ratecontrol_t *rc, int i_slice_type )
56 rc->i_slice_type = i_slice_type;
59 int x264_ratecontrol_qp( x264_ratecontrol_t *rc )
61 return x264_clip3( rc->i_qp, 1, 51 );
64 void x264_ratecontrol_end( x264_ratecontrol_t *rc, int bits )
69 int i_target = rc->i_bitrate / rc->fps;
72 rc->i_qp_last = rc->i_qp;
74 rc->i_size += bits / 8;
76 i_avg = 8 * rc->i_size / rc->i_frames;
78 if( rc->i_slice_type == SLICE_TYPE_I )
80 i_target = i_target * 20 / 10;
83 if( i_avg > i_target * 11 / 10 )
85 i_qp = rc->i_qp + ( i_avg / i_target - 1 );
87 else if( i_avg < i_target * 9 / 10 )
89 i_qp = rc->i_qp - ( i_target / i_avg - 1 );
92 rc->i_qp = x264_clip3( i_qp, rc->i_qp_last - 2, rc->i_qp_last + 2 );