xref: /utopia/UTPA2-700.0.x/modules/mfe/drv/mfe/cModel/msRateCtrl.c (revision 53ee8cc121a030b8d368113ac3e966b4705770ef)
1 //<MStar Software>
2 //******************************************************************************
3 // MStar Software
4 // Copyright (c) 2010 - 2012 MStar Semiconductor, Inc. All rights reserved.
5 // All software, firmware and related documentation herein ("MStar Software") are
6 // intellectual property of MStar Semiconductor, Inc. ("MStar") and protected by
7 // law, including, but not limited to, copyright law and international treaties.
8 // Any use, modification, reproduction, retransmission, or republication of all
9 // or part of MStar Software is expressly prohibited, unless prior written
10 // permission has been granted by MStar.
11 //
12 // By accessing, browsing and/or using MStar Software, you acknowledge that you
13 // have read, understood, and agree, to be bound by below terms ("Terms") and to
14 // comply with all applicable laws and regulations:
15 //
16 // 1. MStar shall retain any and all right, ownership and interest to MStar
17 //    Software and any modification/derivatives thereof.
18 //    No right, ownership, or interest to MStar Software and any
19 //    modification/derivatives thereof is transferred to you under Terms.
20 //
21 // 2. You understand that MStar Software might include, incorporate or be
22 //    supplied together with third party`s software and the use of MStar
23 //    Software may require additional licenses from third parties.
24 //    Therefore, you hereby agree it is your sole responsibility to separately
25 //    obtain any and all third party right and license necessary for your use of
26 //    such third party`s software.
27 //
28 // 3. MStar Software and any modification/derivatives thereof shall be deemed as
29 //    MStar`s confidential information and you agree to keep MStar`s
30 //    confidential information in strictest confidence and not disclose to any
31 //    third party.
32 //
33 // 4. MStar Software is provided on an "AS IS" basis without warranties of any
34 //    kind. Any warranties are hereby expressly disclaimed by MStar, including
35 //    without limitation, any warranties of merchantability, non-infringement of
36 //    intellectual property rights, fitness for a particular purpose, error free
37 //    and in conformity with any international standard.  You agree to waive any
38 //    claim against MStar for any loss, damage, cost or expense that you may
39 //    incur related to your use of MStar Software.
40 //    In no event shall MStar be liable for any direct, indirect, incidental or
41 //    consequential damages, including without limitation, lost of profit or
42 //    revenues, lost or damage of data, and unauthorized system use.
43 //    You agree that this Section 4 shall still apply without being affected
44 //    even if MStar Software has been modified by MStar in accordance with your
45 //    request or instruction for your use, except otherwise agreed by both
46 //    parties in writing.
47 //
48 // 5. If requested, MStar may from time to time provide technical supports or
49 //    services in relation with MStar Software to you for your use of
50 //    MStar Software in conjunction with your or your customer`s product
51 //    ("Services").
52 //    You understand and agree that, except otherwise agreed by both parties in
53 //    writing, Services are provided on an "AS IS" basis and the warranty
54 //    disclaimer set forth in Section 4 above shall apply.
55 //
56 // 6. Nothing contained herein shall be construed as by implication, estoppels
57 //    or otherwise:
58 //    (a) conferring any license or right to use MStar name, trademark, service
59 //        mark, symbol or any other identification;
60 //    (b) obligating MStar or any of its affiliates to furnish any person,
61 //        including without limitation, you and your customers, any assistance
62 //        of any kind whatsoever, or any information; or
63 //    (c) conferring any license or right under any intellectual property right.
64 //
65 // 7. These terms shall be governed by and construed in accordance with the laws
66 //    of Taiwan, R.O.C., excluding its conflict of law rules.
67 //    Any and all dispute arising out hereof or related hereto shall be finally
68 //    settled by arbitration referred to the Chinese Arbitration Association,
69 //    Taipei in accordance with the ROC Arbitration Law and the Arbitration
70 //    Rules of the Association by three (3) arbitrators appointed in accordance
71 //    with the said Rules.
72 //    The place of arbitration shall be in Taipei, Taiwan and the language shall
73 //    be English.
74 //    The arbitration award shall be final and binding to both parties.
75 //
76 //******************************************************************************
77 //<MStar Software>
78 //////////////////////////////////////////////////////////////////////////
79 // MStar simple rate control
80 //////////////////////////////////////////////////////////////////////////
81 
82 #include "MFE_chip.h"
83 #include "mfe_common.h"
84 #include "mfe_type.h"
85 #include "ms_dprintf.h"
86 
87 #include "mdrv_mfe_math.h"
88 
89 #include "mfe_reg.h"
90 #include "msRateCtrl.h"
91 #if defined(_MFE_T8_)&&defined(_MIPS_PLATFORM_)&&!defined(_KERNEL_MODE_)
92 #include <stdlib.h>
93 #include <stdio.h>
94 #endif
95 
96 
97 
98 // H264
99     // Spec limitation is [1, 51]
100 	#define MSRC_MAX_QP_H264  48
101 	#define MSRC_MIN_QP_H264  5
102 	#define FRAMESKIP_THR_QP_H264   40
103 // MPEG-4, H263
104     // Spec limitation is [1, 31]
105 	#define MSRC_MAX_QP_MPEG4  28
106 	#define MSRC_MIN_QP_MPEG4  1
107 	#define FRAMESKIP_THR_QP_MPEG4   20
108 
109 //! How many seconds of frames are responsible for compensation of bitrate usage.
110 #define CBR_DEPUTY_SECOND     1
111 #define CVBR_DEPUTY_SECOND    3
112 #define VBR_DEPUTY_SECOND     10
113 
114 #define MIN_DEPUTY_FACTOR 10
115 
116 //! Default I-frame weighting over inter-frame
117 // #define IFRAME_WEIGHT   2
118 // #define PFRAME_WEIGHT   1
119 #define IFRAME_WEIGHT   8
120 #define PFRAME_WEIGHT   4
121 #define BFRAME_WEIGHT	3
122 
123 #define QS_SHIFT_FACTOR	5
124 
125 #ifdef _SUPPORT_MBLEVEL_RC_
126 	#define MBACT_NORMALIZATION_FACTOR 2
127 	//#define FLAT_AREA_VAR_THR          5
128 	#define SPEC_QP_DIFF_LIMIT         2 // Spec limitation
129 	#define USE_INT_PREC
130 	// Below are used when USE_INT_PREC
131 	#define SCALE_BITS                 6
132 	#define SCALE_ACT                  6
133 #endif
134 
135 //////////////////////////////////////////////////////////////////////////
136 // global variables
137 //////////////////////////////////////////////////////////////////////////
138 #ifndef _USE_EXT_RCDATA_
139 	CVBRRateControl g_cvbrContext;
140 	CVBRRCInfo g_cvbrInfo;
141 	int g_cvbrFrameSkip;
142 #endif
143 
144 //private:
145 int cvbr_ComputeFrameQP(CVBRRateControl* ct, int nFrameType);	// Return the target 'QStep'
146 int cvbr_ComputeMbQP(CVBRRateControl* ct, int mb_idx);	// Return the target 'QP'
147 
148 int rcQP2Qstep(CVBRRateControl* ct, int QP);
149 int rcQstep2QP(CVBRRateControl* ct, int QstepX32);
150 
151 /*
152 void output_MBR_reg(void* hd, CVBRRateControl* ct)
153 {
154     if (ct->m_nVPMbRow>0 && ct->m_nVPSize<=0)
155         sd_output(hd, 0, 2, "reg_mfe_g_er_mode");
156     else if (ct->m_nVPMbRow<=0 && ct->m_nVPSize>0)
157         sd_output(hd, 1, 2, "reg_mfe_g_er_mode");
158     else if (ct->m_nVPMbRow>0 && ct->m_nVPSize>0)
159         sd_output(hd, 2, 2, "reg_mfe_g_er_mode");
160     else
161         sd_output(hd, 3, 2, "reg_mfe_g_er_mode");
162     if (ct->m_nVPMbRow==1)
163         sd_output(hd, 0, 2, "reg_mfe_g_er_mby");
164     else if (ct->m_nVPMbRow==2)
165         sd_output(hd, 1, 2, "reg_mfe_g_er_mby");
166     else if (ct->m_nVPMbRow==4)
167         sd_output(hd, 2, 2, "reg_mfe_g_er_mby");
168     else if (ct->m_nVPMbRow==8)
169         sd_output(hd, 3, 2, "reg_mfe_g_er_mby");
170     else
171         sd_output(hd, 0, 2, "reg_mfe_g_er_mby");
172 }
173 */
174 
cvbr_InitRateControl(CVBRRateControl * ct,CVBRRCInfo * pRCInfo)175 void cvbr_InitRateControl(CVBRRateControl* ct, CVBRRCInfo* pRCInfo)
176 {
177 	int i, j;
178 
179 	ct->m_nFrameCount = 0;
180 
181 	MFE_ASSERT(pRCInfo->nWidth<=MAX_MB_WIDTH*16);
182 	if (pRCInfo->rcMethod==CONST_QUALITY)
183 		MFE_ASSERT(pRCInfo->rcGranularity==FRAMELEVELRC);
184 	// Copy parameters, no error checking yet.
185 	ct->m_nCodecType = pRCInfo->nCodecType;
186 	ct->m_nWidth = pRCInfo->nWidth;
187 	ct->m_nHeight = pRCInfo->nHeight;
188 /*
189 	if (pRCInfo->fTargetFrameRate - (int)pRCInfo->fTargetFrameRate != 0) {
190 		switch ((int)pRCInfo->fTargetFrameRate) {
191 		case 14:	// 14.985
192 			ct->m_nTargetFrameRateNum = 15000;
193 			ct->m_nTargetFrameRateDeNum = 1001;
194 			break;
195 		case 23:	// 23.976
196 			ct->m_nTargetFrameRateNum = 24000;
197 			ct->m_nTargetFrameRateDeNum = 1001;
198 			break;
199 		case 29:	// 29.97
200 			ct->m_nTargetFrameRateNum = 30000;
201 			ct->m_nTargetFrameRateDeNum = 1001;
202 			break;
203 		default:
204 			MFE_ASSERT(0);
205 		}
206 	}
207 */
208 	//2010/01/21 because LG GP3 no support float operation, so only support 29.97 now.
209 	//if fps is 29.97, fTargetFrameRate_is_float =1
210 	if (pRCInfo->fTargetFrameRate_is_float==1) {
211 			ct->m_nTargetFrameRateNum = 30000;
212 			ct->m_nTargetFrameRateDeNum = 1001;
213 	}
214 	else {
215 		ct->m_nTargetFrameRateNum = pRCInfo->int_fTargetFrameRate;
216 		ct->m_nTargetFrameRateDeNum = 1;
217 	}
218 
219 	ct->m_nTargetFrameRateInt = ct->m_nTargetFrameRateNum / ct->m_nTargetFrameRateDeNum;
220 	ct->m_nBitrate = pRCInfo->nBitrate;
221 	ct->m_nMaxBitrate = pRCInfo->nMaxBitrate;
222 	ct->m_nConstQP = pRCInfo->nConstQP;
223 	ct->m_nVPSize = pRCInfo->nVPSize;
224 	ct->m_nVPMbRow = pRCInfo->nVPMbRow;
225 	ct->m_bFixedFrameRate = pRCInfo->bFixedFrameRate;
226 	ct->m_nPCount = pRCInfo->nPCount;
227 	ct->m_nBCount = pRCInfo->nBCount;
228 	ct->m_rcGranularity = pRCInfo->rcGranularity;
229 	ct->m_rcMethod = pRCInfo->rcMethod;
230 	// More bitrate checking
231 	if (ct->m_rcMethod==CONSTRAINED_VARIABLE_BITRATE) {
232 		if (ct->m_nBitrate==0)
233 			ct->m_nBitrate = (int)(ct->m_nMaxBitrate *6/10);
234 		if (ct->m_nMaxBitrate==0)
235 			ct->m_nMaxBitrate = (int)(ct->m_nBitrate * 14/10);
236 	ct->m_nMaxOffset = (int)MFE_DIV_S64((MFE_S64)(ct->m_nMaxBitrate - ct->m_nBitrate)*ct->m_nTargetFrameRateDeNum, ct->m_nTargetFrameRateNum) ;
237 //	ct->m_nMaxOffset = (int)((MFE_S64)(ct->m_nMaxBitrate - ct->m_nBitrate)*ct->m_nTargetFrameRateDeNum / ct->m_nTargetFrameRateNum);
238 
239 		if (ct->m_rcGranularity==FRAMELEVELRC)
240 			ct->m_nMaxOffset = (ct->m_nMaxOffset) >> 2;
241 	}
242 	else {
243 		ct->m_nMaxBitrate = 0;  // Don't care
244 	}
245 
246 	// Derived
247 	ct->m_nAvgBitsPerFrame = (int)MFE_DIV_S64((MFE_S64)ct->m_nBitrate*ct->m_nTargetFrameRateDeNum, ct->m_nTargetFrameRateNum) ;
248 	//ct->m_nAvgBitsPerFrame = (int)((MFE_S64)ct->m_nBitrate *ct->m_nTargetFrameRateDeNum / ct->m_nTargetFrameRateNum);
249 
250 	i = 1+ct->m_nPCount*(1+ct->m_nBCount);
251 	j = IFRAME_WEIGHT + PFRAME_WEIGHT*ct->m_nPCount + BFRAME_WEIGHT*(ct->m_nPCount*ct->m_nBCount);
252 	ct->m_nBitsPerFrame[0] = (int)MFE_DIV_S64((MFE_S64)ct->m_nBitrate*ct->m_nTargetFrameRateDeNum*IFRAME_WEIGHT*i, j*ct->m_nTargetFrameRateNum);
253 	ct->m_nBitsPerFrame[1] = (int)MFE_DIV_S64((MFE_S64)ct->m_nBitrate*ct->m_nTargetFrameRateDeNum*PFRAME_WEIGHT*i,j*ct->m_nTargetFrameRateNum);
254 	ct->m_nBitsPerFrame[2] = (int)MFE_DIV_S64((MFE_S64)ct->m_nBitrate*ct->m_nTargetFrameRateDeNum*BFRAME_WEIGHT*i,j*ct->m_nTargetFrameRateNum);
255 #ifdef _SUPPORT_MBLEVEL_RC_
256 	ct->m_nMbWidth = (ct->m_nWidth+15)>>4;
257 #endif
258 
259 	// QP, QStep: min, max
260 	if (ct->m_nCodecType==REG_ENC_MODE_MPG4 || ct->m_nCodecType==REG_ENC_MODE_H263) {
261 		ct->m_nMinQP = MSRC_MIN_QP_MPEG4;
262 		ct->m_nMaxQP = MSRC_MAX_QP_MPEG4;
263 		ct->m_nMinQStep = rcQP2Qstep(ct, MSRC_MIN_QP_MPEG4)-1;
264 		ct->m_nMaxQStep = rcQP2Qstep(ct, MSRC_MAX_QP_MPEG4);
265 		ct->m_nFrameSkipThrQP = FRAMESKIP_THR_QP_MPEG4;
266 	}
267 	else {
268 		ct->m_nMinQP = MSRC_MIN_QP_H264;
269 		ct->m_nMaxQP = MSRC_MAX_QP_H264;
270 		ct->m_nMinQStep = rcQP2Qstep(ct, MSRC_MIN_QP_H264)-1;
271 		ct->m_nMaxQStep = rcQP2Qstep(ct, MSRC_MAX_QP_H264);
272 		ct->m_nFrameSkipThrQP = FRAMESKIP_THR_QP_H264;
273 		MFE_ASSERT(ct->m_nCodecType==REG_ENC_MODE_H264);
274 	}
275 
276 	// Bitrate usage monitoring
277 	ct->m_nMinDeputyCount = (ct->m_nTargetFrameRateNum*CBR_DEPUTY_SECOND)/ct->m_nTargetFrameRateDeNum;
278 	ct->m_nTargetFullness = ct->m_nBitrate >> 1;
279 	ct->m_nBufFullness = ct->m_nTargetFullness;
280 	switch (ct->m_rcMethod) {
281 		case VARIABLE_BITRATE:
282 			ct->m_nDeputyCount = (ct->m_nTargetFrameRateNum*VBR_DEPUTY_SECOND)/ct->m_nTargetFrameRateDeNum;
283 			break;
284 		case CONSTRAINED_VARIABLE_BITRATE:
285 			ct->m_nDeputyCount = (ct->m_nTargetFrameRateNum*CVBR_DEPUTY_SECOND)/ct->m_nTargetFrameRateDeNum;
286 			ct->m_BitrateGauge[0] = ct->m_nBitsPerFrame[0];
287 			for (i=1; i<MAX_GAUGE_SIZE; i++) {
288 				ct->m_BitrateGauge[i] = ct->m_nBitsPerFrame[1];
289 				for (j=0; j<ct->m_nBCount; j++, i++) {
290 					if (i==MAX_GAUGE_SIZE) break;
291 					ct->m_BitrateGauge[i] = ct->m_nBitsPerFrame[2];
292 				}
293 			}
294 			ct->m_nGaugeCount = ct->m_nTargetFrameRateInt;
295 			ct->m_nGaugeIndex = 0;
296 			ct->m_nGaugeBitrate = (int)MFE_DIV_S64((MFE_S64)ct->m_nBitrate*ct->m_nTargetFrameRateDeNum*ct->m_nGaugeCount, ct->m_nTargetFrameRateNum) ;
297 			//ct->m_nGaugeBitrate = (int)((MFE_S64)ct->m_nBitrate*ct->m_nTargetFrameRateDeNum*ct->m_nGaugeCount) / ct->m_nTargetFrameRateNum;
298 			break;
299 		case CONST_BITRATE:
300 		default:
301 	ct->m_nDeputyCount = (int)MFE_DIV_S64((MFE_S64)ct->m_nTargetFrameRateNum*CBR_DEPUTY_SECOND,ct->m_nTargetFrameRateDeNum) ;
302 	//ct->m_nDeputyCount = (int)((MFE_S64)ct->m_nTargetFrameRateNum*CBR_DEPUTY_SECOND)/ct->m_nTargetFrameRateDeNum;
303 			break;
304 	}
305 
306 	ct->m_nFrameCount = 0;
307 	ct->m_nTotalBits = 0;
308 	ct->m_nLastFrameAvgQP[0] = ct->m_nLastFrameAvgQP[1] = ct->m_nLastFrameBits = 0;
309 	ct->m_nLongTermQP64 = 0;
310 
311 	ct->m_nTotalMB = (ct->m_nWidth>>4)*(ct->m_nHeight>>4);
312 #ifndef _USE_EXT_RCDATA_
313 	g_cvbrFrameSkip = 0;
314 #endif
315 
316 
317 //	ms_dprintk(DRV_L3,"[CVBRRC] InitRateControl: w=%d, h=%d, FPS=%2.3f, FixedFPS=%d, Bitrate=%d\n",
318 //		ct->m_nWidth, ct->m_nHeight, (float)ct->m_nTargetFrameRateNum/ct->m_nTargetFrameRateDeNum,
319 //		ct->m_bFixedFrameRate, ct->m_nBitrate);
320 
321 
322 
323 
324 }
325 
326 
cvbr_CloseRateControl(CVBRRateControl * ct)327 void cvbr_CloseRateControl(CVBRRateControl* ct)
328 {
329 }
330 
331 // FieldType: 0--Progressive, 1--First field, 2--second field.
cvbr_InitFrame(CVBRRateControl * ct,int nFrameType,char FieldType)332 int cvbr_InitFrame(CVBRRateControl* ct, int nFrameType, char FieldType)
333 {
334 	int nDeputyCount = 0;
335 	int delta = 0, nRtnQP;
336 
337 	if (FieldType==0||FieldType==1)
338 		ct->m_bIsBotField = 0;
339 	else
340 		ct->m_bIsBotField = 1;	// FieldType is 2
341 
342 	ct->m_nFrameType = nFrameType;
343 	ct->m_nLastVPBits = 0;
344 	ct->m_nNewPacket = 0;
345 
346 	// Target frame bitcount
347 	if (FieldType!=2)
348 	{
349 		if (ct->m_nFrameCount>0) {
350 			// 1. Determine the number of future frame to compensate for current bitrate mismatch.
351 			if (ct->m_nFrameCount>ct->m_nDeputyCount*MIN_DEPUTY_FACTOR)
352 				nDeputyCount = ct->m_nDeputyCount;
353 			else if (ct->m_nFrameCount<ct->m_nMinDeputyCount)
354 				nDeputyCount = ct->m_nMinDeputyCount;
355 			else
356 				nDeputyCount = ct->m_nMinDeputyCount +
357 				(ct->m_nFrameCount-ct->m_nMinDeputyCount)*(ct->m_nDeputyCount-ct->m_nMinDeputyCount)/(ct->m_nDeputyCount*MIN_DEPUTY_FACTOR-ct->m_nMinDeputyCount);
358 			// 2. Calculate the bitcount that this frame should be compensate for.
359 			if (ct->m_rcMethod==CONST_BITRATE) {
360 			delta = (int)MFE_DIV_S64((MFE_S64)(ct->m_nBufFullness-ct->m_nTargetFullness)*ct->m_nTargetFrameRateDeNum, ct->m_nTargetFrameRateNum) ;
361 		       //delta = (int)((MFE_S64)(ct->m_nBufFullness-ct->m_nTargetFullness)*ct->m_nTargetFrameRateDeNum)/ct->m_nTargetFrameRateNum;
362 
363 
364 // 			delta = (ct->m_nBufFullness>ct->m_nTargetFullness) ?
365 // 				(int)((ct->m_nBufFullness-ct->m_nTargetFullness)/ct->m_fTargetFrameRate) : ct->m_nBufFullness-ct->m_nTargetFullness;
366 			}
367 			else if (ct->m_rcMethod==CONSTRAINED_VARIABLE_BITRATE) {
368 				delta = (ct->m_nBufFullness-ct->m_nTargetFullness) / nDeputyCount;
369 				if (delta<-ct->m_nMaxOffset)
370 					delta = -ct->m_nMaxOffset;
371 			}
372 			else if (ct->m_rcMethod==VARIABLE_BITRATE) {
373 				delta = (ct->m_nBufFullness-ct->m_nTargetFullness) / nDeputyCount;
374 				if (delta>0 && ((ct->m_nLastFrameAvgQP[0]<<6)>ct->m_nLongTermQP64))
375 					delta = delta>>1;  // Make it more variable bitrate to allow better quality
376 			}
377 			// 3. Finally, calculate the target bitcount.
378 			if (ct->m_nPCount==0) {
379 				ct->m_nTargetBits = ct->m_nBitsPerFrame[0] - delta;
380 			}
381 			else {
382 				switch (nFrameType) {
383 			case I_VOP:
384 				ct->m_nTargetBits = ct->m_nBitsPerFrame[0] - delta;
385 				break;
386 			case P_VOP:
387 				ct->m_nTargetBits = ct->m_nBitsPerFrame[1] - delta;
388 				break;
389 			case B_VOP:
390 				ct->m_nTargetBits = ct->m_nBitsPerFrame[2] - delta;
391 				break;
392 				}
393 			}
394 			if (ct->m_nTargetBits<=(ct->m_nAvgBitsPerFrame>>3))
395 				ct->m_nTargetBits = (ct->m_nAvgBitsPerFrame>>3);  // Target bitcount must>0 for ComputeFrameQP()
396 		}
397 		else {
398 			ct->m_nTargetBits = ct->m_nBitsPerFrame[0];    // Must be I-frame
399 		}
400 
401 		/* Return initial frame QP */
402 
403 		ct->m_nFrameQP = cvbr_ComputeFrameQP(ct, nFrameType);
404 
405 		ct->m_nLastFrameAvgQP[0] = ct->m_nLastFrameAvgQP[1] = 0;
406 		ct->m_nLastFrameBits = 0;
407 
408 #ifdef _SUPPORT_MBLEVEL_RC_
409 		ct->m_nTargetMbBits = ct->m_nTargetBits / ct->m_nTotalMB;
410 #endif
411 	}
412 	else {	// bottom field
413 		int nTargetBits;
414 		ct->m_nFrameQP = ct->m_nLastFrameAvgQP[0] / ((ct->m_nTotalMB>>1)-1);
415 #ifdef _SUPPORT_MBLEVEL_RC_
416 		nTargetBits = ct->m_nTargetBits - ct->m_nLastFrameBits;
417 		if (nTargetBits<ct->m_nTargetBits>>3)
418 			nTargetBits = ct->m_nTargetBits>>3;
419 		ct->m_nTargetMbBits = nTargetBits / (ct->m_nTotalMB>>1);
420 #endif
421 	}
422 
423 #ifdef _SUPPORT_MBLEVEL_RC_
424 	ct->m_nMBN = 0;
425 	if (ct->m_nTargetMbBits<1)
426 		ct->m_nTargetMbBits = 1;
427 #endif
428 
429 	nRtnQP = rcQstep2QP(ct, ct->m_nFrameQP);
430 	//ct->m_nFrameQP = rcQP2Qstep(ct, nRtnQP);
431 
432 //	ms_dprintk(DRV_L3,"[CVBRRC] %5d%s[%s] InitFrame: TargetBits %7d InitQP %2d Buffer %7d Deputy=%d\n",
433 //		ct->m_nFrameCount, FieldType==0?"F":(FieldType==1?"T":"B"), nFrameType==I_VOP?"I":(nFrameType==P_VOP?"P":"B"),
434 //		(int)(ct->m_nTargetBits), nRtnQP, ct->m_nBufFullness, nDeputyCount);
435 
436 	return nRtnQP;
437 }
438 
cvbr_UpdateFrame(CVBRRateControl * ct,int totalUsedBits,char bDummyFrame,char FieldType)439 int cvbr_UpdateFrame(CVBRRateControl* ct, int totalUsedBits, char bDummyFrame, char FieldType)
440 {
441 	int frameskip = 0;
442 
443 	// Update counter
444 	ct->m_nTotalBits += totalUsedBits;
445 	ct->m_nLastFrameBits += totalUsedBits;
446 	ct->m_nBufFullness += totalUsedBits;
447 	if (FieldType!=1) {
448 		ct->m_nFrameCount++;
449 		ct->m_nLastTargetBits = ct->m_nTargetBits;
450 
451 		if (!bDummyFrame) {
452 			ct->m_nLastFrameAvgQP[0] = (ct->m_nLastFrameAvgQP[0]+ct->m_nLastFrameAvgQP[1]) / (FieldType==0 ? ct->m_nTotalMB-1 : ct->m_nTotalMB-2);
453 			// Variable bitrate
454 			if (ct->m_rcMethod==VARIABLE_BITRATE)
455 				ct->m_nLongTermQP64 += ((ct->m_nLastFrameAvgQP[0]<<6)-ct->m_nLongTermQP64) / ct->m_nFrameCount;
456 			else if (ct->m_rcMethod==CONSTRAINED_VARIABLE_BITRATE) {
457 				if (ct->m_nFrameCount==1)
458 					ct->m_nLongTermQP64 = ct->m_nLastFrameAvgQP[0]<<6;
459 				else
460 					ct->m_nLongTermQP64 = (ct->m_nLongTermQP64*(ct->m_nDeputyCount-1) + (ct->m_nLastFrameAvgQP[0]<<6)) / ct->m_nDeputyCount;
461 			}
462 		}
463 		else {
464 			ct->m_nLastFrameAvgQP[0] = ct->m_nFrameQP;
465 		}
466 
467 		if (ct->m_rcMethod==CONSTRAINED_VARIABLE_BITRATE) {
468 			ct->m_nGaugeBitrate -= ct->m_BitrateGauge[ct->m_nGaugeIndex];
469 			ct->m_nGaugeBitrate += totalUsedBits;
470 			ct->m_BitrateGauge[ct->m_nGaugeIndex] = totalUsedBits;
471 			ct->m_nGaugeIndex++;
472 			if (ct->m_nGaugeIndex==ct->m_nGaugeCount)
473 				ct->m_nGaugeIndex = 0;
474 		}
475 
476 		// Update buffer status
477 		ct->m_nBufFullness -= ct->m_nAvgBitsPerFrame;
478 	}
479 
480 
481 	// Check if next skipped frame(s) needed
482 	if (FieldType!=1 && !ct->m_bFixedFrameRate && !bDummyFrame)
483 	{
484 		if (ct->m_rcMethod==CONSTRAINED_VARIABLE_BITRATE || ct->m_rcMethod==VARIABLE_BITRATE) {
485 			if (   ct->m_nLongTermQP64>(rcQP2Qstep(ct, ct->m_nFrameSkipThrQP)<<6)
486 				&& ct->m_nLastFrameBits >= (ct->m_nLastTargetBits<<1) ) {
487 					//frameskip = (ct->m_nLastFrameBits / ct->m_nLastTargetBits)-1;
488 					frameskip = (int)((ct->m_nLastFrameBits - ct->m_nLastTargetBits) / ct->m_nAvgBitsPerFrame - 1);
489 					if (frameskip<0)
490 						frameskip = 0;
491 					else if (frameskip>ct->m_nMaxFrozenFrame)
492 						frameskip = ct->m_nMaxFrozenFrame;
493 			}
494 		}
495 		else if (ct->m_rcMethod==CONST_BITRATE) {
496 			if (ct->m_nLastFrameAvgQP[0]>rcQP2Qstep(ct, ct->m_nFrameSkipThrQP)) {
497 				// Actual fullness is updated after encoding dummy-P frame
498 				int nBufFullness = ct->m_nBufFullness;
499 				while (nBufFullness > ct->m_nTargetFullness) {
500 					nBufFullness = (int)(nBufFullness - ct->m_nAvgBitsPerFrame);
501 					frameskip += 1;
502 				}
503 			}
504 		}
505 	}
506 
507 #ifdef DEBUG
508 	if (frameskip > 255)
509 	{
510 		fprintf (stderr, "Warning: frameskip > 255\n");
511 	}
512 	if (FieldType!=1){
513 	    MFE_S64 tmp_bitrate ;
514 	    tmp_bitrate= (int)MFE_DIV_S64((MFE_S64)ct->m_nTotalBits*ct->m_nTargetFrameRateNum, ct->m_nFrameCount*ct->m_nTargetFrameRateDeNum) ;
515 
516 //	    ms_dprintk(DRV_L3,"[CVBRRC] UpdateFrame(%7d bits, %3d%%) AvgQ=%2d LTQ=%2d Bitrate=%8d frameskip=%2d\n",
517 //		ct->m_nLastFrameBits, (ct->m_nLastFrameBits-ct->m_nTargetBits)*100/ct->m_nTargetBits, rcQstep2QP(ct, ct->m_nLastFrameAvgQP[0]),
518 //		(int)(ct->m_nLongTermQP64+32)>>6,(int)tmp_bitrate, frameskip);
519 	}
520 
521 //	DEBUG_RC(("[CVBRRC]       UpdateFrame(%7d bits, %3d%%) AvgQ=%2d LTQ=%2d Bitrate=%8d frameskip=%2d\n",
522 //	totalUsedBits, (totalUsedBits-ct->m_nTargetBits)*100/ct->m_nTargetBits, ct->m_nLastFrameAvgQP[0],
523 //	(int)ct->m_fLongTermQP, ct->m_nGaugeBitrate, frameskip));
524 #endif
525 
526 	return frameskip;
527 }
528 
529 #define SMOOTH_PERIOD	1
530 #define INIT_QP_FACTOR	720
531 #define MIN_INIT_QP		1
532 #define MAX_INIT_QP		15
533 
534 /* Return target QPStep */
cvbr_ComputeFrameQP(CVBRRateControl * ct,int nFrameType)535 int cvbr_ComputeFrameQP(CVBRRateControl* ct, int nFrameType)
536 {
537 	int newQPStep=0;
538 	MFE_S64 buf_rest;
539 	int buf_rest_pic;
540 	int frames_left;
541 	int nAdjust;
542 
543 	int bitrate = ct->m_nBitrate;
544 	int targetFPS_DeNum =  ct->m_nTargetFrameRateDeNum;
545 	int targetFPS_Num =  ct->m_nTargetFrameRateNum;
546 	int TotalMB = ct->m_nTotalMB;
547 	int frame_count = ct->m_nFrameCount;
548 
549 	// For the very first frame, guess one qp!
550 	if (ct->m_nFrameCount==0) {
551 		int nbpMb, newQP;
552 		if (ct->m_rcMethod==CONST_QUALITY) {
553 			newQP = ct->m_nConstQP;
554 			newQPStep = rcQP2Qstep(ct, newQP);	// So that frame qp will be exactly ct->m_nConstQP
555 		}
556 		else {
557 	              nbpMb= (int)MFE_DIV_S64((MFE_S64)bitrate*targetFPS_DeNum, TotalMB*targetFPS_Num) +1 ;
558 	          //nbpMb = (int)((MFE_S64)ct->m_nBitrate*ct->m_nTargetFrameRateDeNum)/(ct->m_nTotalMB*ct->m_nTargetFrameRateNum) + 1;
559 			newQP = INIT_QP_FACTOR / nbpMb;
560 			if (newQP<MIN_INIT_QP)
561 				newQP = MIN_INIT_QP;
562 			else if (newQP>MAX_INIT_QP)
563 				newQP = MAX_INIT_QP;
564 			newQPStep = newQP<<QS_SHIFT_FACTOR;
565 		}
566 
567 		ct->m_nMaxFrozenFrame = newQP>>1;
568 		if (ct->m_nMaxFrozenFrame>15)
569 			ct->m_nMaxFrozenFrame=15;
570 		return newQPStep;
571 	}
572 
573 	if (ct->m_rcMethod==CONST_QUALITY)
574 		return rcQP2Qstep(ct, ct->m_nConstQP);
575 
576 	if (ct->m_rcMethod==CONST_BITRATE) {
577 	       buf_rest= MFE_DIV_S64((MFE_S64)frame_count*targetFPS_DeNum*bitrate, targetFPS_Num) ;
578           //buf_rest = (((MFE_S64)ct->m_nFrameCount*ct->m_nTargetFrameRateDeNum*ct->m_nBitrate)/ct->m_nTargetFrameRateNum);
579 
580 		buf_rest += (SMOOTH_PERIOD*ct->m_nBitrate) - ct->m_nTotalBits;
581 
582 		newQPStep = ct->m_nLastFrameAvgQP[0];
583 		frames_left = (SMOOTH_PERIOD * ct->m_nTargetFrameRateNum) / ct->m_nTargetFrameRateDeNum;
584 		//if (frames_left > 0)
585 		{
586 			int dQP;
587 			buf_rest_pic = (int)MFE_DIV_S64(buf_rest , frames_left);
588 			dQP = ct->m_nLastFrameAvgQP[0]>>3;
589 			if (ct->m_nLastFrameBits > (buf_rest_pic*9)>>3) {
590 				newQPStep = ct->m_nLastFrameAvgQP[0]+dQP;
591 			}
592 			else if (ct->m_nLastFrameBits < (buf_rest_pic*7)>>3) {
593 				newQPStep = ct->m_nLastFrameAvgQP[0]-dQP;
594 			}
595 		}
596 	}
597 
598 	else if (ct->m_rcMethod==CONSTRAINED_VARIABLE_BITRATE) {
599  		int nLowBound, nHighBound;
600 		nAdjust = ct->m_nLongTermQP64>>2;
601 		nLowBound = (ct->m_nLongTermQP64 - nAdjust) >> 6;
602 		nHighBound = (ct->m_nLongTermQP64 + nAdjust) >> 6;
603 		if (ct->m_nPCount>0 && nFrameType==I_VOP) {
604 			newQPStep = ct->m_nLastFrameAvgQP[0];
605 			if (ct->m_nGaugeBitrate<ct->m_nBitrate)
606 				newQPStep = newQPStep-(1<<QS_SHIFT_FACTOR);
607 			newQPStep = MSRC_MAX((1<<QS_SHIFT_FACTOR), newQPStep);
608 			newQPStep = MSRC_MIN((12<<QS_SHIFT_FACTOR), newQPStep);
609 		}
610 		else {
611 			MFE_S64 tmp;
612 	              tmp= MFE_DIV_S64((MFE_S64)ct->m_nLongTermQP64 * MFE_DIV_S64(ct->m_nTotalBits,ct->m_nFrameCount), ct->m_nTargetBits) ;
613                  //tmp = ct->m_nLongTermQP64 * (ct->m_nTotalBits/ct->m_nFrameCount) /ct->m_nTargetBits);
614 			MFE_ASSERT((tmp >> 6) < (1<<31));
615 	              newQPStep=  (int)(
616 				  	MFE_DIV_S64((MFE_S64)ct->m_nLongTermQP64 * MFE_DIV_S64(ct->m_nTotalBits,ct->m_nFrameCount),
617 				  	             ct->m_nTargetBits)  >>6) ;
618 	//newQPStep = (int)((ct->m_nLongTermQP64 * (ct->m_nTotalBits/ct->m_nFrameCount) / ct->m_nTargetBits) >> 6);
619 			if (ct->m_nLastFrameBits>ct->m_nLastTargetBits) {
620 				nAdjust = ((ct->m_nLastFrameBits-ct->m_nLastTargetBits)/ct->m_nMaxOffset) + (1<<QS_SHIFT_FACTOR);
621 				if (nAdjust>(3<<QS_SHIFT_FACTOR)) nAdjust=(3<<QS_SHIFT_FACTOR);
622 				if ((ct->m_nLastFrameAvgQP[0]<<6) > ct->m_nLongTermQP64) {  // Danger! Make it more aggressive
623 					nHighBound = ct->m_nLastFrameAvgQP[0]+nAdjust;
624 					newQPStep = ct->m_nLastFrameAvgQP[0]+nAdjust;
625 				}
626 				else {
627 					nHighBound += nAdjust;
628 					newQPStep += nAdjust;
629 				}
630 			}
631 			else if (ct->m_nGaugeBitrate>ct->m_nBitrate) {
632 				if (newQPStep < ct->m_nLastFrameAvgQP[0])
633 					newQPStep = ct->m_nLastFrameAvgQP[0];
634 				if ((newQPStep<<6) < ct->m_nLongTermQP64)
635 					newQPStep = ct->m_nLongTermQP64>>6;
636 			}
637 			else {
638 				if ((newQPStep<<6) >= ct->m_nLongTermQP64)
639 					newQPStep = (ct->m_nLongTermQP64>>6)-1;
640 				if (ct->m_nTargetFullness>ct->m_nBufFullness) {
641 					nAdjust = (ct->m_nTargetFullness-ct->m_nBufFullness) / (int)ct->m_nBitrate;
642 					newQPStep -= nAdjust;
643 				}
644 			}
645 		}
646 		newQPStep = MSRC_MIN(nHighBound, newQPStep);
647 		newQPStep = MSRC_MAX(nLowBound, newQPStep);
648 	}
649 	else if (ct->m_rcMethod==VARIABLE_BITRATE) {
650 		int nLowBound, nHighBound;
651 		if (ct->m_nPCount>0 && nFrameType==I_VOP) {
652 			newQPStep = ct->m_nLastFrameAvgQP[0];
653 			if ((ct->m_nLastFrameAvgQP[0]<<6) > ct->m_nLongTermQP64)
654 				newQPStep = newQPStep-(1<<QS_SHIFT_FACTOR);
655 		}
656 		else {
657 			int nAdjLTQ;
658 			MFE_S64 tmp;
659 			if (ct->m_nFrameCount>=ct->m_nTargetFrameRateInt || ct->m_nPCount==0) {
660 	              tmp=  MFE_DIV_S64(
661 				  	(MFE_S64)ct->m_nLongTermQP64 * MFE_DIV_S64(ct->m_nTotalBits,ct->m_nFrameCount),
662 				  	ct->m_nAvgBitsPerFrame) ;
663                  //tmp = ct->m_nLongTermQP64 * (ct->m_nTotalBits/ct->m_nFrameCount) / ct->m_nAvgBitsPerFrame;
664 				MFE_ASSERT((tmp >> 6) < (1<<31));
665 
666 	              nAdjLTQ=  (int)(MFE_DIV_S64(
667 				  	(MFE_S64)ct->m_nLongTermQP64 * MFE_DIV_S64(ct->m_nTotalBits,ct->m_nFrameCount),
668 				  	ct->m_nAvgBitsPerFrame)   >>6) ;
669 	//nAdjLTQ = (int)((ct->m_nLongTermQP64 * (ct->m_nTotalBits/ct->m_nFrameCount) / ct->m_nAvgBitsPerFrame) >> 6);
670 
671 			}
672 			else {
673 				nAdjLTQ = ct->m_nLongTermQP64>>6;   // Wait for stabilization
674 			}
675 			MFE_ASSERT(ct->m_nTargetBits>0);
676 			newQPStep = (nAdjLTQ * ct->m_nAvgBitsPerFrame) / ct->m_nTargetBits;
677 
678 			nAdjust = MSRC_MAX((2<<QS_SHIFT_FACTOR), (int)(nAdjLTQ)>>2);
679 			nLowBound = (int)(nAdjLTQ) - nAdjust;
680 			nHighBound = (int)(nAdjLTQ) + nAdjust;
681 			if (ct->m_nLastFrameBits>ct->m_nLastTargetBits) {
682 				nAdjust = (int)(ct->m_nLastFrameBits/ct->m_nLastTargetBits);
683 				if (nAdjust>2) nAdjust=2;
684 				nHighBound += nAdjust;
685 			}
686 
687 			if (ct->m_nAvgBitsPerFrame>ct->m_nTargetBits) {
688 				newQPStep = MSRC_MIN(nHighBound, newQPStep);
689 			}
690 			else {
691 				newQPStep = MSRC_MAX(nLowBound, newQPStep);
692 			}
693 		}
694 	}
695 
696 	return newQPStep;
697 }
698 
699 // int QP2QSTEP32[52] = {	// QP2Qstep(QP) * 32
700 // 	20,
701 // 	22, 26, 28, 32, 36, 40, 44, 52, 56, 64,
702 // 	72, 80, 88, 104, 112, 128, 144, 160, 176, 208,
703 // 	224, 256, 288, 320, 352, 416, 448, 512, 576, 640,
704 // 	704, 832, 896, 1024, 1152, 1280, 1408, 1664, 1792, 2048,
705 // 	2304, 2560, 2816, 3328, 3584, 4096, 4608, 5120, 5632, 6656,
706 // 	7168,
707 // };
rcQP2Qstep(CVBRRateControl * ct,int QP)708 int rcQP2Qstep(CVBRRateControl* ct,  int QP)
709 {
710     if (ct->m_nCodecType==REG_ENC_MODE_H264)
711     {
712         int i;
713         int Qstep;
714         static const int QP2QSTEP[6] = { 20, 22, 26, 28, 32, 36 };
715 
716         Qstep = QP2QSTEP[QP % 6];
717         for( i=0; i<(QP/6); i++)
718             Qstep *= 2;
719 
720         return Qstep;
721     }
722     else
723     {
724         return QP<<QS_SHIFT_FACTOR;
725     }
726 
727     return 0;   // Should never entering this.
728 }
729 
rcQstep2QP(CVBRRateControl * ct,int QstepX32)730 int rcQstep2QP(CVBRRateControl* ct, int QstepX32)
731 {
732     if (ct->m_nCodecType==REG_ENC_MODE_H264)
733     {
734         int q_per = 0, q_rem = 0;
735 
736         //  MFE_ASSERT( QstepX32 >= QP2QSTEP[0] && QstepX32 <= QP2QSTEP[51]);
737         if( QstepX32 <= ct->m_nMinQStep)
738             return ct->m_nMinQP;
739         else if (QstepX32 > ct->m_nMaxQStep)
740             return ct->m_nMaxQP;
741 
742         while( QstepX32 > rcQP2Qstep(ct, 5) )
743         {
744             QstepX32 >>= 1;
745             q_per += 1;
746         }
747 
748         if (QstepX32 <= 21)
749         {
750             QstepX32 = 20;
751             q_rem = 0;
752         }
753         else if (QstepX32 <= 24)
754         {
755             QstepX32 = 22;
756             q_rem = 1;
757         }
758         else if (QstepX32 <= 27)
759         {
760             QstepX32 = 26;
761             q_rem = 2;
762         }
763         else if (QstepX32 <= 30)
764         {
765             QstepX32 = 28;
766             q_rem = 3;
767         }
768         else if (QstepX32 <= 34)
769         {
770             QstepX32 = 32;
771             q_rem = 4;
772         }
773         else
774         {
775             QstepX32 = 36;
776             q_rem = 5;
777         }
778 
779         return (q_per * 6 + q_rem);
780     }
781     else if (ct->m_nCodecType==REG_ENC_MODE_MPG4 || ct->m_nCodecType==REG_ENC_MODE_H263)
782     {
783         if( QstepX32 <= ct->m_nMinQStep)
784             return ct->m_nMinQP;
785         else if (QstepX32 > ct->m_nMaxQStep)
786             return ct->m_nMaxQP;
787 
788         return QstepX32>>QS_SHIFT_FACTOR;
789     }
790 
791     return 0;   // Should never entering this.
792 }
793 
794 #ifdef _SUPPORT_MBLEVEL_RC_
795 
796 #define DUMP_FRAME_NO -1 //140
797 // Each MB must call this routine once
cvbr_InitMB(CVBRRateControl * ct,int nVar,const int nPrevQP,const int nBits,int IsIntra,int IsP4MV,int BPredType,int nResetDQ)798 int cvbr_InitMB(CVBRRateControl* ct, int nVar, const int nPrevQP, const int nBits, int IsIntra, int IsP4MV, int BPredType, int nResetDQ)
799 {
800 #ifdef USE_INT_PREC
801 	int nAvgAct, nActj, nNBits=0;
802 #else
803 	float fAvgAct, fActj, fNBits;
804 #endif
805 	int QStep, RtnQP, nVariance;
806 //        int TgtQP;
807 	MFE_BOOL bChangeQP = 0;
808 	int nMBX, nMBY;
809 
810 #ifdef RAND_INPUT
811 	nVariance = nVar = rand()%128;
812 	//IsIntra = (rand()%4)==0 ? 1 : 0;
813 	//Is4MV = (rand()%4)==0 ? 1 : 0;
814 #else
815 	nVariance = nVar;
816 #endif
817 
818 //     if (ct->m_nFrameCount == DUMP_FRAME_NO)
819 //         printf("ct->m_nMBN = %d (MBX, MBY) = (%2d, %2d), nBits = %d\n", ct->m_nMBN, ct->m_nMBN%ct->m_nMbWidth, ct->m_nMBN/ct->m_nMbWidth, nBits);
820 
821 // 	if (ct->m_rcGranularity==FRAMELEVELRC) {
822 // 		return rcQstep2QP(ct->m_nFrameQP);
823 // 	}
824 
825 	if (ct->m_nMBN==0) { // Initialization
826 		ct->m_nSumAct = 0;
827 		ct->m_nTargetUsedBits = 0;
828 	}
829 
830 	if (ct->m_nMBN>0)
831 	{ // Previous MB updating: Last MB is not counted!
832 		// Update QP
833 		ct->m_nPrevTopQP[(ct->m_nMBN-1)%ct->m_nMbWidth] = nPrevQP;
834 		ct->m_nLastFrameAvgQP[ct->m_bIsBotField] += rcQP2Qstep(ct, nPrevQP);
835 
836 		// SW simulation hw pipeline: Update bit usage history
837 		if (ct->m_nMBN<3)
838 			ct->m_nUsedBits[ct->m_nMBN-1] = nBits;
839 		else {
840 			ct->m_nUsedBits[0] = ct->m_nUsedBits[1];
841 			ct->m_nUsedBits[1] = nBits;
842 		}
843 	}
844 
845 	if (ct->m_nMBN>1)	// HW pipeline: See below nNBits (or fNBits) calculation
846 		ct->m_nTargetUsedBits += ct->m_nTargetMbBits;
847 
848 	// Update history
849 	if (nVariance==0) nVariance = 1;
850 	ct->m_nSumAct += nVariance;
851 
852 	// QP calculation
853 	ct->m_nNewPacket = 0; // Default
854 	if (ct->m_nMBN<2) {
855 		RtnQP = rcQstep2QP(ct, ct->m_nFrameQP);
856 	}
857 	else
858 	{
859 		if (ct->m_nCodecType==REG_ENC_MODE_MPG4 && (!IsIntra) && ((ct->m_nFrameType==P_VOP&&IsP4MV)||(ct->m_nFrameType==B_VOP&&BPredType==0))) {
860 			RtnQP = nPrevQP;	// Not allowing DQ!=0
861 		}
862 		else {
863 #ifdef USE_INT_PREC
864 			nNBits = (ct->m_nUsedBits[0]<<SCALE_BITS) / ct->m_nTargetUsedBits;
865 			//MFE_ASSERT(nNBits<(1<<(SCALE_BITS+6)));
866 			if (nNBits>=(1<<(SCALE_BITS+6)))
867 				nNBits = (1<<(SCALE_BITS+6)) - 1;
868 			nAvgAct = ct->m_nSumAct / (ct->m_nMBN+1);
869 			nActj = (((nVariance<<1) + nAvgAct) << SCALE_ACT) / (nVariance + (nAvgAct<<1));
870 			// Target QStep
871 			if (ct->m_nFrameType==I_VOP)
872 				QStep = (int)(((MFE_S64)ct->m_nFrameQP * nActj) >> SCALE_ACT);
873 			else
874 				QStep = (int)(((MFE_S64)ct->m_nFrameQP * nActj * nNBits) >> (SCALE_ACT+SCALE_BITS));
875 #else
876 			fNBits = (float)ct->m_nUsedBits[0] / ct->m_nTargetUsedBits;
877 			fAvgAct = (float)ct->m_nSumAct / (ct->m_nMBN+1);
878 			fActj = ((nVariance*MBACT_NORMALIZATION_FACTOR) + fAvgAct) / (nVariance + (fAvgAct*MBACT_NORMALIZATION_FACTOR));
879 			// Target QStep
880 			if (ct->m_nFrameType==I_VOP)
881 				QStep = (int)(ct->m_nFrameQP * fActj);
882 			else
883 				QStep = (int)(ct->m_nFrameQP * fActj * fNBits);
884 #endif
885 			// 		if (QStep<(1<<QS_SHIFT_FACTOR))
886 			// 			QStep = (1<<QS_SHIFT_FACTOR);
887 			MFE_ASSERT(QStep>=0 && QStep<(1<<20));
888 
889 			// Target QP
890 			RtnQP = rcQstep2QP(ct, QStep);
891 			// Refinement: Phase 1, top and left MB-QP limitation
892 			if (ct->m_nMBN >= ct->m_nMbWidth) {
893 				if (RtnQP > ct->m_nPrevTopQP[ct->m_nMBN%ct->m_nMbWidth] + TOP_QP_DIFF_LIMIT) {
894 					RtnQP = ct->m_nPrevTopQP[ct->m_nMBN%ct->m_nMbWidth] + SPEC_QP_DIFF_LIMIT;
895 					bChangeQP = 1;
896 				}
897 				else if (RtnQP < ct->m_nPrevTopQP[ct->m_nMBN%ct->m_nMbWidth] - TOP_QP_DIFF_LIMIT) {
898 					RtnQP = ct->m_nPrevTopQP[ct->m_nMBN%ct->m_nMbWidth] - SPEC_QP_DIFF_LIMIT;
899 					bChangeQP = 1;
900 				}
901 			}
902 			if (RtnQP > nPrevQP + LEFT_QP_DIFF_LIMIT) {
903 				RtnQP = nPrevQP + SPEC_QP_DIFF_LIMIT;
904 				bChangeQP = 1;
905 			}
906 			else if (RtnQP < nPrevQP - LEFT_QP_DIFF_LIMIT) {
907 				RtnQP = nPrevQP - SPEC_QP_DIFF_LIMIT;
908 				bChangeQP = 1;
909 			}
910 			// Refinement: Phase 2, spec QP range limitation
911 			RtnQP = MSRC_MAX(ct->m_nMinQP, RtnQP);
912 			RtnQP = MSRC_MIN(ct->m_nMaxQP, RtnQP);
913 #if 0	// Don't need this because QP is bounded by rcQstep2QP(),
914 			// and if TOP_QP_DIFF_LIMIT and BOTTOM_QP_DIFF_LIMIT >=2, there is no way to have +-1.
915 			// Refinement: Phase 3, MPEG-4 B-frame limitation
916 			if (ct->m_nCodecType==REG_ENC_MODE_MPG4 && ct->m_nFrameType==B_VOP /*&& RtnQP!=nPrevQP*/) {
917 				if (RtnQP-nPrevQP==-1 || RtnQP-nPrevQP==1)
918 					RtnQP = nPrevQP;
919 			}
920 #endif
921 			// Avoid frequent QP changing
922 			if (!bChangeQP)
923 				RtnQP = nPrevQP; // Reset
924 		}
925 
926 		//DEBUG_RC(("  [CVBRRC] %d : NBits=%d, AvgAct=%d\n", ct->m_nMBN, (int)fNBits, (int)fAvgAct ));
927 
928 		//////////////////////////////////////////////////////////////////////////
929 		// er_en
930 		if (ct->m_nVPSize) {
931 			if (ct->m_nUsedBits[0]-ct->m_nLastVPBits>=ct->m_nVPSize) {
932 				if (ct->m_nVPMbRow) {
933 					nMBX = ct->m_nMBN%ct->m_nMbWidth;
934 					nMBY = ct->m_nMBN/ct->m_nMbWidth;
935 					if (nMBX==0 && nMBY>0 && (nMBY%ct->m_nVPMbRow)==0) {
936 						ct->m_nNewPacket = 1;
937 						ct->m_nLastVPBits = ct->m_nUsedBits[0];
938 					}
939 				}
940 				else {
941 					ct->m_nNewPacket = 1;
942 					ct->m_nLastVPBits = ct->m_nUsedBits[0];
943 				}
944 			}
945 		}
946 		else if (ct->m_nVPMbRow) {
947 			nMBX = ct->m_nMBN%ct->m_nMbWidth;
948 			nMBY = ct->m_nMBN/ct->m_nMbWidth;
949 			if (nMBX==0 && nMBY>0 && (nMBY%ct->m_nVPMbRow)==0) {
950 				ct->m_nNewPacket = 1;
951 				ct->m_nLastVPBits = ct->m_nUsedBits[0];
952 			}
953 		}
954 	}
955 
956 	if (ct->m_rcGranularity==FRAMELEVELRC) {
957 		RtnQP = rcQstep2QP(ct, ct->m_nFrameQP);
958 	}
959 
960 	ct->m_nMBN++;
961 	if (ct->m_rcMethod==CONST_QUALITY)
962 		return ct->m_nConstQP;
963 	MFE_ASSERT(RtnQP<=ct->m_nMaxQP && RtnQP>=ct->m_nMinQP);
964 	return RtnQP;
965 }
966 
967 #else	// _SUPPORT_MBLEVEL_RC_ not defined
968 
cvbr_InitMB(CVBRRateControl * ct,int nVar,const int nPrevQP,const int nBits,int IsIntra,int IsP4MV,int BPredType,int nResetDQ)969 int cvbr_InitMB(CVBRRateControl* ct, int nVar, const int nPrevQP, const int nBits, int IsIntra, int IsP4MV, int BPredType, int nResetDQ)
970 {
971 	if (ct->m_nMBN>0)
972 		ct->m_nLastFrameAvgQP[ct->m_bIsBotField] += rcQP2Qstep(nPrevQP);
973 	if (ct->m_rcMethod==CONST_QUALITY)
974 		return ct->m_nConstQP;
975 	return rcQstep2QP(ct->m_nFrameQP);
976 }
977 
978 #endif // _SUPPORT_MBLEVEL_RC_
979