1 
2 /*!
3  ***************************************************************************
4  * \file rc_quadratic.c
5  *
6  * \brief
7  *    Rate Control algorithm
8  *
9  * \author
10  *    Main contributors (see contributors.h for copyright, address and affiliation details)
11  *     - Siwei Ma             <swma@jdl.ac.cn>
12  *     - Zhengguo LI          <ezgli@lit.a-star.edu.sg>
13  *     - Athanasios Leontaris <aleon@dolby.com>
14  *
15  * \date
16  *   16 Jan. 2003
17  **************************************************************************
18  */
19 
20 #include <math.h>
21 #include <limits.h>
22 
23 #include "global.h"
24 #include "ratectl.h"
25 
26 
27 static const float THETA = 1.3636F;
28 static const float OMEGA = 0.9F;
29 static const float MINVALUE = 4.0F;
30 /*!
31  *************************************************************************************
32  * \brief
33  *    Dynamically allocate memory needed for rate control
34  *
35  *************************************************************************************
36  */
rc_alloc_quadratic(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic ** p_quad)37 void rc_alloc_quadratic( VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic **p_quad )
38 {
39   int rcBufSize = p_Vid->FrameSizeInMbs / p_Inp->basicunit;
40 
41   RCQuadratic *lprc;
42 
43   (*p_quad) = (RCQuadratic *) malloc ( sizeof( RCQuadratic ) );
44   if (NULL==(*p_quad))
45   {
46     no_mem_exit("rc_alloc_quadratic: (*p_quad)");
47   }
48   lprc = *p_quad;
49 
50   lprc->PreviousFrameMAD = 1.0;
51   lprc->CurrentFrameMAD = 1.0;
52   lprc->Pprev_bits = 0;
53   lprc->Target = 0;
54   lprc->TargetField = 0;
55   lprc->LowerBound = 0;
56   lprc->UpperBound1 = INT_MAX;
57   lprc->UpperBound2 = INT_MAX;
58   lprc->Wp = 0.0;
59   lprc->Wb = 0.0;
60   lprc->AveWb = 0.0;
61   lprc->PAveFrameQP   = p_Inp->qp[I_SLICE] + p_Vid->bitdepth_luma_qp_scale;
62   lprc->m_Qc          = lprc->PAveFrameQP;
63   lprc->FieldQPBuffer = lprc->PAveFrameQP;
64   lprc->FrameQPBuffer = lprc->PAveFrameQP;
65   lprc->PAverageQp    = lprc->PAveFrameQP;
66   lprc->MyInitialQp   = lprc->PAveFrameQP;
67   lprc->AveWb         = 0.0;
68 
69   lprc->BUPFMAD = (double*) calloc ((rcBufSize), sizeof (double));
70   if (NULL==lprc->BUPFMAD)
71   {
72     no_mem_exit("rc_alloc_quadratic: lprc->BUPFMAD");
73   }
74 
75   lprc->BUCFMAD = (double*) calloc ((rcBufSize), sizeof (double));
76   if (NULL==lprc->BUCFMAD)
77   {
78     no_mem_exit("rc_alloc_quadratic: lprc->BUCFMAD");
79   }
80 
81   lprc->FCBUCFMAD = (double*) calloc ((rcBufSize), sizeof (double));
82   if (NULL==lprc->FCBUCFMAD)
83   {
84     no_mem_exit("rc_alloc_quadratic: lprc->FCBUCFMAD");
85   }
86 
87   lprc->FCBUPFMAD = (double*) calloc ((rcBufSize), sizeof (double));
88   if (NULL==lprc->FCBUPFMAD)
89   {
90     no_mem_exit("rc_alloc_quadratic: lprc->FCBUPFMAD");
91   }
92 }
93 
94 /*!
95  *************************************************************************************
96  * \brief
97  *    Copy JVT rate control objects
98  *
99  *************************************************************************************
100  */
rc_copy_quadratic(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * dst,RCQuadratic * src)101 void rc_copy_quadratic( VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *dst, RCQuadratic *src )
102 {
103   int rcBufSize = p_Vid->FrameSizeInMbs / p_Inp->basicunit;
104   /* buffer original addresses for which memory has been allocated */
105   double   *tmpBUPFMAD = dst->BUPFMAD;
106   double   *tmpBUCFMAD = dst->BUCFMAD;
107   double *tmpFCBUPFMAD = dst->FCBUPFMAD;
108   double *tmpFCBUCFMAD = dst->FCBUCFMAD;
109 
110   /* copy object */
111   memcpy( (void *)dst, (void *)src, sizeof(RCQuadratic) );
112 
113   /* restore original addresses */
114   dst->BUPFMAD   = tmpBUPFMAD;
115   dst->BUCFMAD   = tmpBUCFMAD;
116   dst->FCBUPFMAD = tmpFCBUPFMAD;
117   dst->FCBUCFMAD = tmpFCBUCFMAD;
118 
119   /* copy MADs */
120   memcpy( (void *)dst->BUPFMAD,   (void *)src->BUPFMAD,   (rcBufSize) * sizeof (double) );
121   memcpy( (void *)dst->BUCFMAD,   (void *)src->BUCFMAD,   (rcBufSize) * sizeof (double) );
122   memcpy( (void *)dst->FCBUPFMAD, (void *)src->FCBUPFMAD, (rcBufSize) * sizeof (double) );
123   memcpy( (void *)dst->FCBUCFMAD, (void *)src->FCBUCFMAD, (rcBufSize) * sizeof (double) );
124 }
125 
126 /*!
127  *************************************************************************************
128  * \brief
129  *    Free memory needed for rate control
130  *
131  *************************************************************************************
132 */
rc_free_quadratic(RCQuadratic ** p_quad)133 void rc_free_quadratic(RCQuadratic **p_quad)
134 {
135   if (NULL!=(*p_quad)->BUPFMAD)
136   {
137     free ((*p_quad)->BUPFMAD);
138     (*p_quad)->BUPFMAD = NULL;
139   }
140   if (NULL!=(*p_quad)->BUCFMAD)
141   {
142     free ((*p_quad)->BUCFMAD);
143     (*p_quad)->BUCFMAD = NULL;
144   }
145   if (NULL!=(*p_quad)->FCBUCFMAD)
146   {
147     free ((*p_quad)->FCBUCFMAD);
148     (*p_quad)->FCBUCFMAD = NULL;
149   }
150   if (NULL!=(*p_quad)->FCBUPFMAD)
151   {
152     free ((*p_quad)->FCBUPFMAD);
153     (*p_quad)->FCBUPFMAD = NULL;
154   }
155   if (NULL!=(*p_quad))
156   {
157     free ((*p_quad));
158     (*p_quad) = NULL;
159   }
160 }
161 
162 
163 /*!
164  *************************************************************************************
165  * \brief
166  *    Initialize rate control parameters
167  *
168  *************************************************************************************
169 */
rc_init_seq(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,RCGeneric * p_gen)170 void rc_init_seq(VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, RCGeneric *p_gen)
171 {
172   double L1,L2,L3,bpp;
173   int qp, i;
174 
175   switch ( p_Inp->RCUpdateMode )
176   {
177   case RC_MODE_0:
178     p_Vid->updateQP = updateQPRC0;
179     break;
180   case RC_MODE_1:
181     p_Vid->updateQP = updateQPRC1;
182     break;
183   case RC_MODE_2:
184     p_Vid->updateQP = updateQPRC2;
185     break;
186   case RC_MODE_3:
187     p_Vid->updateQP = updateQPRC3;
188     break;
189   default:
190     p_Vid->updateQP = updateQPRC0;
191     break;
192   }
193   // set function pointers
194   p_Vid->rc_update_pict_frame_ptr = rc_update_pict_frame;
195   p_Vid->rc_update_picture_ptr    = rc_update_picture;
196   p_Vid->rc_init_pict_ptr         = rc_init_pict;
197 
198   p_quad->Xp=0;
199   p_quad->Xb=0;
200 
201   p_quad->bit_rate = (float) p_Inp->bit_rate;
202   p_quad->frame_rate = p_Vid->framerate;
203   p_quad->PrevBitRate = p_quad->bit_rate;
204 
205   /*compute the total number of MBs in a frame*/
206   if(p_Inp->basicunit > p_Vid->FrameSizeInMbs)
207     p_Inp->basicunit = p_Vid->FrameSizeInMbs;
208   if(p_Inp->basicunit < p_Vid->FrameSizeInMbs)
209     p_quad->TotalNumberofBasicUnit = p_Vid->FrameSizeInMbs/p_Inp->basicunit;
210   else
211     p_quad->TotalNumberofBasicUnit = 1;
212 
213   /*initialize the parameters of fluid flow traffic model*/
214   p_gen->CurrentBufferFullness = 0;
215   p_quad->GOPTargetBufferLevel = (double) p_gen->CurrentBufferFullness;
216 
217   /*initialize the previous window size*/
218   p_quad->m_windowSize    = 0;
219   p_quad->MADm_windowSize = 0;
220   p_gen->NumberofCodedBFrame = 0;
221   p_quad->NumberofCodedPFrame = 0;
222   p_gen->NumberofGOP         = 0;
223   /*remaining # of bits in GOP */
224   p_gen->RemainingBits = 0;
225   /*control parameter */
226   if(p_Inp->NumberBFrames>0)
227   {
228     p_quad->GAMMAP=0.25;
229     p_quad->BETAP=0.9;
230   }
231   else
232   {
233     p_quad->GAMMAP=0.5;
234     p_quad->BETAP=0.5;
235   }
236 
237   /*quadratic rate-distortion model*/
238   p_quad->PPreHeader=0;
239 
240   p_quad->Pm_X1 = p_quad->bit_rate * 1.0;
241   p_quad->Pm_X2 = 0.0;
242   /* linear prediction model for P picture*/
243   p_quad->PMADPictureC1 = 1.0;
244   p_quad->PMADPictureC2 = 0.0;
245 
246   // Initialize values
247   for(i=0;i<21;i++)
248   {
249     p_quad->Pm_rgQp[i] = 0;
250     p_quad->Pm_rgRp[i] = 0.0;
251     p_quad->PPictureMAD[i] = 0.0;
252   }
253 
254   //Define the largest variation of quantization parameters
255   p_quad->PMaxQpChange = p_Inp->RCMaxQPChange;
256 
257   /*basic unit layer rate control*/
258   p_quad->PAveHeaderBits1 = 0;
259   p_quad->PAveHeaderBits3 = 0;
260   p_quad->DDquant = (p_quad->TotalNumberofBasicUnit>=9 ? 1 : 2);
261 
262   p_quad->MBPerRow = p_Vid->PicWidthInMbs;
263 
264   /*adaptive field/frame coding*/
265   p_gen->FieldControl=0;
266 
267   if (p_Inp->SeinitialQP==0)
268   {
269     /*compute the initial QP*/
270     bpp = 1.0*p_quad->bit_rate /(p_quad->frame_rate*p_Vid->size);
271 
272     if (p_Vid->width == 176)
273     {
274       L1 = 0.1;
275       L2 = 0.3;
276       L3 = 0.6;
277     }
278     else if (p_Vid->width == 352)
279     {
280       L1 = 0.2;
281       L2 = 0.6;
282       L3 = 1.2;
283     }
284     else
285     {
286       L1 = 0.6;
287       L2 = 1.4;
288       L3 = 2.4;
289     }
290     if (bpp<= L1)
291       qp = 35;
292     else if(bpp<=L2)
293       qp = 25;
294     else if(bpp<=L3)
295       qp = 20;
296     else
297       qp = 10;
298     p_Inp->SeinitialQP = qp;
299   }
300 
301   // high bit-depth
302   p_quad->bitdepth_qp_scale = p_Vid->bitdepth_luma_qp_scale;
303 }
304 
305 /*!
306  *************************************************************************************
307  * \brief
308  *    Initialize one GOP
309  *
310  *************************************************************************************
311 */
rc_init_GOP(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,RCGeneric * p_gen,int np,int nb)312 void rc_init_GOP(VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, RCGeneric *p_gen, int np, int nb)
313 {
314   //int OverBits;
315   int GOPDquant;
316   int64 AllocatedBits;
317 
318   // bit allocation for RC_MODE_3
319   switch( p_Inp->RCUpdateMode )
320   {
321   case RC_MODE_3:
322     {
323       int sum = 0, tmp, level, levels = 0, num_frames[RC_MAX_TEMPORAL_LEVELS];
324       float numer, denom;
325       int gop = p_Inp->NumberBFrames + 1;
326       int i_period = p_Inp->intra_period == 0 ? p_Inp->idr_period : (p_Inp->idr_period == 0 ? p_Inp->intra_period : imin(p_Inp->intra_period, p_Inp->idr_period) );
327 
328       memset( num_frames, 0, RC_MAX_TEMPORAL_LEVELS * sizeof(int) );
329       // are there any B frames?
330       if ( p_Inp->NumberBFrames )
331       {
332         if ( p_Inp->HierarchicalCoding == 1 ) // two layers: even/odd
333         {
334           levels = 2;
335           num_frames[0] = p_Inp->NumberBFrames >> 1;
336           num_frames[1] = (p_Inp->NumberBFrames - num_frames[0]) >= 0 ? (p_Inp->NumberBFrames - num_frames[0]) : 0;
337         }
338         else if ( p_Inp->HierarchicalCoding == 2 ) // binary hierarchical structure
339         {
340           // check if gop is power of two
341           tmp = gop;
342           while ( tmp )
343           {
344             sum += tmp & 1;
345             tmp >>= 1;
346           }
347           assert( sum == 1 );
348 
349           // determine number of levels
350           levels = 0;
351           tmp = gop;
352           while ( tmp > 1 )
353           {
354             tmp >>= 1; // divide by 2
355             num_frames[levels] = 1 << levels;
356             levels++;
357           }
358           assert( levels >= 1 && levels <= RC_MAX_TEMPORAL_LEVELS );
359         }
360         else if ( p_Inp->HierarchicalCoding == 3 )
361         {
362           fprintf(stderr, "\n RCUpdateMode=3 and HierarchicalCoding == 3 are currently not supported"); // This error message should be moved elsewhere and have proper memory deallocation
363           exit(1);
364         }
365         else // all frames of the same priority - level
366         {
367           levels = 1;
368           num_frames[0] = p_Inp->NumberBFrames;
369         }
370         p_gen->temporal_levels = levels;
371       }
372       else
373       {
374         for ( level = 0; level < RC_MAX_TEMPORAL_LEVELS; level++ )
375         {
376           p_Inp->RCBSliceBitRatio[level] = 0.0F;
377         }
378         p_gen->temporal_levels = 0;
379       }
380       // calculate allocated bits for each type of frame
381       numer = (float)(( (!i_period ? 1 : i_period) * gop) * ((double)p_Inp->bit_rate / p_Inp->source.frame_rate));
382       denom = 0.0F;
383 
384       for ( level = 0; level < levels; level++ )
385       {
386         denom += (float)(num_frames[level] * p_Inp->RCBSliceBitRatio[level]);
387         p_gen->hierNb[level] = num_frames[level] * np;
388       }
389       denom += 1.0F;
390       if ( i_period >= 1 )
391       {
392         denom *= (float)i_period;
393         denom += (float)p_Inp->RCISliceBitRatio - 1.0F;
394       }
395 
396       // set bit targets for each type of frame
397       p_gen->RCPSliceBits = (int) floor( numer / denom + 0.5F );
398       p_gen->RCISliceBits = i_period ? (int)(p_Inp->RCISliceBitRatio * p_gen->RCPSliceBits + 0.5) : 0;
399 
400       for ( level = 0; level < levels; level++ )
401       {
402         p_gen->RCBSliceBits[level] = (int)floor(p_Inp->RCBSliceBitRatio[level] * p_gen->RCPSliceBits + 0.5);
403       }
404 
405       p_gen->NISlice = i_period ? ( p_Inp->no_frames / i_period ) : 0;
406       p_gen->NPSlice = (p_Inp->no_frames / (1 + p_Inp->NumberBFrames)) - p_gen->NISlice; // approximate but good enough for sufficient number of frames
407     }
408     break;
409   default:
410     break;
411   }
412 
413   /* check if the last GOP over uses its budget. If yes, the initial QP of the I frame in
414   the coming  GOP will be increased.*/
415 
416   //OverBits=-(int)(p_gen->RemainingBits);
417 
418   /*initialize the lower bound and the upper bound for the target bits of each frame, HRD consideration*/
419   p_quad->LowerBound  = (int)(p_gen->RemainingBits + p_quad->bit_rate / p_quad->frame_rate);
420   p_quad->UpperBound1 = (int)(p_gen->RemainingBits + (p_quad->bit_rate * 2.048));
421 
422   /*compute the total number of bits for the current GOP*/
423   AllocatedBits = (int64) floor((1 + np + nb) * p_quad->bit_rate / p_quad->frame_rate + 0.5);
424   p_gen->RemainingBits += AllocatedBits;
425   p_quad->Np = np;
426   p_quad->Nb = nb;
427 
428   p_quad->GOPOverdue=FALSE;
429 
430   /*field coding*/
431   //p_gen->NoGranularFieldRC = ( p_Inp->PicInterlace || !p_Inp->MbInterlace || p_Inp->basicunit != p_Vid->FrameSizeInMbs );
432   if ( !p_Inp->PicInterlace && p_Inp->MbInterlace && p_Inp->basicunit == p_Vid->FrameSizeInMbs )
433     p_gen->NoGranularFieldRC = 0;
434   else
435     p_gen->NoGranularFieldRC = 1;
436 
437   /*Compute InitialQp for each GOP*/
438   p_quad->TotalPFrame=np;
439   p_gen->NumberofGOP++;
440   if(p_gen->NumberofGOP==1)
441   {
442     p_quad->MyInitialQp = p_Inp->SeinitialQP + p_quad->bitdepth_qp_scale;
443     p_quad->CurrLastQP = p_quad->MyInitialQp - 1; //recent change -0;
444     p_quad->QPLastGOP   = p_quad->MyInitialQp;
445 
446     p_quad->PAveFrameQP   = p_quad->MyInitialQp;
447     p_quad->m_Qc          = p_quad->PAveFrameQP;
448     p_quad->FieldQPBuffer = p_quad->PAveFrameQP;
449     p_quad->FrameQPBuffer = p_quad->PAveFrameQP;
450     p_quad->PAverageQp    = p_quad->PAveFrameQP;
451   }
452   else
453   {
454     /*adaptive field/frame coding*/
455     if( p_Inp->PicInterlace == ADAPTIVE_CODING || p_Inp->MbInterlace )
456     {
457       if (p_gen->FieldFrame == 1)
458       {
459         p_quad->TotalQpforPPicture += p_quad->FrameQPBuffer;
460         p_quad->QPLastPFrame = p_quad->FrameQPBuffer;
461       }
462       else
463       {
464         p_quad->TotalQpforPPicture += p_quad->FieldQPBuffer;
465         p_quad->QPLastPFrame = p_quad->FieldQPBuffer;
466       }
467     }
468     /*compute the average QP of P frames in the previous GOP*/
469     p_quad->PAverageQp=(int)(1.0 * p_quad->TotalQpforPPicture / p_quad->NumberofPPicture+0.5);
470 
471     GOPDquant=(int)((1.0*(np+nb+1)/15.0) + 0.5);
472     if(GOPDquant>2)
473       GOPDquant=2;
474 
475     p_quad->PAverageQp -= GOPDquant;
476 
477     if (p_quad->PAverageQp > (p_quad->QPLastPFrame - 2))
478       p_quad->PAverageQp--;
479 
480     // QP is constrained by QP of previous GOP
481     p_quad->PAverageQp = iClip3(p_quad->QPLastGOP - 2, p_quad->QPLastGOP + 2, p_quad->PAverageQp);
482     // Also clipped within range.
483     p_quad->PAverageQp = iClip3(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale,  p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale,  p_quad->PAverageQp);
484 
485     p_quad->MyInitialQp = p_quad->PAverageQp;
486     p_quad->Pm_Qp       = p_quad->PAverageQp;
487     p_quad->PAveFrameQP = p_quad->PAverageQp;
488     p_quad->QPLastGOP   = p_quad->MyInitialQp;
489     p_quad->PrevLastQP = p_quad->CurrLastQP;
490     p_quad->CurrLastQP = p_quad->MyInitialQp - 1;
491   }
492 
493   p_quad->TotalQpforPPicture=0;
494   p_quad->NumberofPPicture=0;
495   p_quad->NumberofBFrames=0;
496 }
497 
498 
499 /*!
500  *************************************************************************************
501  * \brief
502  *    Initialize one picture
503  *
504  *************************************************************************************
505 */
rc_init_pict(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,RCGeneric * p_gen,int fieldpic,int topfield,int targetcomputation,float mult)506 void rc_init_pict(VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, RCGeneric *p_gen, int fieldpic,int topfield,int targetcomputation, float mult)
507 {
508   int tmp_T;
509 
510   /* compute the total number of basic units in a frame */
511   if(p_Inp->MbInterlace)
512     p_quad->TotalNumberofBasicUnit = p_Vid->FrameSizeInMbs / p_Vid->BasicUnit;
513   else
514     p_quad->TotalNumberofBasicUnit = p_Vid->FrameSizeInMbs / p_Inp->basicunit;
515 
516   p_Vid->NumberofCodedMacroBlocks = 0;
517 
518   /* Normally, the bandwidth for the VBR case is estimated by
519      a congestion control algorithm. A bandwidth curve can be predefined if we only want to
520      test the proposed algorithm */
521   if(p_Inp->channel_type==1)
522   {
523     if(p_quad->NumberofCodedPFrame==58)
524       p_quad->bit_rate *= 1.5;
525     else if(p_quad->NumberofCodedPFrame==59)
526       p_quad->PrevBitRate = p_quad->bit_rate;
527   }
528 
529   /* predefine a target buffer level for each frame */
530   if((fieldpic||topfield) && targetcomputation)
531   {
532     if ( p_Vid->type == P_SLICE || (p_Inp->RCUpdateMode == RC_MODE_1 && (p_Vid->number !=0)) )
533     {
534       /* Since the available bandwidth may vary at any time, the total number of
535       bits is updated picture by picture*/
536       if(p_quad->PrevBitRate!=p_quad->bit_rate)
537         p_gen->RemainingBits +=(int) floor((p_quad->bit_rate-p_quad->PrevBitRate)*(p_quad->Np + p_quad->Nb)/p_quad->frame_rate+0.5);
538 
539       /* predefine the  target buffer level for each picture.
540       frame layer rate control */
541       if(p_Vid->BasicUnit == p_Vid->FrameSizeInMbs)
542       {
543         if(p_quad->NumberofPPicture==1)
544         {
545           p_quad->TargetBufferLevel = (double) p_gen->CurrentBufferFullness;
546           p_quad->DeltaP = (p_gen->CurrentBufferFullness - p_quad->GOPTargetBufferLevel) / (p_quad->TotalPFrame-1);
547           p_quad->TargetBufferLevel -= p_quad->DeltaP;
548         }
549         else if(p_quad->NumberofPPicture>1)
550           p_quad->TargetBufferLevel -= p_quad->DeltaP;
551       }
552       /* basic unit layer rate control */
553       else
554       {
555         if(p_quad->NumberofCodedPFrame>0)
556         {
557           /* adaptive frame/field coding */
558           if(((p_Inp->PicInterlace==ADAPTIVE_CODING)||(p_Inp->MbInterlace))&&(p_gen->FieldControl==1))
559             memcpy((void *)p_quad->FCBUPFMAD,(void *)p_quad->FCBUCFMAD, p_quad->TotalNumberofBasicUnit * sizeof(double));
560           else
561             memcpy((void *)p_quad->BUPFMAD,(void *)p_quad->BUCFMAD, p_quad->TotalNumberofBasicUnit * sizeof(double));
562         }
563 
564         if(p_gen->NumberofGOP==1)
565         {
566           if(p_quad->NumberofPPicture==1)
567           {
568             p_quad->TargetBufferLevel = (double) p_gen->CurrentBufferFullness;
569             p_quad->DeltaP = (p_gen->CurrentBufferFullness - p_quad->GOPTargetBufferLevel)/(p_quad->TotalPFrame - 1);
570             p_quad->TargetBufferLevel -= p_quad->DeltaP;
571           }
572           else if(p_quad->NumberofPPicture>1)
573             p_quad->TargetBufferLevel -= p_quad->DeltaP;
574         }
575         else if(p_gen->NumberofGOP>1)
576         {
577           if(p_quad->NumberofPPicture==0)
578           {
579             p_quad->TargetBufferLevel = (double) p_gen->CurrentBufferFullness;
580             p_quad->DeltaP = (p_gen->CurrentBufferFullness - p_quad->GOPTargetBufferLevel) / p_quad->TotalPFrame;
581             p_quad->TargetBufferLevel -= p_quad->DeltaP;
582           }
583           else if(p_quad->NumberofPPicture>0)
584             p_quad->TargetBufferLevel -= p_quad->DeltaP;
585         }
586       }
587 
588       if(p_quad->NumberofCodedPFrame==1)
589         p_quad->AveWp = p_quad->Wp;
590 
591       if((p_quad->NumberofCodedPFrame<8)&&(p_quad->NumberofCodedPFrame>1))
592         p_quad->AveWp = (p_quad->AveWp + p_quad->Wp * (p_quad->NumberofCodedPFrame-1))/p_quad->NumberofCodedPFrame;
593       else if(p_quad->NumberofCodedPFrame>1)
594         p_quad->AveWp = (p_quad->Wp + 7 * p_quad->AveWp) / 8;
595 
596       // compute the average complexity of B frames
597       if(p_Inp->NumberBFrames>0)
598       {
599         // compute the target buffer level
600         p_quad->TargetBufferLevel += (p_quad->AveWp * (p_Inp->NumberBFrames + 1)*p_quad->bit_rate\
601           /(p_quad->frame_rate*(p_quad->AveWp+p_quad->AveWb*p_Inp->NumberBFrames))-p_quad->bit_rate/p_quad->frame_rate);
602       }
603     }
604     else if ( p_Vid->type == B_SLICE )
605     {
606       /* update the total number of bits if the bandwidth is changed*/
607       if(p_quad->PrevBitRate != p_quad->bit_rate)
608         p_gen->RemainingBits +=(int) floor((p_quad->bit_rate-p_quad->PrevBitRate) * (p_quad->Np + p_quad->Nb) / p_quad->frame_rate+0.5);
609       if(p_gen->NumberofCodedBFrame == 1)
610       {
611         if(p_quad->NumberofCodedPFrame == 1)
612         {
613           p_quad->AveWp = p_quad->Wp;
614         }
615         p_quad->AveWb = p_quad->Wb;
616       }
617       else if(p_gen->NumberofCodedBFrame > 1)
618       {
619         //compute the average weight
620         if(p_gen->NumberofCodedBFrame<8)
621           p_quad->AveWb = (p_quad->AveWb + p_quad->Wb*(p_gen->NumberofCodedBFrame-1)) / p_gen->NumberofCodedBFrame;
622         else
623           p_quad->AveWb = (p_quad->Wb + 7 * p_quad->AveWb) / 8;
624       }
625     }
626     /* Compute the target bit for each frame */
627     if( p_Vid->type == P_SLICE || ( (p_Vid->number != 0) && (p_Inp->RCUpdateMode == RC_MODE_1 || p_Inp->RCUpdateMode == RC_MODE_3 ) ) )
628     {
629       /* frame layer rate control */
630       if(p_Vid->BasicUnit == p_Vid->FrameSizeInMbs || (p_Inp->RCUpdateMode == RC_MODE_3) )
631       {
632         if(p_quad->NumberofCodedPFrame>0)
633         {
634           if (p_Inp->RCUpdateMode == RC_MODE_3)
635           {
636             int level_idx = (p_Vid->type == B_SLICE && p_Inp->HierarchicalCoding) ? (p_Vid->p_curr_frm_struct->layer - 1) : 0;
637             int bitrate = (p_Vid->type == B_SLICE) ? p_gen->RCBSliceBits[ level_idx ]
638             : ( p_Vid->type == P_SLICE ? p_gen->RCPSliceBits : p_gen->RCISliceBits );
639             int level, denom = p_gen->NISlice * p_gen->RCISliceBits + p_gen->NPSlice * p_gen->RCPSliceBits;
640 
641             if ( p_Inp->HierarchicalCoding )
642             {
643               for ( level = 0; level < p_gen->temporal_levels; level++ )
644                 denom += p_gen->hierNb[ level ] * p_gen->RCBSliceBits[ level ];
645             }
646             else
647             {
648               denom += p_gen->hierNb[0] * p_gen->RCBSliceBits[0];
649             }
650             // target due to remaining bits
651             p_quad->Target = (int) floor( (float)(1.0 * bitrate * p_gen->RemainingBits) / (float)denom + 0.5F );
652             // target given original taget rate and buffer considerations
653             tmp_T  = imax(0, (int) floor( (double)bitrate - p_quad->GAMMAP * (p_gen->CurrentBufferFullness-p_quad->TargetBufferLevel) + 0.5) );
654             // translate Target rate from B or I "domain" to P domain since the P RC model is going to be used to select the QP
655             // for hierarchical coding adjust the target QP to account for different temporal levels
656             switch( p_Vid->type )
657             {
658             case B_SLICE:
659               p_quad->Target = (int) floor( (float)p_quad->Target / p_Inp->RCBoverPRatio + 0.5F);
660               break;
661             case I_SLICE:
662               p_quad->Target = (int) floor( (float)p_quad->Target / (p_Inp->RCIoverPRatio * 4.0) + 0.5F); // 4x accounts for the fact that header bits reduce the percentage of texture
663               break;
664             case P_SLICE:
665             default:
666               break;
667             }
668           }
669           else
670           {
671             p_quad->Target = (int) floor( p_quad->Wp * p_gen->RemainingBits / (p_quad->Np * p_quad->Wp + p_quad->Nb * p_quad->Wb) + 0.5);
672             tmp_T  = imax(0, (int) floor(p_quad->bit_rate / p_quad->frame_rate - p_quad->GAMMAP * (p_gen->CurrentBufferFullness-p_quad->TargetBufferLevel) + 0.5));
673             p_quad->Target = (int) floor(p_quad->BETAP * (p_quad->Target - tmp_T) + tmp_T + 0.5);
674           }
675         }
676       }
677       /* basic unit layer rate control */
678       else
679       {
680         if(((p_gen->NumberofGOP == 1)&&(p_quad->NumberofCodedPFrame>0))
681           || (p_gen->NumberofGOP > 1))
682         {
683           p_quad->Target = (int) (floor( p_quad->Wp * p_gen->RemainingBits / (p_quad->Np * p_quad->Wp + p_quad->Nb * p_quad->Wb) + 0.5));
684           tmp_T  = imax(0, (int) (floor(p_quad->bit_rate / p_quad->frame_rate - p_quad->GAMMAP * (p_gen->CurrentBufferFullness-p_quad->TargetBufferLevel) + 0.5)));
685           p_quad->Target = (int) (floor(p_quad->BETAP * (p_quad->Target - tmp_T) + tmp_T + 0.5));
686         }
687       }
688       p_quad->Target = (int)(mult * p_quad->Target);
689 
690       /* HRD consideration */
691       if ( p_Inp->RCUpdateMode != RC_MODE_3 || p_Vid->type == P_SLICE )
692         p_quad->Target = iClip3(p_quad->LowerBound, p_quad->UpperBound2, p_quad->Target);
693       if((topfield) || (fieldpic && ((p_Inp->PicInterlace==ADAPTIVE_CODING)||(p_Inp->MbInterlace))))
694         p_quad->TargetField=p_quad->Target;
695     }
696   }
697 
698   if(fieldpic || topfield)
699   {
700     /* frame layer rate control */
701     p_gen->NumberofHeaderBits  = 0;
702     p_gen->NumberofTextureBits = 0;
703 
704     /* basic unit layer rate control */
705     if(p_Vid->BasicUnit < p_Vid->FrameSizeInMbs)
706     {
707       p_quad->TotalFrameQP = 0;
708       p_gen->NumberofBasicUnitHeaderBits  = 0;
709       p_gen->NumberofBasicUnitTextureBits = 0;
710       p_gen->TotalMADBasicUnit = 0;
711       if(p_gen->FieldControl==0)
712         p_quad->NumberofBasicUnit = p_quad->TotalNumberofBasicUnit;
713       else
714         p_quad->NumberofBasicUnit = p_quad->TotalNumberofBasicUnit >> 1;
715     }
716   }
717 
718   if( ( p_Vid->type==P_SLICE || (p_Inp->RCUpdateMode == RC_MODE_1 && (p_Vid->number != 0)) ) && p_Vid->BasicUnit < p_Vid->FrameSizeInMbs && p_gen->FieldControl == 1 )
719   {
720     /* top field at basic unit layer rate control */
721     if(topfield)
722     {
723       p_quad->bits_topfield=0;
724       p_quad->Target=(int)(p_quad->TargetField*0.6);
725     }
726     /* bottom field at basic unit layer rate control */
727     else
728     {
729       p_quad->Target=p_quad->TargetField-p_quad->bits_topfield;
730       p_gen->NumberofBasicUnitHeaderBits=0;
731       p_gen->NumberofBasicUnitTextureBits=0;
732       p_gen->TotalMADBasicUnit=0;
733       p_quad->NumberofBasicUnit=p_quad->TotalNumberofBasicUnit >> 1;
734     }
735   }
736 }
737 
738 /*!
739  *************************************************************************************
740  * \brief
741  *    update one picture after frame/field encoding
742  *
743  * \param p_Vid
744  *    Image encoding parameters for picture
745  * \param p_Inp
746  *    Input configuration parameters
747  * \param p_quad
748  *    quadratic model
749  * \param p_gen
750  *    generic rate control parameters
751  * \param nbits
752  *    number of bits used for picture
753  *
754  *************************************************************************************
755 */
rc_update_pict(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,RCGeneric * p_gen,int nbits)756 void rc_update_pict(VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, RCGeneric *p_gen, int nbits)
757 {
758   int delta_bits = (nbits - (int)floor(p_quad->bit_rate / p_quad->frame_rate + 0.5F) );
759   // remaining # of bits in GOP
760   p_gen->RemainingBits -= nbits;
761   p_gen->CurrentBufferFullness += delta_bits;
762 
763   // update the lower bound and the upper bound for the target bits of each frame, HRD consideration
764   p_quad->LowerBound  -= (int) delta_bits;
765   p_quad->UpperBound1 -= (int) delta_bits;
766   p_quad->UpperBound2  = (int)(OMEGA * p_quad->UpperBound1);
767 
768   // update the parameters of quadratic R-D model
769   if( p_Vid->type==P_SLICE || (p_Inp->RCUpdateMode == RC_MODE_1 && p_Vid->curr_frm_idx) )
770   {
771     updateRCModel(p_Vid, p_Inp, p_quad, p_gen);
772     if ( p_Inp->RCUpdateMode == RC_MODE_3 )
773       p_quad->PreviousWholeFrameMAD = ComputeFrameMAD(p_Vid);
774   }
775 }
776 
777 /*!
778  *************************************************************************************
779  * \brief
780  *    update one picture after coding
781  *
782  * \param p_Vid
783  *    video parameters for current picture
784  * \param p_Inp
785  *    input parameters from configuration
786  * \param bits
787  *    number of bits used for picture
788  *
789  *************************************************************************************
790 */
791 
rc_update_picture(VideoParameters * p_Vid,InputParameters * p_Inp,int bits)792 void rc_update_picture( VideoParameters *p_Vid, InputParameters *p_Inp, int bits )
793 {
794   rc_update_pict(p_Vid, p_Inp, p_Vid->p_rc_quad, p_Vid->p_rc_gen, bits);
795 }
796 
updateComplexity(VideoParameters * p_Vid,RCQuadratic * p_quad,RCGeneric * p_gen,Boolean is_updated,int nbits)797 int updateComplexity( VideoParameters *p_Vid, RCQuadratic *p_quad, RCGeneric *p_gen, Boolean is_updated, int nbits )
798 {
799   double Avem_Qc;
800 
801   /* frame layer rate control */
802   if(p_Vid->BasicUnit == p_Vid->FrameSizeInMbs)
803     return ((int) floor(nbits * p_quad->m_Qc + 0.5));
804   /* basic unit layer rate control */
805   else
806   {
807     if( is_updated )
808     {
809       if( p_gen->NoGranularFieldRC == 0 || p_gen->FieldControl == 0 )
810       {
811         Avem_Qc = (double)p_quad->TotalFrameQP / (double)p_quad->TotalNumberofBasicUnit;
812         return ((int)floor(nbits * Avem_Qc + 0.5));
813       }
814     }
815     else if( p_Vid->type == B_SLICE )
816       return ((int) floor(nbits * p_quad->m_Qc + 0.5));
817   }
818   return 0;
819 }
820 
updatePparams(RCQuadratic * p_quad,RCGeneric * p_gen,int complexity)821 void updatePparams( RCQuadratic *p_quad, RCGeneric *p_gen, int complexity )
822 {
823   p_quad->Xp = complexity;
824   p_quad->Np--;
825   p_quad->Wp = p_quad->Xp;
826   p_quad->Pm_Hp = p_gen->NumberofHeaderBits;
827   p_quad->NumberofCodedPFrame++;
828   p_quad->NumberofPPicture++;
829 }
830 
updateBparams(RCQuadratic * p_quad,RCGeneric * p_gen,int complexity)831 void updateBparams( RCQuadratic *p_quad, RCGeneric *p_gen, int complexity )
832 {
833   p_quad->Xb = complexity;
834   p_quad->Nb--;
835   p_quad->Wb = p_quad->Xb / THETA;
836   p_quad->NumberofBFrames++;
837   p_gen->NumberofCodedBFrame++;
838 }
839 
840 /*!
841  *************************************************************************************
842  * \brief
843  *    update after frame encoding
844  * \param p_Vid
845  *    Image encoding parameters for picture
846  * \param p_Inp
847  *    Input configuration parameters
848  * \param p_quad
849  *    quadratic model
850  * \param p_gen
851  *    generic rate control parameters
852  * \param nbits
853  *    number of bits used for frame
854  *
855  *************************************************************************************
856 */
rc_update_pict_frame(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,RCGeneric * p_gen,int nbits)857 void rc_update_pict_frame(VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, RCGeneric *p_gen, int nbits)
858 {
859   /* update the complexity weight of I, P, B frame */
860   int complexity = 0;
861 
862   switch( p_Inp->RCUpdateMode )
863   {
864   case RC_MODE_0:
865   case RC_MODE_2:
866   default:
867     complexity = updateComplexity( p_Vid, p_quad, p_gen, (Boolean) (p_Vid->type == P_SLICE), nbits );
868     if ( p_Vid->type == P_SLICE )
869     {
870       if( p_gen->NoGranularFieldRC == 0 || p_gen->FieldControl == 0 )
871         updatePparams( p_quad, p_gen, complexity );
872       else
873         p_gen->NoGranularFieldRC = 0;
874     }
875     else if ( p_Vid->type == B_SLICE )
876       updateBparams( p_quad, p_gen, complexity );
877     break;
878   case RC_MODE_1:
879     complexity = updateComplexity( p_Vid, p_quad, p_gen, (Boolean) (p_Vid->number != 0), nbits );
880     if ( p_Vid->number != 0 )
881     {
882       if( p_gen->NoGranularFieldRC == 0 || p_gen->FieldControl == 0 )
883         updatePparams( p_quad, p_gen, complexity );
884       else
885         p_gen->NoGranularFieldRC = 0;
886     }
887     break;
888   case RC_MODE_3:
889     complexity = updateComplexity( p_Vid, p_quad, p_gen, (Boolean) (p_Vid->type == P_SLICE), nbits );
890     if (p_Vid->type == I_SLICE && (p_Vid->number != 0))
891       p_gen->NISlice--;
892 
893     if ( p_Vid->type == P_SLICE )
894     {
895       if( p_gen->NoGranularFieldRC == 0 || p_gen->FieldControl == 0 )
896       {
897         updatePparams( p_quad, p_gen, complexity );
898         p_gen->NPSlice--;
899       }
900       else
901         p_gen->NoGranularFieldRC = 0;
902     }
903     else if ( p_Vid->type == B_SLICE )
904     {
905       updateBparams( p_quad, p_gen, complexity );
906       p_gen->hierNb[ p_Inp->HierarchicalCoding ? (p_Vid->p_curr_frm_struct->layer - 1) : 0 ]--;
907     }
908     break;
909   }
910 }
911 
912 
913 /*!
914  *************************************************************************************
915  * \brief
916  *    update the parameters of quadratic R-D model
917  *
918  *************************************************************************************
919 */
updateRCModel(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,RCGeneric * p_gen)920 void updateRCModel (VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, RCGeneric *p_gen)
921 {
922   int n_windowSize;
923   int i;
924   double std = 0.0, threshold;
925   int m_Nc = p_quad->NumberofCodedPFrame;
926   Boolean MADModelFlag = FALSE;
927   Boolean m_rgRejected[RC_MODEL_HISTORY];
928   double  error       [RC_MODEL_HISTORY];
929 
930   if( p_Vid->type == P_SLICE || (p_Inp->RCUpdateMode == RC_MODE_1 && (p_Vid->number != 0)) )
931   {
932     /*frame layer rate control*/
933     if(p_Vid->BasicUnit == p_Vid->FrameSizeInMbs)
934     {
935       p_quad->CurrentFrameMAD = ComputeFrameMAD(p_Vid);
936       m_Nc=p_quad->NumberofCodedPFrame;
937     }
938     /*basic unit layer rate control*/
939     else
940     {
941       /*compute the MAD of the current basic unit*/
942       p_quad->CurrentFrameMAD = (double) ((p_gen->TotalMADBasicUnit >> 8)/p_Vid->BasicUnit);
943       p_gen->TotalMADBasicUnit=0;
944 
945       /* compute the average number of header bits*/
946       p_quad->CodedBasicUnit=p_quad->TotalNumberofBasicUnit-p_quad->NumberofBasicUnit;
947       if(p_quad->CodedBasicUnit > 0)
948       {
949         p_quad->PAveHeaderBits1=(int)((double)(p_quad->PAveHeaderBits1*(p_quad->CodedBasicUnit-1)+
950           p_gen->NumberofBasicUnitHeaderBits)/p_quad->CodedBasicUnit+0.5);
951         if(p_quad->PAveHeaderBits3 == 0)
952           p_quad->PAveHeaderBits2 = p_quad->PAveHeaderBits1;
953         else
954         {
955           p_quad->PAveHeaderBits2 = (int)((double)(p_quad->PAveHeaderBits1 * p_quad->CodedBasicUnit+
956             p_quad->PAveHeaderBits3 * p_quad->NumberofBasicUnit)/p_quad->TotalNumberofBasicUnit+0.5);
957         }
958       }
959 
960       if ((p_quad->NumberofBasicUnit >= p_quad->TotalNumberofBasicUnit) || (p_quad->NumberofBasicUnit<0))
961       {
962         fprintf(stderr, "Write into invalid memory in updateRCModel at frame %d, p_quad->NumberofBasicUnit %d\n",
963           p_Vid->framepoc, p_quad->NumberofBasicUnit);
964       }
965 
966       /*update the record of MADs for reference*/
967       if(((p_Inp->PicInterlace == ADAPTIVE_CODING) || (p_Inp->MbInterlace)) && (p_gen->FieldControl == 1))
968         p_quad->FCBUCFMAD[p_quad->TotalNumberofBasicUnit-1-p_quad->NumberofBasicUnit]=p_quad->CurrentFrameMAD;
969       else
970         p_quad->BUCFMAD[p_quad->TotalNumberofBasicUnit-1-p_quad->NumberofBasicUnit]=p_quad->CurrentFrameMAD;
971 
972       if(p_quad->NumberofBasicUnit != 0)
973         m_Nc = p_quad->NumberofCodedPFrame * p_quad->TotalNumberofBasicUnit + p_quad->CodedBasicUnit;
974       else
975         m_Nc = (p_quad->NumberofCodedPFrame-1) * p_quad->TotalNumberofBasicUnit + p_quad->CodedBasicUnit;
976     }
977 
978     if(m_Nc > 1)
979       MADModelFlag=TRUE;
980 
981     p_quad->PPreHeader = p_gen->NumberofHeaderBits;
982     for (i = (RC_MODEL_HISTORY-2); i > 0; i--)
983     {// update the history
984       p_quad->Pm_rgQp[i] = p_quad->Pm_rgQp[i - 1];
985       p_quad->m_rgQp[i]  = p_quad->Pm_rgQp[i];
986       p_quad->Pm_rgRp[i] = p_quad->Pm_rgRp[i - 1];
987       p_quad->m_rgRp[i]  = p_quad->Pm_rgRp[i];
988     }
989     p_quad->Pm_rgQp[0] = QP2Qstep(p_quad->m_Qc); //*1.0/p_quad->CurrentFrameMAD;
990     /*frame layer rate control*/
991     if(p_Vid->BasicUnit == p_Vid->FrameSizeInMbs)
992       p_quad->Pm_rgRp[0] = p_gen->NumberofTextureBits*1.0/p_quad->CurrentFrameMAD;
993     /*basic unit layer rate control*/
994     else
995       p_quad->Pm_rgRp[0] = p_gen->NumberofBasicUnitTextureBits*1.0/p_quad->CurrentFrameMAD;
996 
997     p_quad->m_rgQp[0] = p_quad->Pm_rgQp[0];
998     p_quad->m_rgRp[0] = p_quad->Pm_rgRp[0];
999     p_quad->m_X1 = p_quad->Pm_X1;
1000     p_quad->m_X2 = p_quad->Pm_X2;
1001 
1002     /*compute the size of window*/
1003     n_windowSize = (p_quad->CurrentFrameMAD>p_quad->PreviousFrameMAD)
1004       ? (int)(p_quad->PreviousFrameMAD/p_quad->CurrentFrameMAD * (RC_MODEL_HISTORY-1) )
1005       : (int)(p_quad->CurrentFrameMAD/p_quad->PreviousFrameMAD *(RC_MODEL_HISTORY-1));
1006     n_windowSize=iClip3(1, m_Nc, n_windowSize);
1007     n_windowSize=imin(n_windowSize,p_quad->m_windowSize+1);
1008     n_windowSize=imin(n_windowSize,(RC_MODEL_HISTORY-1));
1009 
1010     /*update the previous window size*/
1011     p_quad->m_windowSize=n_windowSize;
1012 
1013     for (i = 0; i < (RC_MODEL_HISTORY-1); i++)
1014     {
1015       m_rgRejected[i] = FALSE;
1016     }
1017 
1018     // initial RD model estimator
1019     RCModelEstimator (p_Vid, p_Inp, p_quad, n_windowSize, m_rgRejected);
1020 
1021     n_windowSize = p_quad->m_windowSize;
1022     // remove outlier
1023 
1024     for (i = 0; i < (int) n_windowSize; i++)
1025     {
1026       error[i] = p_quad->m_X1 / p_quad->m_rgQp[i] + p_quad->m_X2 / (p_quad->m_rgQp[i] * p_quad->m_rgQp[i]) - p_quad->m_rgRp[i];
1027       std += error[i] * error[i];
1028     }
1029     threshold = (n_windowSize == 2) ? 0 : sqrt (std / n_windowSize);
1030     for (i = 0; i < (int) n_windowSize; i++)
1031     {
1032       if (fabs(error[i]) > threshold)
1033         m_rgRejected[i] = TRUE;
1034     }
1035     // always include the last data point
1036     m_rgRejected[0] = FALSE;
1037 
1038     // second RD model estimator
1039     RCModelEstimator (p_Vid, p_Inp, p_quad, n_windowSize, m_rgRejected);
1040 
1041     if( MADModelFlag )
1042       updateMADModel(p_Vid, p_Inp, p_quad, p_gen);
1043     else if( p_Vid->type == P_SLICE || (p_Inp->RCUpdateMode == RC_MODE_1 && (p_Vid->number != 0)) )
1044       p_quad->PPictureMAD[0] = p_quad->CurrentFrameMAD;
1045   }
1046 }
1047 
1048 /*!
1049  *************************************************************************************
1050  * \brief
1051  *    Model Estimator
1052  *
1053  *************************************************************************************
1054 */
RCModelEstimator(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,int n_windowSize,Boolean * m_rgRejected)1055 void RCModelEstimator (VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, int n_windowSize, Boolean *m_rgRejected)
1056 {
1057   int n_realSize = n_windowSize;
1058   int i;
1059   double oneSampleQ = 0;
1060   double a00 = 0.0, a01 = 0.0, a10 = 0.0, a11 = 0.0, b0 = 0.0, b1 = 0.0;
1061   double MatrixValue;
1062   Boolean estimateX2 = FALSE;
1063 
1064   for (i = 0; i < n_windowSize; i++)
1065   {// find the number of samples which are not rejected
1066     if (m_rgRejected[i])
1067       n_realSize--;
1068   }
1069 
1070   // default RD model estimation results
1071   p_quad->m_X1 = p_quad->m_X2 = 0.0;
1072 
1073   for (i = 0; i < n_windowSize; i++)
1074   {
1075     if (!m_rgRejected[i])
1076       oneSampleQ = p_quad->m_rgQp[i];
1077   }
1078   for (i = 0; i < n_windowSize; i++)
1079   {// if all non-rejected Q are the same, take 1st order model
1080     if ((p_quad->m_rgQp[i] != oneSampleQ) && !m_rgRejected[i])
1081       estimateX2 = TRUE;
1082     if (!m_rgRejected[i])
1083       p_quad->m_X1 += (p_quad->m_rgQp[i] * p_quad->m_rgRp[i]) / n_realSize;
1084   }
1085 
1086   // take 2nd order model to estimate X1 and X2
1087   if ((n_realSize >= 1) && estimateX2)
1088   {
1089     for (i = 0; i < n_windowSize; i++)
1090     {
1091       if (!m_rgRejected[i])
1092       {
1093         a00  = a00 + 1.0;
1094         a01 += 1.0 / p_quad->m_rgQp[i];
1095         a10  = a01;
1096         a11 += 1.0 / (p_quad->m_rgQp[i] * p_quad->m_rgQp[i]);
1097         b0  += p_quad->m_rgQp[i] * p_quad->m_rgRp[i];
1098         b1  += p_quad->m_rgRp[i];
1099       }
1100     }
1101     // solve the equation of AX = B
1102     MatrixValue=a00*a11-a01*a10;
1103     if(fabs(MatrixValue) > 0.000001)
1104     {
1105       p_quad->m_X1 = (b0 * a11 - b1 * a01) / MatrixValue;
1106       p_quad->m_X2 = (b1 * a00 - b0 * a10) / MatrixValue;
1107     }
1108     else
1109     {
1110       p_quad->m_X1 = b0 / a00;
1111       p_quad->m_X2 = 0.0;
1112     }
1113   }
1114   if( p_Vid->type == P_SLICE || (p_Inp->RCUpdateMode == RC_MODE_1 && (p_Vid->number != 0)) )
1115   {
1116     p_quad->Pm_X1 = p_quad->m_X1;
1117     p_quad->Pm_X2 = p_quad->m_X2;
1118   }
1119 }
1120 
1121 /*!
1122  *************************************************************************************
1123  * \brief
1124  *    update the parameters of linear prediction model
1125  *
1126  *************************************************************************************
1127 */
updateMADModel(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,RCGeneric * p_gen)1128 void updateMADModel (VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, RCGeneric *p_gen)
1129 {
1130   int    n_windowSize;
1131   int    i;
1132   double std = 0.0, threshold;
1133   int    m_Nc = p_quad->NumberofCodedPFrame;
1134   Boolean PictureRejected[RC_MODEL_HISTORY];
1135   double  error          [RC_MODEL_HISTORY];
1136 
1137   if(p_quad->NumberofCodedPFrame>0)
1138   {
1139     //assert (p_Vid->type!=P_SLICE);
1140     /*frame layer rate control*/
1141     if(p_Vid->BasicUnit == p_Vid->FrameSizeInMbs)
1142       m_Nc = p_quad->NumberofCodedPFrame;
1143     else // basic unit layer rate control
1144       m_Nc=p_quad->NumberofCodedPFrame*p_quad->TotalNumberofBasicUnit+p_quad->CodedBasicUnit;
1145 
1146     for (i = (RC_MODEL_HISTORY-2); i > 0; i--)
1147     {// update the history
1148       p_quad->PPictureMAD[i]  = p_quad->PPictureMAD[i - 1];
1149       p_quad->PictureMAD[i]   = p_quad->PPictureMAD[i];
1150       p_quad->ReferenceMAD[i] = p_quad->ReferenceMAD[i-1];
1151     }
1152     p_quad->PPictureMAD[0] = p_quad->CurrentFrameMAD;
1153     p_quad->PictureMAD[0]  = p_quad->PPictureMAD[0];
1154 
1155     if(p_Vid->BasicUnit == p_Vid->FrameSizeInMbs)
1156       p_quad->ReferenceMAD[0]=p_quad->PictureMAD[1];
1157     else
1158     {
1159       if(((p_Inp->PicInterlace==ADAPTIVE_CODING)||(p_Inp->MbInterlace)) &&(p_gen->FieldControl==1))
1160         p_quad->ReferenceMAD[0]=p_quad->FCBUPFMAD[p_quad->TotalNumberofBasicUnit-1-p_quad->NumberofBasicUnit];
1161       else
1162         p_quad->ReferenceMAD[0]=p_quad->BUPFMAD[p_quad->TotalNumberofBasicUnit-1-p_quad->NumberofBasicUnit];
1163     }
1164     p_quad->MADPictureC1 = p_quad->PMADPictureC1;
1165     p_quad->MADPictureC2 = p_quad->PMADPictureC2;
1166 
1167     /*compute the size of window*/
1168     n_windowSize = (p_quad->CurrentFrameMAD > p_quad->PreviousFrameMAD)
1169       ? (int) ((float)(RC_MODEL_HISTORY-1) * p_quad->PreviousFrameMAD / p_quad->CurrentFrameMAD)
1170       : (int) ((float)(RC_MODEL_HISTORY-1) * p_quad->CurrentFrameMAD / p_quad->PreviousFrameMAD);
1171     n_windowSize = iClip3(1, (m_Nc-1), n_windowSize);
1172     n_windowSize=imin(n_windowSize, imin(20, p_quad->MADm_windowSize + 1));
1173 
1174     /*update the previous window size*/
1175     p_quad->MADm_windowSize=n_windowSize;
1176 
1177     for (i = 0; i < (RC_MODEL_HISTORY-1); i++)
1178     {
1179       PictureRejected[i] = FALSE;
1180     }
1181 
1182     //update the MAD for the previous frame
1183     if( p_Vid->type == P_SLICE || (p_Inp->RCUpdateMode == RC_MODE_1 && (p_Vid->number != 0)) )
1184       p_quad->PreviousFrameMAD=p_quad->CurrentFrameMAD;
1185 
1186     // initial MAD model estimator
1187     MADModelEstimator (p_Vid, p_Inp, p_quad, n_windowSize, PictureRejected);
1188 
1189     // remove outlier
1190     for (i = 0; i < n_windowSize; i++)
1191     {
1192       error[i] = p_quad->MADPictureC1 * p_quad->ReferenceMAD[i] + p_quad->MADPictureC2 - p_quad->PictureMAD[i];
1193       std += (error[i] * error[i]);
1194     }
1195 
1196     threshold = (n_windowSize == 2) ? 0 : sqrt (std / n_windowSize);
1197     for (i = 0; i < n_windowSize; i++)
1198     {
1199       if (fabs(error[i]) > threshold)
1200         PictureRejected[i] = TRUE;
1201     }
1202     // always include the last data point
1203     PictureRejected[0] = FALSE;
1204 
1205     // second MAD model estimator
1206     MADModelEstimator (p_Vid, p_Inp, p_quad, n_windowSize, PictureRejected);
1207   }
1208 }
1209 
1210 
1211 /*!
1212  *************************************************************************************
1213  * \brief
1214  *    MAD mode estimator
1215  *
1216  *************************************************************************************
1217 */
MADModelEstimator(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,int n_windowSize,Boolean * PictureRejected)1218 void MADModelEstimator (VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, int n_windowSize, Boolean *PictureRejected)
1219 {
1220   int    n_realSize = n_windowSize;
1221   int    i;
1222   double oneSampleQ = 0.0;
1223   double a00 = 0.0, a01 = 0.0, a10 = 0.0, a11 = 0.0, b0 = 0.0, b1 = 0.0;
1224   double MatrixValue;
1225   Boolean estimateX2 = FALSE;
1226 
1227   for (i = 0; i < n_windowSize; i++)
1228   {// find the number of samples which are not rejected
1229     if (PictureRejected[i])
1230       n_realSize--;
1231   }
1232 
1233   // default MAD model estimation results
1234   p_quad->MADPictureC1 = p_quad->MADPictureC2 = 0.0;
1235 
1236   for (i = 0; i < n_windowSize; i++)
1237   {
1238     if (!PictureRejected[i])
1239       oneSampleQ = p_quad->PictureMAD[i];
1240   }
1241 
1242   for (i = 0; i < n_windowSize; i++)
1243   {// if all non-rejected MAD are the same, take 1st order model
1244     if ((p_quad->PictureMAD[i] != oneSampleQ) && !PictureRejected[i])
1245       estimateX2 = TRUE;
1246     if (!PictureRejected[i])
1247       p_quad->MADPictureC1 += p_quad->PictureMAD[i] / (p_quad->ReferenceMAD[i]*n_realSize);
1248   }
1249 
1250   // take 2nd order model to estimate X1 and X2
1251   if ((n_realSize >= 1) && estimateX2)
1252   {
1253     for (i = 0; i < n_windowSize; i++)
1254     {
1255       if (!PictureRejected[i])
1256       {
1257         a00  = a00 + 1.0;
1258         a01 += p_quad->ReferenceMAD[i];
1259         a10  = a01;
1260         a11 += p_quad->ReferenceMAD[i] * p_quad->ReferenceMAD[i];
1261         b0  += p_quad->PictureMAD[i];
1262         b1  += p_quad->PictureMAD[i]   * p_quad->ReferenceMAD[i];
1263       }
1264     }
1265     // solve the equation of AX = B
1266     MatrixValue = a00 * a11 - a01 * a10;
1267     if(fabs(MatrixValue) > 0.000001)
1268     {
1269       p_quad->MADPictureC2 = (b0 * a11 - b1 * a01) / MatrixValue;
1270       p_quad->MADPictureC1 = (b1 * a00 - b0 * a10) / MatrixValue;
1271     }
1272     else
1273     {
1274       p_quad->MADPictureC1 = b0/a01;
1275       p_quad->MADPictureC2 = 0.0;
1276     }
1277   }
1278   if( p_Vid->type == P_SLICE || (p_Inp->RCUpdateMode == RC_MODE_1 && (p_Vid->number != 0)) )
1279   {
1280     p_quad->PMADPictureC1 = p_quad->MADPictureC1;
1281     p_quad->PMADPictureC2 = p_quad->MADPictureC2;
1282   }
1283 }
1284 
1285 /*!
1286  *************************************************************************************
1287  * \brief
1288  *    compute a  quantization parameter for each frame (RC_MODE_0)
1289  *
1290  *************************************************************************************
1291 */
updateQPRC0(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,RCGeneric * p_gen,int topfield)1292 int updateQPRC0(VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, RCGeneric *p_gen, int topfield)
1293 {
1294   int m_Bits;
1295   int BFrameNumber;
1296   int StepSize;
1297   int SumofBasicUnit;
1298   int MaxQpChange, m_Qp, m_Hp;
1299 
1300   /* frame layer rate control */
1301   if( p_Vid->BasicUnit == p_Vid->FrameSizeInMbs )
1302   {
1303     /* fixed quantization parameter is used to coded I frame, the first P frame and the first B frame
1304     the quantization parameter is adjusted according the available channel bandwidth and
1305     the type of video */
1306     /*top field*/
1307     if((topfield) || (p_gen->FieldControl==0))
1308     {
1309       if (p_Vid->type==I_SLICE)
1310       {
1311         p_quad->m_Qc = p_quad->MyInitialQp;
1312         return p_quad->m_Qc;
1313       }
1314       else if(p_Vid->type == B_SLICE)
1315       {
1316         if(p_Inp->NumberBFrames==1)
1317         {
1318           if((p_Inp->PicInterlace==ADAPTIVE_CODING)||(p_Inp->MbInterlace))
1319             updateQPInterlace( p_quad, p_gen );
1320 
1321           p_quad->m_Qc = imin(p_quad->PrevLastQP, p_quad->CurrLastQP) + 2;
1322           p_quad->m_Qc = imax(p_quad->m_Qc, imax(p_quad->PrevLastQP, p_quad->CurrLastQP));
1323           p_quad->m_Qc = imax(p_quad->m_Qc, p_quad->CurrLastQP + 1);
1324           p_quad->m_Qc = iClip3(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc); // Clipping
1325         }
1326         else
1327         {
1328           BFrameNumber = (p_quad->NumberofBFrames + 1) % p_Inp->NumberBFrames;
1329           if(BFrameNumber==0)
1330             BFrameNumber = p_Inp->NumberBFrames;
1331 
1332           /*adaptive field/frame coding*/
1333           if(BFrameNumber==1)
1334           {
1335             if((p_Inp->PicInterlace==ADAPTIVE_CODING)||(p_Inp->MbInterlace))
1336               updateQPInterlace( p_quad, p_gen );
1337           }
1338 
1339           if((p_quad->CurrLastQP-p_quad->PrevLastQP)<=(-2*p_Inp->NumberBFrames-3))
1340             StepSize=-3;
1341           else  if((p_quad->CurrLastQP-p_quad->PrevLastQP)==(-2*p_Inp->NumberBFrames-2))
1342             StepSize=-2;
1343           else if((p_quad->CurrLastQP-p_quad->PrevLastQP)==(-2*p_Inp->NumberBFrames-1))
1344             StepSize=-1;
1345           else if((p_quad->CurrLastQP-p_quad->PrevLastQP)==(-2*p_Inp->NumberBFrames))
1346             StepSize=0;
1347           else if((p_quad->CurrLastQP-p_quad->PrevLastQP)==(-2*p_Inp->NumberBFrames+1))
1348             StepSize=1;
1349           else
1350             StepSize=2;
1351 
1352           p_quad->m_Qc  = p_quad->PrevLastQP + StepSize;
1353           p_quad->m_Qc += iClip3( -2 * (BFrameNumber - 1), 2*(BFrameNumber-1),
1354             (BFrameNumber-1)*(p_quad->CurrLastQP-p_quad->PrevLastQP)/(p_Inp->NumberBFrames-1));
1355           p_quad->m_Qc  = iClip3(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc); // Clipping
1356         }
1357         return p_quad->m_Qc;
1358       }
1359       else if( p_Vid->type == P_SLICE && p_quad->NumberofPPicture == 0 )
1360       {
1361         p_quad->m_Qc=p_quad->MyInitialQp;
1362 
1363         if(p_gen->FieldControl==0)
1364           updateQPNonPicAFF( p_Vid->active_sps, p_quad );
1365         return p_quad->m_Qc;
1366       }
1367       else
1368       {
1369         /*adaptive field/frame coding*/
1370         if( ( p_Inp->PicInterlace == ADAPTIVE_CODING || p_Inp->MbInterlace ) && p_gen->FieldControl == 0 )
1371           updateQPInterlaceBU( p_quad, p_gen );
1372 
1373         p_quad->m_X1 = p_quad->Pm_X1;
1374         p_quad->m_X2 = p_quad->Pm_X2;
1375         p_quad->MADPictureC1 = p_quad->PMADPictureC1;
1376         p_quad->MADPictureC2 = p_quad->PMADPictureC2;
1377         p_quad->PreviousPictureMAD = p_quad->PPictureMAD[0];
1378 
1379         MaxQpChange = p_quad->PMaxQpChange;
1380         m_Qp = p_quad->Pm_Qp;
1381         m_Hp = p_quad->PPreHeader;
1382 
1383         /* predict the MAD of current picture*/
1384         p_quad->CurrentFrameMAD = p_quad->MADPictureC1*p_quad->PreviousPictureMAD + p_quad->MADPictureC2;
1385 
1386         /*compute the number of bits for the texture*/
1387         if(p_quad->Target < 0)
1388         {
1389           p_quad->m_Qc=m_Qp+MaxQpChange;
1390           p_quad->m_Qc = iClip3(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc); // Clipping
1391         }
1392         else
1393         {
1394           m_Bits = p_quad->Target-m_Hp;
1395           m_Bits = imax(m_Bits, (int)(p_quad->bit_rate/(MINVALUE*p_quad->frame_rate)));
1396 
1397           updateModelQPFrame( p_quad, m_Bits );
1398 
1399           p_quad->m_Qc = iClip3(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc); // clipping
1400           p_quad->m_Qc = iClip3(m_Qp-MaxQpChange, m_Qp+MaxQpChange, p_quad->m_Qc); // control variation
1401         }
1402 
1403         if( p_gen->FieldControl == 0 )
1404           updateQPNonPicAFF( p_Vid->active_sps, p_quad );
1405 
1406         return p_quad->m_Qc;
1407       }
1408     }
1409     /*bottom field*/
1410     else
1411     {
1412       if( p_Vid->type == P_SLICE && p_gen->NoGranularFieldRC == 0 )
1413         updateBottomField( p_Inp, p_quad );
1414       return p_quad->m_Qc;
1415     }
1416   }
1417   /*basic unit layer rate control*/
1418   else
1419   {
1420     /*top field of I frame*/
1421     if (p_Vid->type == I_SLICE)
1422     {
1423       p_quad->m_Qc = p_quad->MyInitialQp;
1424       return p_quad->m_Qc;
1425     }
1426     else if( p_Vid->type == B_SLICE )
1427     {
1428       /*top field of B frame*/
1429       if((topfield)||(p_gen->FieldControl==0))
1430       {
1431         if(p_Inp->NumberBFrames==1)
1432         {
1433           /*adaptive field/frame coding*/
1434           if((p_Inp->PicInterlace==ADAPTIVE_CODING)||(p_Inp->MbInterlace))
1435             updateQPInterlace( p_quad, p_gen );
1436 
1437           if(p_quad->PrevLastQP==p_quad->CurrLastQP)
1438             p_quad->m_Qc=p_quad->PrevLastQP+2;
1439           else
1440             p_quad->m_Qc = ((p_quad->PrevLastQP+p_quad->CurrLastQP) >> 1) + 1;
1441           p_quad->m_Qc = iClip3(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc); // Clipping
1442         }
1443         else
1444         {
1445           BFrameNumber=(p_quad->NumberofBFrames+1)%p_Inp->NumberBFrames;
1446           if(BFrameNumber==0)
1447             BFrameNumber=p_Inp->NumberBFrames;
1448 
1449           /*adaptive field/frame coding*/
1450           if(BFrameNumber==1)
1451           {
1452             if((p_Inp->PicInterlace==ADAPTIVE_CODING)||(p_Inp->MbInterlace))
1453               updateQPInterlace( p_quad, p_gen );
1454           }
1455 
1456           if((p_quad->CurrLastQP-p_quad->PrevLastQP)<=(-2*p_Inp->NumberBFrames-3))
1457             StepSize=-3;
1458           else  if((p_quad->CurrLastQP-p_quad->PrevLastQP)==(-2*p_Inp->NumberBFrames-2))
1459             StepSize=-2;
1460           else if((p_quad->CurrLastQP-p_quad->PrevLastQP)==(-2*p_Inp->NumberBFrames-1))
1461             StepSize=-1;
1462           else if((p_quad->CurrLastQP-p_quad->PrevLastQP)==(-2*p_Inp->NumberBFrames))
1463             StepSize=0;//0
1464           else if((p_quad->CurrLastQP-p_quad->PrevLastQP)==(-2*p_Inp->NumberBFrames+1))
1465             StepSize=1;//1
1466           else
1467             StepSize=2;//2
1468           p_quad->m_Qc=p_quad->PrevLastQP+StepSize;
1469           p_quad->m_Qc +=
1470             iClip3( -2*(BFrameNumber-1), 2*(BFrameNumber-1), (BFrameNumber-1)*(p_quad->CurrLastQP-p_quad->PrevLastQP)/(p_Inp->NumberBFrames-1) );
1471           p_quad->m_Qc = iClip3(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc); // Clipping
1472         }
1473         return p_quad->m_Qc;
1474       }
1475       /*bottom field of B frame*/
1476       else
1477       {
1478         return p_quad->m_Qc;
1479       }
1480     }
1481     else if( p_Vid->type == P_SLICE )
1482     {
1483       if( (p_gen->NumberofGOP == 1) && (p_quad->NumberofPPicture == 0) )
1484       {
1485         if((p_gen->FieldControl==0)||((p_gen->FieldControl==1) && (p_gen->NoGranularFieldRC==0)))
1486           return updateFirstP( p_Vid, p_Inp, p_quad, p_gen, topfield );
1487       }
1488       else
1489       {
1490         p_quad->m_X1=p_quad->Pm_X1;
1491         p_quad->m_X2=p_quad->Pm_X2;
1492         p_quad->MADPictureC1=p_quad->PMADPictureC1;
1493         p_quad->MADPictureC2=p_quad->PMADPictureC2;
1494 
1495         m_Qp=p_quad->Pm_Qp;
1496 
1497         if(p_gen->FieldControl==0)
1498           SumofBasicUnit=p_quad->TotalNumberofBasicUnit;
1499         else
1500           SumofBasicUnit=p_quad->TotalNumberofBasicUnit>>1;
1501 
1502         /*the average QP of the previous frame is used to coded the first basic unit of the current frame or field*/
1503         if(p_quad->NumberofBasicUnit==SumofBasicUnit)
1504           return updateFirstBU( p_Vid, p_Inp, p_quad, p_gen, topfield );
1505         else
1506         {
1507           /*compute the number of remaining bits*/
1508           p_quad->Target -= (p_gen->NumberofBasicUnitHeaderBits + p_gen->NumberofBasicUnitTextureBits);
1509           p_gen->NumberofBasicUnitHeaderBits  = 0;
1510           p_gen->NumberofBasicUnitTextureBits = 0;
1511           if(p_quad->Target<0)
1512             return updateNegativeTarget( p_Vid, p_Inp, p_quad, p_gen, topfield, m_Qp );
1513           else
1514           {
1515             /*predict the MAD of current picture*/
1516             predictCurrPicMAD( p_Inp, p_quad, p_gen );
1517 
1518             /*compute the total number of bits for the current basic unit*/
1519             updateModelQPBU( p_Vid, p_Inp, p_quad, m_Qp );
1520 
1521             p_quad->TotalFrameQP +=p_quad->m_Qc;
1522             p_quad->Pm_Qp=p_quad->m_Qc;
1523             p_quad->NumberofBasicUnit--;
1524             if( p_quad->NumberofBasicUnit == 0 && p_Vid->type == P_SLICE )
1525               updateLastBU( p_Vid, p_Inp, p_quad, p_gen, topfield );
1526 
1527             return p_quad->m_Qc;
1528           }
1529         }
1530       }
1531     }
1532   }
1533   return p_quad->m_Qc;
1534 }
1535 
1536 /*!
1537  *************************************************************************************
1538  * \brief
1539  *    compute a  quantization parameter for each frame
1540  *
1541  *************************************************************************************
1542 */
updateQPRC1(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,RCGeneric * p_gen,int topfield)1543 int updateQPRC1(VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, RCGeneric *p_gen, int topfield)
1544 {
1545   int m_Bits;
1546   int SumofBasicUnit;
1547   int MaxQpChange, m_Qp, m_Hp;
1548 
1549   /* frame layer rate control */
1550   if( p_Vid->BasicUnit == p_Vid->FrameSizeInMbs )
1551   {
1552     /* fixed quantization parameter is used to coded I frame, the first P frame and the first B frame
1553     the quantization parameter is adjusted according the available channel bandwidth and
1554     the type of vide */
1555     /*top field*/
1556     if((topfield) || (p_gen->FieldControl==0))
1557     {
1558       if (p_Vid->number == 0)
1559       {
1560         p_quad->m_Qc = p_quad->MyInitialQp;
1561         return p_quad->m_Qc;
1562       }
1563       else if( p_quad->NumberofPPicture == 0 && (p_Vid->number != 0))
1564       {
1565         p_quad->m_Qc=p_quad->MyInitialQp;
1566 
1567         if(p_gen->FieldControl==0)
1568           updateQPNonPicAFF( p_Vid->active_sps, p_quad );
1569         return p_quad->m_Qc;
1570       }
1571       else
1572       {
1573         /*adaptive field/frame coding*/
1574         if( ( p_Inp->PicInterlace == ADAPTIVE_CODING || p_Inp->MbInterlace ) && p_gen->FieldControl == 0 )
1575           updateQPInterlaceBU( p_quad, p_gen );
1576 
1577         p_quad->m_X1 = p_quad->Pm_X1;
1578         p_quad->m_X2 = p_quad->Pm_X2;
1579         p_quad->MADPictureC1 = p_quad->PMADPictureC1;
1580         p_quad->MADPictureC2 = p_quad->PMADPictureC2;
1581         p_quad->PreviousPictureMAD = p_quad->PPictureMAD[0];
1582 
1583         MaxQpChange = p_quad->PMaxQpChange;
1584         m_Qp = p_quad->Pm_Qp;
1585         m_Hp = p_quad->PPreHeader;
1586 
1587         /* predict the MAD of current picture*/
1588         p_quad->CurrentFrameMAD=p_quad->MADPictureC1*p_quad->PreviousPictureMAD + p_quad->MADPictureC2;
1589 
1590         /*compute the number of bits for the texture*/
1591         if(p_quad->Target < 0)
1592         {
1593           p_quad->m_Qc=m_Qp+MaxQpChange;
1594           p_quad->m_Qc = iClip3(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc); // Clipping
1595         }
1596         else
1597         {
1598           m_Bits = p_quad->Target-m_Hp;
1599           m_Bits = imax(m_Bits, (int)(p_quad->bit_rate/(MINVALUE*p_quad->frame_rate)));
1600 
1601           updateModelQPFrame( p_quad, m_Bits );
1602 
1603           p_quad->m_Qc = iClip3(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc); // clipping
1604           p_quad->m_Qc = iClip3(m_Qp-MaxQpChange, m_Qp+MaxQpChange, p_quad->m_Qc); // control variation
1605         }
1606 
1607         if( p_gen->FieldControl == 0 )
1608           updateQPNonPicAFF( p_Vid->active_sps, p_quad );
1609 
1610         return p_quad->m_Qc;
1611       }
1612     }
1613     /*bottom field*/
1614     else
1615     {
1616       if( p_gen->NoGranularFieldRC == 0 )
1617         updateBottomField( p_Inp, p_quad );
1618       return p_quad->m_Qc;
1619     }
1620   }
1621   /*basic unit layer rate control*/
1622   else
1623   {
1624     /*top field of I frame*/
1625     if (p_Vid->number == 0)
1626     {
1627       p_quad->m_Qc = p_quad->MyInitialQp;
1628       return p_quad->m_Qc;
1629     }
1630     else
1631     {
1632       if((p_gen->NumberofGOP==1)&&(p_quad->NumberofPPicture==0))
1633       {
1634         if((p_gen->FieldControl==0)||((p_gen->FieldControl==1) && (p_gen->NoGranularFieldRC==0)))
1635           return updateFirstP( p_Vid, p_Inp, p_quad, p_gen, topfield );
1636       }
1637       else
1638       {
1639         p_quad->m_X1=p_quad->Pm_X1;
1640         p_quad->m_X2=p_quad->Pm_X2;
1641         p_quad->MADPictureC1=p_quad->PMADPictureC1;
1642         p_quad->MADPictureC2=p_quad->PMADPictureC2;
1643 
1644         m_Qp=p_quad->Pm_Qp;
1645 
1646         if(p_gen->FieldControl==0)
1647           SumofBasicUnit=p_quad->TotalNumberofBasicUnit;
1648         else
1649           SumofBasicUnit=p_quad->TotalNumberofBasicUnit>>1;
1650 
1651         /*the average QP of the previous frame is used to coded the first basic unit of the current frame or field*/
1652         if(p_quad->NumberofBasicUnit==SumofBasicUnit)
1653           return updateFirstBU( p_Vid, p_Inp, p_quad, p_gen, topfield );
1654         else
1655         {
1656           /*compute the number of remaining bits*/
1657           p_quad->Target -= (p_gen->NumberofBasicUnitHeaderBits + p_gen->NumberofBasicUnitTextureBits);
1658           p_gen->NumberofBasicUnitHeaderBits  = 0;
1659           p_gen->NumberofBasicUnitTextureBits = 0;
1660           if(p_quad->Target<0)
1661             return updateNegativeTarget( p_Vid, p_Inp, p_quad, p_gen, topfield, m_Qp );
1662           else
1663           {
1664             /*predict the MAD of current picture*/
1665             predictCurrPicMAD( p_Inp, p_quad, p_gen );
1666 
1667             /*compute the total number of bits for the current basic unit*/
1668             updateModelQPBU( p_Vid, p_Inp, p_quad, m_Qp );
1669 
1670             p_quad->TotalFrameQP +=p_quad->m_Qc;
1671             p_quad->Pm_Qp=p_quad->m_Qc;
1672             p_quad->NumberofBasicUnit--;
1673             if((p_quad->NumberofBasicUnit==0) && (p_Vid->number != 0))
1674               updateLastBU( p_Vid, p_Inp, p_quad, p_gen, topfield );
1675 
1676             return p_quad->m_Qc;
1677           }
1678         }
1679       }
1680     }
1681   }
1682   return p_quad->m_Qc;
1683 }
1684 
1685 /*!
1686  *************************************************************************************
1687  * \brief
1688  *    compute a  quantization parameter for each frame
1689  *
1690  *************************************************************************************
1691 */
updateQPRC2(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,RCGeneric * p_gen,int topfield)1692 int updateQPRC2(VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, RCGeneric *p_gen, int topfield)
1693 {
1694   int m_Bits;
1695   int SumofBasicUnit;
1696   int MaxQpChange, m_Qp, m_Hp;
1697 
1698   /* frame layer rate control */
1699   if( p_Vid->BasicUnit == p_Vid->FrameSizeInMbs )
1700   {
1701     /* fixed quantization parameter is used to coded I frame, the first P frame and the first B frame
1702     the quantization parameter is adjusted according the available channel bandwidth and
1703     the type of vide */
1704     /*top field*/
1705     if((topfield) || (p_gen->FieldControl==0))
1706     {
1707       if (p_Vid->number == 0)
1708       {
1709         p_quad->m_Qc = p_quad->MyInitialQp;
1710         return p_quad->m_Qc;
1711       }
1712       else if (p_Vid->type==I_SLICE)
1713       {
1714         if((p_Inp->PicInterlace==ADAPTIVE_CODING)||(p_Inp->MbInterlace))
1715           updateQPInterlace( p_quad, p_gen );
1716 
1717         if ( p_Vid->p_curr_frm_struct->idr_flag )
1718           p_quad->m_Qc = p_quad->MyInitialQp;
1719         else
1720           p_quad->m_Qc = p_quad->CurrLastQP; // Set QP to average qp of last P frame
1721 
1722         return p_quad->m_Qc;
1723       }
1724       else if(p_Vid->type == B_SLICE)
1725       {
1726         int prevQP = imax(p_quad->PrevLastQP, p_quad->CurrLastQP);
1727         // for more than one consecutive B frames the below call will overwrite the old anchor frame QP with the current value
1728         // it should be called once in the B-frame sequence....this should be modified for the BU < frame as well
1729         if((p_Inp->PicInterlace==ADAPTIVE_CODING)||(p_Inp->MbInterlace))
1730           updateQPInterlace( p_quad, p_gen );
1731 
1732         if (p_Inp->HierarchicalCoding)
1733         {
1734           p_quad->m_Qc = prevQP + p_Vid->p_curr_frm_struct->layer;
1735         }
1736         else
1737           p_quad->m_Qc = prevQP + 2 - p_Vid->nal_reference_idc;
1738         p_quad->m_Qc = iClip3(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc); // Clipping
1739 
1740         return p_quad->m_Qc;
1741       }
1742       else if( p_Vid->type == P_SLICE && p_quad->NumberofPPicture == 0 )
1743       {
1744         p_quad->m_Qc=p_quad->MyInitialQp;
1745 
1746         if(p_gen->FieldControl==0)
1747           updateQPNonPicAFF( p_Vid->active_sps, p_quad );
1748         return p_quad->m_Qc;
1749       }
1750       else
1751       {
1752         /*adaptive field/frame coding*/
1753         if( ( p_Inp->PicInterlace == ADAPTIVE_CODING || p_Inp->MbInterlace ) && p_gen->FieldControl == 0 )
1754           updateQPInterlaceBU( p_quad, p_gen );
1755 
1756         p_quad->m_X1 = p_quad->Pm_X1;
1757         p_quad->m_X2 = p_quad->Pm_X2;
1758         p_quad->MADPictureC1 = p_quad->PMADPictureC1;
1759         p_quad->MADPictureC2 = p_quad->PMADPictureC2;
1760         p_quad->PreviousPictureMAD = p_quad->PPictureMAD[0];
1761 
1762         MaxQpChange = p_quad->PMaxQpChange;
1763         m_Qp = p_quad->Pm_Qp;
1764         m_Hp = p_quad->PPreHeader;
1765 
1766         /* predict the MAD of current picture*/
1767         p_quad->CurrentFrameMAD=p_quad->MADPictureC1*p_quad->PreviousPictureMAD + p_quad->MADPictureC2;
1768 
1769         /*compute the number of bits for the texture*/
1770         if(p_quad->Target < 0)
1771         {
1772           p_quad->m_Qc=m_Qp+MaxQpChange;
1773           p_quad->m_Qc = iClip3(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc); // Clipping
1774         }
1775         else
1776         {
1777           m_Bits = p_quad->Target-m_Hp;
1778           m_Bits = imax(m_Bits, (int)(p_quad->bit_rate/(MINVALUE*p_quad->frame_rate)));
1779 
1780           updateModelQPFrame( p_quad, m_Bits );
1781 
1782           p_quad->m_Qc = iClip3(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc); // clipping
1783           p_quad->m_Qc = iClip3(m_Qp-MaxQpChange, m_Qp+MaxQpChange, p_quad->m_Qc); // control variation
1784         }
1785 
1786         if( p_gen->FieldControl == 0 )
1787           updateQPNonPicAFF( p_Vid->active_sps, p_quad );
1788 
1789         return p_quad->m_Qc;
1790       }
1791     }
1792     /*bottom field*/
1793     else
1794     {
1795       if( p_Vid->type==P_SLICE && p_gen->NoGranularFieldRC == 0 )
1796         updateBottomField( p_Inp, p_quad );
1797       return p_quad->m_Qc;
1798     }
1799   }
1800   /*basic unit layer rate control*/
1801   else
1802   {
1803     /*top field of I frame*/
1804     if (p_Vid->number == 0)
1805     {
1806       p_quad->m_Qc = p_quad->MyInitialQp;
1807       return p_quad->m_Qc;
1808     }
1809     else if (p_Vid->type==I_SLICE)
1810     {
1811       /*adaptive field/frame coding*/
1812       if((p_Inp->PicInterlace==ADAPTIVE_CODING)||(p_Inp->MbInterlace))
1813         updateQPInterlace( p_quad, p_gen );
1814 
1815       p_quad->m_Qc = p_quad->PrevLastQP; // Set QP to average qp of last P frame
1816       p_quad->PrevLastQP = p_quad->CurrLastQP;
1817       p_quad->CurrLastQP = p_quad->PrevLastQP;
1818       p_quad->PAveFrameQP = p_quad->CurrLastQP;
1819 
1820       return p_quad->m_Qc;
1821     }
1822     else if(p_Vid->type == B_SLICE)
1823     {
1824       int prevQP = imax(p_quad->PrevLastQP, p_quad->CurrLastQP);
1825       if((p_Inp->PicInterlace==ADAPTIVE_CODING)||(p_Inp->MbInterlace))
1826         updateQPInterlace( p_quad, p_gen );
1827 
1828       if (p_Inp->HierarchicalCoding)
1829       {
1830         p_quad->m_Qc = prevQP + p_Vid->p_curr_frm_struct->layer;
1831       }
1832       else
1833         p_quad->m_Qc = prevQP + 2 - p_Vid->nal_reference_idc;
1834 
1835       p_quad->m_Qc = iClip3(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc); // Clipping
1836 
1837       return p_quad->m_Qc;
1838 
1839     }
1840     else if( p_Vid->type == P_SLICE )
1841     {
1842       if((p_gen->NumberofGOP==1)&&(p_quad->NumberofPPicture==0))
1843       {
1844         if((p_gen->FieldControl==0)||((p_gen->FieldControl==1) && (p_gen->NoGranularFieldRC==0)))
1845           return updateFirstP( p_Vid, p_Inp, p_quad, p_gen, topfield );
1846       }
1847       else
1848       {
1849         p_quad->m_X1=p_quad->Pm_X1;
1850         p_quad->m_X2=p_quad->Pm_X2;
1851         p_quad->MADPictureC1=p_quad->PMADPictureC1;
1852         p_quad->MADPictureC2=p_quad->PMADPictureC2;
1853 
1854         m_Qp=p_quad->Pm_Qp;
1855 
1856         if(p_gen->FieldControl==0)
1857           SumofBasicUnit=p_quad->TotalNumberofBasicUnit;
1858         else
1859           SumofBasicUnit=p_quad->TotalNumberofBasicUnit>>1;
1860 
1861         /*the average QP of the previous frame is used to coded the first basic unit of the current frame or field*/
1862         if(p_quad->NumberofBasicUnit==SumofBasicUnit)
1863           return updateFirstBU( p_Vid, p_Inp, p_quad, p_gen, topfield );
1864         else
1865         {
1866           /*compute the number of remaining bits*/
1867           p_quad->Target -= (p_gen->NumberofBasicUnitHeaderBits + p_gen->NumberofBasicUnitTextureBits);
1868           p_gen->NumberofBasicUnitHeaderBits  = 0;
1869           p_gen->NumberofBasicUnitTextureBits = 0;
1870           if(p_quad->Target<0)
1871             return updateNegativeTarget( p_Vid, p_Inp, p_quad, p_gen, topfield, m_Qp );
1872           else
1873           {
1874             /*predict the MAD of current picture*/
1875             predictCurrPicMAD( p_Inp, p_quad, p_gen );
1876 
1877             /*compute the total number of bits for the current basic unit*/
1878             updateModelQPBU( p_Vid, p_Inp, p_quad, m_Qp );
1879 
1880             p_quad->TotalFrameQP +=p_quad->m_Qc;
1881             p_quad->Pm_Qp=p_quad->m_Qc;
1882             p_quad->NumberofBasicUnit--;
1883             if((p_quad->NumberofBasicUnit==0) && p_Vid->type == P_SLICE )
1884               updateLastBU( p_Vid, p_Inp, p_quad, p_gen, topfield );
1885 
1886             return p_quad->m_Qc;
1887           }
1888         }
1889       }
1890     }
1891   }
1892   return p_quad->m_Qc;
1893 }
1894 
1895 /*!
1896  *************************************************************************************
1897  * \brief
1898  *    compute a  quantization parameter for each frame
1899  *
1900  *************************************************************************************
1901 */
updateQPRC3(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,RCGeneric * p_gen,int topfield)1902 int updateQPRC3(VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, RCGeneric *p_gen, int topfield)
1903 {
1904   int m_Bits;
1905   int SumofBasicUnit;
1906   int MaxQpChange, m_Qp, m_Hp;
1907 
1908   /* frame layer rate control */
1909   if( p_Vid->BasicUnit == p_Vid->FrameSizeInMbs || p_Vid->type != P_SLICE )
1910   {
1911     /* fixed quantization parameter is used to coded I frame, the first P frame and the first B frame
1912     the quantization parameter is adjusted according the available channel bandwidth and
1913     the type of video */
1914     /*top field*/
1915     if((topfield) || (p_gen->FieldControl==0))
1916     {
1917       if (p_Vid->number == 0)
1918       {
1919         if((p_Inp->PicInterlace == ADAPTIVE_CODING) || (p_Inp->MbInterlace))
1920           updateQPInterlace( p_quad, p_gen );
1921         p_quad->m_Qc = p_quad->MyInitialQp;
1922         return p_quad->m_Qc;
1923       }
1924       else if( p_Vid->type == P_SLICE && p_quad->NumberofPPicture == 0 )
1925       {
1926         p_quad->m_Qc=p_quad->MyInitialQp;
1927 
1928         if(p_gen->FieldControl==0)
1929           updateQPNonPicAFF( p_Vid->active_sps, p_quad );
1930         return p_quad->m_Qc;
1931       }
1932       else
1933       {
1934         if( ( (p_Vid->type == B_SLICE && (p_Vid->p_curr_frm_struct->layer && p_Vid->p_curr_frm_struct->atom_idx == 1)) || p_Vid->type == I_SLICE) && ((p_Inp->PicInterlace == ADAPTIVE_CODING) || (p_Inp->MbInterlace)) )
1935           updateQPInterlace( p_quad, p_gen );
1936         /*adaptive field/frame coding*/
1937         if( p_Vid->type == P_SLICE && ( p_Inp->PicInterlace == ADAPTIVE_CODING || p_Inp->MbInterlace ) && p_gen->FieldControl == 0 )
1938           updateQPInterlaceBU( p_quad, p_gen );
1939 
1940         p_quad->m_X1 = p_quad->Pm_X1;
1941         p_quad->m_X2 = p_quad->Pm_X2;
1942         p_quad->MADPictureC1 = p_quad->PMADPictureC1;
1943         p_quad->MADPictureC2 = p_quad->PMADPictureC2;
1944         p_quad->PreviousPictureMAD = p_quad->PPictureMAD[0];
1945 
1946         MaxQpChange = p_quad->PMaxQpChange;
1947         m_Qp = p_quad->Pm_Qp;
1948         m_Hp = p_quad->PPreHeader;
1949 
1950         if ( p_Vid->BasicUnit < p_Vid->FrameSizeInMbs && p_Vid->type != P_SLICE )
1951         {
1952           // when RC_MODE_3 is set and basic unit is smaller than a frame, note that:
1953           // the linear MAD model and the quadratic QP model operate on small units and not on a whole frame;
1954           // we therefore have to account for this
1955           p_quad->PreviousPictureMAD = p_quad->PreviousWholeFrameMAD;
1956         }
1957         if ( p_Vid->type == I_SLICE )
1958           m_Hp = 0; // it is usually a very small portion of the total I_SLICE bit budget
1959 
1960         /* predict the MAD of current picture*/
1961         p_quad->CurrentFrameMAD=p_quad->MADPictureC1*p_quad->PreviousPictureMAD + p_quad->MADPictureC2;
1962 
1963         /*compute the number of bits for the texture*/
1964         if(p_quad->Target < 0)
1965         {
1966           p_quad->m_Qc=m_Qp+MaxQpChange;
1967           p_quad->m_Qc = iClip3(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc); // Clipping
1968         }
1969         else
1970         {
1971           if ( p_Vid->type != P_SLICE )
1972           {
1973             if ( p_Vid->BasicUnit < p_Vid->FrameSizeInMbs )
1974               m_Bits =(p_quad->Target-m_Hp)/p_quad->TotalNumberofBasicUnit;
1975             else
1976               m_Bits =p_quad->Target-m_Hp;
1977           }
1978           else {
1979             m_Bits = p_quad->Target-m_Hp;
1980             m_Bits = imax(m_Bits, (int)(p_quad->bit_rate/(MINVALUE*p_quad->frame_rate)));
1981           }
1982           updateModelQPFrame( p_quad, m_Bits );
1983 
1984           p_quad->m_Qc = iClip3(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc); // clipping
1985           if ( p_Vid->type == P_SLICE )
1986             p_quad->m_Qc = iClip3(m_Qp-MaxQpChange, m_Qp+MaxQpChange, p_quad->m_Qc); // control variation
1987         }
1988 
1989         if( p_Vid->type == P_SLICE && p_gen->FieldControl == 0 )
1990           updateQPNonPicAFF( p_Vid->active_sps, p_quad );
1991 
1992         if ( p_Vid->type == B_SLICE )
1993         {
1994           // hierarchical adjustment
1995           int prevqp = ((p_quad->PrevLastQP+p_quad->CurrLastQP) >> 1) + 1;
1996           if ( p_Inp->HierarchicalCoding && p_Vid->p_curr_frm_struct->layer)
1997             p_quad->m_Qc -= (p_Vid->p_curr_frm_struct->p_atom->gop_levels - p_Vid->p_curr_frm_struct->layer);
1998           // check bounds
1999           p_quad->m_Qc = iClip3(prevqp - (p_Inp->HierarchicalCoding ? 0 : 5), prevqp + 5, p_quad->m_Qc); // control variation
2000           p_quad->m_Qc = iClip3(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc); // clipping
2001         }
2002         return p_quad->m_Qc;
2003       }
2004     }
2005     /*bottom field*/
2006     else
2007     {
2008       if( p_Vid->type==P_SLICE && p_gen->NoGranularFieldRC == 0 )
2009         updateBottomField( p_Inp, p_quad );
2010       return p_quad->m_Qc;
2011     }
2012   }
2013   /*basic unit layer rate control*/
2014   else
2015   {
2016     /*top field of I frame*/
2017     if (p_Vid->number == 0)
2018     {
2019       if((p_Inp->PicInterlace == ADAPTIVE_CODING) || (p_Inp->MbInterlace))
2020         updateQPInterlace( p_quad, p_gen );
2021       p_quad->m_Qc = p_quad->MyInitialQp;
2022       return p_quad->m_Qc;
2023     }
2024     else if( p_Vid->type == P_SLICE )
2025     {
2026       if((p_gen->NumberofGOP==1)&&(p_quad->NumberofPPicture==0))
2027       {
2028         if((p_gen->FieldControl==0)||((p_gen->FieldControl==1) && (p_gen->NoGranularFieldRC==0)))
2029           return updateFirstP( p_Vid, p_Inp, p_quad, p_gen, topfield );
2030       }
2031       else
2032       {
2033         if( ( (p_Vid->type == B_SLICE && (p_Vid->p_curr_frm_struct->layer && p_Vid->p_curr_frm_struct->atom_idx == 1)) || p_Vid->type == I_SLICE) && ((p_Inp->PicInterlace == ADAPTIVE_CODING) || (p_Inp->MbInterlace)) )
2034           updateQPInterlace( p_quad, p_gen );
2035         p_quad->m_X1=p_quad->Pm_X1;
2036         p_quad->m_X2=p_quad->Pm_X2;
2037         p_quad->MADPictureC1=p_quad->PMADPictureC1;
2038         p_quad->MADPictureC2=p_quad->PMADPictureC2;
2039 
2040         m_Qp=p_quad->Pm_Qp;
2041 
2042         if(p_gen->FieldControl==0)
2043           SumofBasicUnit=p_quad->TotalNumberofBasicUnit;
2044         else
2045           SumofBasicUnit=p_quad->TotalNumberofBasicUnit>>1;
2046 
2047         /*the average QP of the previous frame is used to coded the first basic unit of the current frame or field*/
2048         if(p_quad->NumberofBasicUnit==SumofBasicUnit)
2049           return updateFirstBU( p_Vid, p_Inp, p_quad, p_gen, topfield );
2050         else
2051         {
2052           /*compute the number of remaining bits*/
2053           p_quad->Target -= (p_gen->NumberofBasicUnitHeaderBits + p_gen->NumberofBasicUnitTextureBits);
2054           p_gen->NumberofBasicUnitHeaderBits  = 0;
2055           p_gen->NumberofBasicUnitTextureBits = 0;
2056           if(p_quad->Target<0)
2057             return updateNegativeTarget( p_Vid, p_Inp, p_quad, p_gen, topfield, m_Qp );
2058           else
2059           {
2060             /*predict the MAD of current picture*/
2061             predictCurrPicMAD( p_Inp, p_quad, p_gen );
2062 
2063             /*compute the total number of bits for the current basic unit*/
2064             updateModelQPBU( p_Vid, p_Inp, p_quad, m_Qp );
2065 
2066             p_quad->TotalFrameQP +=p_quad->m_Qc;
2067             p_quad->Pm_Qp=p_quad->m_Qc;
2068             p_quad->NumberofBasicUnit--;
2069             if((p_quad->NumberofBasicUnit==0) && p_Vid->type == P_SLICE )
2070               updateLastBU( p_Vid, p_Inp, p_quad, p_gen, topfield );
2071 
2072             return p_quad->m_Qc;
2073           }
2074         }
2075       }
2076     }
2077   }
2078   return p_quad->m_Qc;
2079 }
2080 
2081 /*!
2082  *************************************************************************************
2083  * \brief
2084  *    Save previous QP values for interlaced coding
2085  *
2086  *************************************************************************************
2087 */
updateQPInterlace(RCQuadratic * p_quad,RCGeneric * p_gen)2088 void updateQPInterlace( RCQuadratic *p_quad, RCGeneric *p_gen )
2089 {
2090   if(p_gen->FieldControl==0)
2091   {
2092     /*previous choice is frame coding*/
2093     if(p_gen->FieldFrame==1)
2094     {
2095       p_quad->PrevLastQP=p_quad->CurrLastQP;
2096       p_quad->CurrLastQP=p_quad->FrameQPBuffer;
2097     }
2098     /*previous choice is field coding*/
2099     else
2100     {
2101       p_quad->PrevLastQP=p_quad->CurrLastQP;
2102       p_quad->CurrLastQP=p_quad->FieldQPBuffer;
2103     }
2104   }
2105 }
2106 
2107 /*!
2108  *************************************************************************************
2109  * \brief
2110  *    Save previous QP values for the case of non-PicAFF
2111  *
2112  *************************************************************************************
2113 */
updateQPNonPicAFF(seq_parameter_set_rbsp_t * active_sps,RCQuadratic * p_quad)2114 void updateQPNonPicAFF( seq_parameter_set_rbsp_t *active_sps, RCQuadratic *p_quad )
2115 {
2116   if(active_sps->frame_mbs_only_flag)
2117   {
2118     p_quad->TotalQpforPPicture +=p_quad->m_Qc;
2119     p_quad->PrevLastQP=p_quad->CurrLastQP;
2120     p_quad->CurrLastQP=p_quad->m_Qc;
2121     p_quad->Pm_Qp=p_quad->m_Qc;
2122   }
2123   /*adaptive field/frame coding*/
2124   else
2125     p_quad->FrameQPBuffer=p_quad->m_Qc;
2126 }
2127 
2128 /*!
2129  *************************************************************************************
2130  * \brief
2131  *    Update QP values for bottom field in field coding
2132  *************************************************************************************
2133 */
updateBottomField(InputParameters * p_Inp,RCQuadratic * p_quad)2134 void updateBottomField( InputParameters *p_Inp, RCQuadratic *p_quad )
2135 {
2136   /*field coding*/
2137   if(p_Inp->PicInterlace==FIELD_CODING)
2138   {
2139     p_quad->TotalQpforPPicture +=p_quad->m_Qc;
2140     p_quad->PrevLastQP=p_quad->CurrLastQP+1;
2141     p_quad->CurrLastQP=p_quad->m_Qc;//+0 Recent change 13/1/2003
2142     p_quad->Pm_Qp=p_quad->m_Qc;
2143   }
2144   /*adaptive field/frame coding*/
2145   else
2146     p_quad->FieldQPBuffer=p_quad->m_Qc;
2147 }
2148 
2149 /*!
2150  *************************************************************************************
2151  * \brief
2152  *    update QP variables for P frames
2153  *************************************************************************************
2154 */
updateFirstP(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,RCGeneric * p_gen,int topfield)2155 int updateFirstP( VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, RCGeneric *p_gen, int topfield )
2156 {
2157 
2158   /*top field of the first P frame*/
2159   p_quad->m_Qc=p_quad->MyInitialQp;
2160   p_gen->NumberofBasicUnitHeaderBits=0;
2161   p_gen->NumberofBasicUnitTextureBits=0;
2162   p_quad->NumberofBasicUnit--;
2163   /*bottom field of the first P frame*/
2164   if((!topfield)&&(p_quad->NumberofBasicUnit==0))
2165   {
2166     /*frame coding or field coding*/
2167     if((p_Vid->active_sps->frame_mbs_only_flag)||(p_Inp->PicInterlace==FIELD_CODING))
2168     {
2169       p_quad->TotalQpforPPicture +=p_quad->m_Qc;
2170       p_quad->PrevLastQP=p_quad->CurrLastQP;
2171       p_quad->CurrLastQP=p_quad->m_Qc;
2172       p_quad->PAveFrameQP=p_quad->m_Qc;
2173       p_quad->PAveHeaderBits3=p_quad->PAveHeaderBits2;
2174     }
2175     /*adaptive frame/field coding*/
2176     else if((p_Inp->PicInterlace==ADAPTIVE_CODING)||(p_Inp->MbInterlace))
2177     {
2178       if(p_gen->FieldControl==0)
2179       {
2180         p_quad->FrameQPBuffer=p_quad->m_Qc;
2181         p_quad->FrameAveHeaderBits=p_quad->PAveHeaderBits2;
2182       }
2183       else
2184       {
2185         p_quad->FieldQPBuffer=p_quad->m_Qc;
2186         p_quad->FieldAveHeaderBits=p_quad->PAveHeaderBits2;
2187       }
2188     }
2189   }
2190   p_quad->Pm_Qp=p_quad->m_Qc;
2191   p_quad->TotalFrameQP +=p_quad->m_Qc;
2192   return p_quad->m_Qc;
2193 }
2194 
2195 /*!
2196  *************************************************************************************
2197  * \brief
2198  *    update QP when bit target is negative
2199  *************************************************************************************
2200 */
updateNegativeTarget(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,RCGeneric * p_gen,int topfield,int m_Qp)2201 int updateNegativeTarget( VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, RCGeneric *p_gen, int topfield, int m_Qp )
2202 {
2203   int PAverageQP;
2204 
2205   if(p_quad->GOPOverdue==TRUE)
2206     p_quad->m_Qc=m_Qp+2;
2207   else
2208     p_quad->m_Qc=m_Qp+p_quad->DDquant;//2
2209 
2210   p_quad->m_Qc = imin(p_quad->m_Qc, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale);  // clipping
2211   if(p_Inp->basicunit>=p_quad->MBPerRow)
2212     p_quad->m_Qc = imin(p_quad->m_Qc, p_quad->PAveFrameQP + 6);
2213   else
2214     p_quad->m_Qc = imin(p_quad->m_Qc, p_quad->PAveFrameQP + 3);
2215 
2216   p_quad->TotalFrameQP +=p_quad->m_Qc;
2217   p_quad->NumberofBasicUnit--;
2218   if(p_quad->NumberofBasicUnit==0)
2219   {
2220     if((!topfield)||(p_gen->FieldControl==0))
2221     {
2222       /*frame coding or field coding*/
2223       if((p_Vid->active_sps->frame_mbs_only_flag)||(p_Inp->PicInterlace==FIELD_CODING))
2224       {
2225         PAverageQP=(int)((double)p_quad->TotalFrameQP/(double)p_quad->TotalNumberofBasicUnit+0.5);
2226         if (p_quad->NumberofPPicture == (p_Inp->intra_period - 2))
2227           p_quad->QPLastPFrame = PAverageQP;
2228 
2229         p_quad->TotalQpforPPicture +=PAverageQP;
2230         if(p_quad->GOPOverdue==TRUE)
2231         {
2232           p_quad->PrevLastQP=p_quad->CurrLastQP+1;
2233           p_quad->CurrLastQP=PAverageQP;
2234         }
2235         else
2236         {
2237           if((p_quad->NumberofPPicture==0)&&(p_gen->NumberofGOP>1))
2238           {
2239             p_quad->PrevLastQP=p_quad->CurrLastQP;
2240             p_quad->CurrLastQP=PAverageQP;
2241           }
2242           else if(p_quad->NumberofPPicture>0)
2243           {
2244             p_quad->PrevLastQP=p_quad->CurrLastQP+1;
2245             p_quad->CurrLastQP=PAverageQP;
2246           }
2247         }
2248         p_quad->PAveFrameQP=PAverageQP;
2249         p_quad->PAveHeaderBits3=p_quad->PAveHeaderBits2;
2250       }
2251       /*adaptive field/frame coding*/
2252       else if((p_Inp->PicInterlace==ADAPTIVE_CODING)||(p_Inp->MbInterlace))
2253       {
2254         if(p_gen->FieldControl==0)
2255         {
2256           PAverageQP=(int)((double)p_quad->TotalFrameQP/(double)p_quad->TotalNumberofBasicUnit+0.5);
2257           p_quad->FrameQPBuffer=PAverageQP;
2258           p_quad->FrameAveHeaderBits=p_quad->PAveHeaderBits2;
2259         }
2260         else
2261         {
2262           PAverageQP=(int)((double)p_quad->TotalFrameQP/(double)p_quad->TotalNumberofBasicUnit+0.5);
2263           p_quad->FieldQPBuffer=PAverageQP;
2264           p_quad->FieldAveHeaderBits=p_quad->PAveHeaderBits2;
2265         }
2266       }
2267     }
2268   }
2269   if(p_quad->GOPOverdue==TRUE)
2270     p_quad->Pm_Qp=p_quad->PAveFrameQP;
2271   else
2272     p_quad->Pm_Qp=p_quad->m_Qc;
2273 
2274   return p_quad->m_Qc;
2275 }
2276 
2277 /*!
2278  *************************************************************************************
2279  * \brief
2280  *    update QP for the first Basic Unit in the picture
2281  *************************************************************************************
2282 */
updateFirstBU(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,RCGeneric * p_gen,int topfield)2283 int updateFirstBU( VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, RCGeneric *p_gen, int topfield )
2284 {
2285   /*adaptive field/frame coding*/
2286   if(((p_Inp->PicInterlace==ADAPTIVE_CODING)||(p_Inp->MbInterlace))&&(p_gen->FieldControl==0))
2287   {
2288     /*previous choice is frame coding*/
2289     if(p_gen->FieldFrame==1)
2290     {
2291       if(p_quad->NumberofPPicture>0)
2292         p_quad->TotalQpforPPicture +=p_quad->FrameQPBuffer;
2293       p_quad->PAveFrameQP=p_quad->FrameQPBuffer;
2294       p_quad->PAveHeaderBits3=p_quad->FrameAveHeaderBits;
2295     }
2296     /*previous choice is field coding*/
2297     else
2298     {
2299       if(p_quad->NumberofPPicture>0)
2300         p_quad->TotalQpforPPicture +=p_quad->FieldQPBuffer;
2301       p_quad->PAveFrameQP=p_quad->FieldQPBuffer;
2302       p_quad->PAveHeaderBits3=p_quad->FieldAveHeaderBits;
2303     }
2304   }
2305 
2306   if(p_quad->Target<=0)
2307   {
2308     p_quad->m_Qc = p_quad->PAveFrameQP + 2;
2309     if(p_quad->m_Qc > (p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale))
2310       p_quad->m_Qc = p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale;
2311 
2312     if(topfield||(p_gen->FieldControl==0))
2313       p_quad->GOPOverdue=TRUE;
2314   }
2315   else
2316   {
2317     p_quad->m_Qc=p_quad->PAveFrameQP;
2318   }
2319   p_quad->TotalFrameQP +=p_quad->m_Qc;
2320   p_quad->NumberofBasicUnit--;
2321   p_quad->Pm_Qp = p_quad->PAveFrameQP;
2322 
2323   return p_quad->m_Qc;
2324 }
2325 
2326 /*!
2327  *************************************************************************************
2328  * \brief
2329  *    update QP for the last Basic Unit in the picture
2330  *************************************************************************************
2331 */
updateLastBU(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,RCGeneric * p_gen,int topfield)2332 void updateLastBU( VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, RCGeneric *p_gen, int topfield )
2333 {
2334   int PAverageQP;
2335 
2336   if((!topfield)||(p_gen->FieldControl==0))
2337   {
2338     /*frame coding or field coding*/
2339     if((p_Vid->active_sps->frame_mbs_only_flag)||(p_Inp->PicInterlace==FIELD_CODING))
2340     {
2341       PAverageQP=(int)((double)p_quad->TotalFrameQP/(double) p_quad->TotalNumberofBasicUnit+0.5);
2342       if (p_quad->NumberofPPicture == (p_Inp->intra_period - 2))
2343         p_quad->QPLastPFrame = PAverageQP;
2344 
2345       p_quad->TotalQpforPPicture +=PAverageQP;
2346       p_quad->PrevLastQP=p_quad->CurrLastQP;
2347       p_quad->CurrLastQP=PAverageQP;
2348       p_quad->PAveFrameQP=PAverageQP;
2349       p_quad->PAveHeaderBits3=p_quad->PAveHeaderBits2;
2350     }
2351     else if((p_Inp->PicInterlace==ADAPTIVE_CODING)||(p_Inp->MbInterlace))
2352     {
2353       if(p_gen->FieldControl==0)
2354       {
2355         PAverageQP=(int)((double) p_quad->TotalFrameQP/(double)p_quad->TotalNumberofBasicUnit+0.5);
2356         p_quad->FrameQPBuffer=PAverageQP;
2357         p_quad->FrameAveHeaderBits=p_quad->PAveHeaderBits2;
2358       }
2359       else
2360       {
2361         PAverageQP=(int)((double) p_quad->TotalFrameQP/(double) p_quad->TotalNumberofBasicUnit+0.5);
2362         p_quad->FieldQPBuffer=PAverageQP;
2363         p_quad->FieldAveHeaderBits=p_quad->PAveHeaderBits2;
2364       }
2365     }
2366   }
2367 }
2368 
2369 /*!
2370  *************************************************************************************
2371  * \brief
2372  *    update current picture MAD
2373  *************************************************************************************
2374 */
predictCurrPicMAD(InputParameters * p_Inp,RCQuadratic * p_quad,RCGeneric * p_gen)2375 void predictCurrPicMAD( InputParameters *p_Inp, RCQuadratic *p_quad, RCGeneric *p_gen )
2376 {
2377   int i;
2378   if(((p_Inp->PicInterlace==ADAPTIVE_CODING)||(p_Inp->MbInterlace))&&(p_gen->FieldControl==1))
2379   {
2380     p_quad->CurrentFrameMAD=p_quad->MADPictureC1*p_quad->FCBUPFMAD[p_quad->TotalNumberofBasicUnit-p_quad->NumberofBasicUnit]+p_quad->MADPictureC2;
2381     p_quad->TotalBUMAD=0;
2382     for(i=p_quad->TotalNumberofBasicUnit-1; i>=(p_quad->TotalNumberofBasicUnit-p_quad->NumberofBasicUnit);i--)
2383     {
2384       p_quad->CurrentBUMAD=p_quad->MADPictureC1*p_quad->FCBUPFMAD[i]+p_quad->MADPictureC2;
2385       p_quad->TotalBUMAD +=p_quad->CurrentBUMAD*p_quad->CurrentBUMAD;
2386     }
2387   }
2388   else
2389   {
2390     p_quad->CurrentFrameMAD=p_quad->MADPictureC1*p_quad->BUPFMAD[p_quad->TotalNumberofBasicUnit-p_quad->NumberofBasicUnit]+p_quad->MADPictureC2;
2391     p_quad->TotalBUMAD=0;
2392     for(i=p_quad->TotalNumberofBasicUnit-1; i>=(p_quad->TotalNumberofBasicUnit-p_quad->NumberofBasicUnit);i--)
2393     {
2394       p_quad->CurrentBUMAD=p_quad->MADPictureC1*p_quad->BUPFMAD[i]+p_quad->MADPictureC2;
2395       p_quad->TotalBUMAD +=p_quad->CurrentBUMAD*p_quad->CurrentBUMAD;
2396     }
2397   }
2398 }
2399 
2400 /*!
2401  *************************************************************************************
2402  * \brief
2403  *    update QP using the quadratic model for basic unit coding
2404  *************************************************************************************
2405 */
updateModelQPBU(VideoParameters * p_Vid,InputParameters * p_Inp,RCQuadratic * p_quad,int m_Qp)2406 void updateModelQPBU( VideoParameters *p_Vid, InputParameters *p_Inp, RCQuadratic *p_quad, int m_Qp )
2407 {
2408   double dtmp, m_Qstep;
2409   int m_Bits;
2410   /*compute the total number of bits for the current basic unit*/
2411   m_Bits =(int)(p_quad->Target * p_quad->CurrentFrameMAD * p_quad->CurrentFrameMAD / p_quad->TotalBUMAD);
2412   /*compute the number of texture bits*/
2413   m_Bits -=p_quad->PAveHeaderBits2;
2414 
2415   m_Bits=imax(m_Bits,(int)(p_quad->bit_rate/(MINVALUE*p_quad->frame_rate*p_quad->TotalNumberofBasicUnit)));
2416 
2417   dtmp = p_quad->CurrentFrameMAD * p_quad->CurrentFrameMAD * p_quad->m_X1 * p_quad->m_X1 \
2418     + 4 * p_quad->m_X2 * p_quad->CurrentFrameMAD * m_Bits;
2419   if ((p_quad->m_X2 == 0.0) || (dtmp < 0) || ((sqrt (dtmp) - p_quad->m_X1 * p_quad->CurrentFrameMAD) <= 0.0))  // fall back 1st order mode
2420     m_Qstep = (float)(p_quad->m_X1 * p_quad->CurrentFrameMAD / (double) m_Bits);
2421   else // 2nd order mode
2422     m_Qstep = (float) ((2 * p_quad->m_X2 * p_quad->CurrentFrameMAD) / (sqrt (dtmp) - p_quad->m_X1 * p_quad->CurrentFrameMAD));
2423 
2424   p_quad->m_Qc = Qstep2QP(m_Qstep, p_quad->bitdepth_qp_scale);
2425   p_quad->m_Qc = imin(m_Qp+p_quad->DDquant,  p_quad->m_Qc); // control variation
2426 
2427   if(p_Inp->basicunit>=p_quad->MBPerRow)
2428     p_quad->m_Qc = imin(p_quad->PAveFrameQP+6, p_quad->m_Qc);
2429   else
2430     p_quad->m_Qc = imin(p_quad->PAveFrameQP+3, p_quad->m_Qc);
2431 
2432   p_quad->m_Qc = iClip3(m_Qp-p_quad->DDquant, p_Vid->RCMaxQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc); // clipping
2433   if(p_Inp->basicunit>=p_quad->MBPerRow)
2434     p_quad->m_Qc = imax(p_quad->PAveFrameQP-6, p_quad->m_Qc);
2435   else
2436     p_quad->m_Qc = imax(p_quad->PAveFrameQP-3, p_quad->m_Qc);
2437 
2438   p_quad->m_Qc = imax(p_Vid->RCMinQP + p_quad->bitdepth_qp_scale, p_quad->m_Qc);
2439 }
2440 
2441 /*!
2442  *************************************************************************************
2443  * \brief
2444  *    update QP variables for interlaced pictures and basic unit coding
2445  *************************************************************************************
2446 */
updateQPInterlaceBU(RCQuadratic * p_quad,RCGeneric * p_gen)2447 void updateQPInterlaceBU( RCQuadratic *p_quad, RCGeneric *p_gen )
2448 {
2449   /*previous choice is frame coding*/
2450   if(p_gen->FieldFrame==1)
2451   {
2452     p_quad->TotalQpforPPicture +=p_quad->FrameQPBuffer;
2453     p_quad->Pm_Qp=p_quad->FrameQPBuffer;
2454   }
2455   /*previous choice is field coding*/
2456   else
2457   {
2458     p_quad->TotalQpforPPicture +=p_quad->FieldQPBuffer;
2459     p_quad->Pm_Qp=p_quad->FieldQPBuffer;
2460   }
2461 }
2462 
2463 /*!
2464  *************************************************************************************
2465  * \brief
2466  *    update QP with quadratic model
2467  *************************************************************************************
2468 */
updateModelQPFrame(RCQuadratic * p_quad,int m_Bits)2469 void updateModelQPFrame( RCQuadratic *p_quad, int m_Bits )
2470 {
2471   double dtmp, m_Qstep;
2472 
2473   dtmp = p_quad->CurrentFrameMAD * p_quad->m_X1 * p_quad->CurrentFrameMAD * p_quad->m_X1
2474     + 4 * p_quad->m_X2 * p_quad->CurrentFrameMAD * m_Bits;
2475   if ((p_quad->m_X2 == 0.0) || (dtmp < 0) || ((sqrt (dtmp) - p_quad->m_X1 * p_quad->CurrentFrameMAD) <= 0.0)) // fall back 1st order mode
2476     m_Qstep = (float) (p_quad->m_X1 * p_quad->CurrentFrameMAD / (double) m_Bits);
2477   else // 2nd order mode
2478     m_Qstep = (float) ((2 * p_quad->m_X2 * p_quad->CurrentFrameMAD) / (sqrt (dtmp) - p_quad->m_X1 * p_quad->CurrentFrameMAD));
2479 
2480   p_quad->m_Qc = Qstep2QP(m_Qstep, p_quad->bitdepth_qp_scale);
2481 }
2482 
2483 /*!
2484  *************************************************************************************
2485  * \brief
2486  *    rate control at the MB level
2487  *************************************************************************************
2488 */
rc_handle_mb(Macroblock * currMB,int prev_mb)2489 int rc_handle_mb( Macroblock *currMB, int prev_mb )
2490 {
2491   VideoParameters *p_Vid = currMB->p_Vid;
2492   InputParameters *p_Inp = currMB->p_Inp;
2493   Macroblock     *prevMB = currMB->PrevMB;
2494   int mb_qp = p_Vid->qp;
2495   RCGeneric   *p_gen   = p_Vid->p_rc_gen;
2496   RCQuadratic *p_quad = p_Vid->p_rc_quad;
2497 
2498   if (prev_mb > -1)
2499   {
2500     if ( p_Inp->MbInterlace == ADAPTIVE_CODING && !p_Vid->bot_MB && currMB->mb_field )
2501       mb_qp = prevMB->qp;
2502   }
2503 
2504   // frame layer rate control
2505   if (p_Inp->basicunit != p_Vid->FrameSizeInMbs)
2506   {
2507     // each I or B frame has only one QP
2508     if ( ((p_Vid->type == I_SLICE || p_Vid->type == B_SLICE) && p_Inp->RCUpdateMode != RC_MODE_1 ) || !(p_Vid->number) )
2509     {
2510       return mb_qp;
2511     }
2512     else if ( p_Vid->type == P_SLICE || p_Inp->RCUpdateMode == RC_MODE_1 )
2513     {
2514       if (!p_Vid->write_macroblock) //write macroblock
2515       {
2516         if (prev_mb > -1)
2517         {
2518           if (!((p_Inp->MbInterlace) && p_Vid->bot_MB)) //top macroblock
2519           {
2520             if (prevMB->prev_cbp != 1)
2521             {
2522               mb_qp = prevMB->prev_qp;
2523             }
2524           }
2525         }
2526       }
2527 
2528       // compute the quantization parameter for each basic unit of P frame
2529 
2530       if (!p_Vid->write_macroblock)
2531       {
2532         if(!((p_Inp->MbInterlace) && p_Vid->bot_MB))
2533         {
2534           if(p_Inp->RCUpdateMode <= MAX_RC_MODE && (p_Vid->NumberofCodedMacroBlocks > 0) && (p_Vid->NumberofCodedMacroBlocks % p_Vid->BasicUnit == 0))
2535           {
2536             updateRCModel(p_Vid, p_Inp, p_quad, p_gen);
2537             // frame coding
2538             if(p_Vid->active_sps->frame_mbs_only_flag)
2539             {
2540               p_Vid->BasicUnitQP = p_Vid->updateQP(p_Vid, p_Inp, p_quad, p_gen, p_gen->TopFieldFlag) - p_quad->bitdepth_qp_scale;
2541             }
2542             // picture adaptive field/frame coding
2543             else if(p_Inp->MbInterlace || ((p_Inp->PicInterlace!=FRAME_CODING) && (p_gen->NoGranularFieldRC==0)))
2544             {
2545               p_Vid->BasicUnitQP = p_Vid->updateQP(p_Vid, p_Inp, p_quad, p_gen, p_gen->TopFieldFlag) - p_quad->bitdepth_qp_scale;
2546             }
2547           }
2548 
2549           if(p_Vid->current_mb_nr==0)
2550             p_Vid->BasicUnitQP = mb_qp;
2551 
2552 
2553           mb_qp = p_Vid->BasicUnitQP;
2554           mb_qp = iClip3(MIN_QP - p_Vid->bitdepth_luma_qp_scale, MAX_QP, mb_qp);
2555         }
2556       }
2557     }
2558   }
2559   return mb_qp;
2560 }
2561 
2562 /*!
2563  *************************************************************************************
2564  * \brief
2565  *    initialize rate control model for the top field
2566  *************************************************************************************
2567 */
rc_init_top_field(VideoParameters * p_Vid,InputParameters * p_Inp)2568 void rc_init_top_field ( VideoParameters *p_Vid, InputParameters *p_Inp )
2569 {
2570   RCGeneric   *p_gen   = p_Vid->p_rc_gen;
2571   RCQuadratic *p_quad = p_Vid->p_rc_quad;
2572 
2573   p_Vid->BasicUnit = p_Inp->basicunit;
2574   p_gen->TopFieldFlag = 1;
2575   p_Vid->rc_init_pict_ptr(p_Vid, p_Inp, p_quad, p_gen, 0, 1, (p_Inp->PicInterlace == FIELD_CODING), 1.0F);
2576   p_Vid->p_curr_frm_struct->qp = p_Vid->qp = p_Vid->updateQP(p_Vid, p_Inp, p_quad, p_gen, 1) - p_quad->bitdepth_qp_scale;
2577 }
2578 
2579 /*!
2580  *************************************************************************************
2581  * \brief
2582  *    initialize rate control model for the bottom field
2583  *************************************************************************************
2584 */
rc_init_bottom_field(VideoParameters * p_Vid,InputParameters * p_Inp,int TopFieldBits)2585 void rc_init_bottom_field ( VideoParameters *p_Vid, InputParameters *p_Inp, int TopFieldBits )
2586 {
2587   RCGeneric   *p_gen   = p_Vid->p_rc_gen;
2588   RCQuadratic *p_quad = p_Vid->p_rc_quad;
2589 
2590   p_quad->bits_topfield = TopFieldBits;
2591   p_gen->TopFieldFlag = 0;
2592   p_Vid->rc_init_pict_ptr(p_Vid, p_Inp, p_quad, p_gen, 0,0,0, 1.0F);
2593   p_Vid->p_curr_frm_struct->qp = p_Vid->qp = p_Vid->updateQP(p_Vid, p_Inp, p_quad, p_gen, 0) - p_quad->bitdepth_qp_scale;
2594 }
2595 
2596 /*!
2597  *************************************************************************************
2598  * \brief
2599  *    initialize rate control for RDPictureDecision
2600  *************************************************************************************
2601 */
rc_init_frame_rdpic(VideoParameters * p_Vid,InputParameters * p_Inp,float rateRatio)2602 void rc_init_frame_rdpic( VideoParameters *p_Vid, InputParameters *p_Inp, float rateRatio )
2603 {
2604   RCGeneric *p_gen = p_Vid->p_rc_gen;
2605   RCGeneric *p_gen_init = p_Vid->p_rc_gen_init;
2606   RCQuadratic *p_quad = p_Vid->p_rc_quad;
2607   RCQuadratic *p_quad_init = p_Vid->p_rc_quad_init;
2608 
2609   switch (p_Inp->RCUpdateMode)
2610   {
2611   case RC_MODE_0:  case RC_MODE_1:  case RC_MODE_2:  case RC_MODE_3:
2612     // re-store the initial RC model
2613     rc_copy_quadratic( p_Vid, p_Inp, p_quad, p_quad_init );
2614     rc_copy_generic( p_Vid, p_gen, p_gen_init );
2615     p_Vid->rc_init_pict_ptr(p_Vid, p_Inp, p_quad, p_gen, 1, 0, 1, rateRatio );
2616     p_Vid->p_curr_frm_struct->qp = p_Vid->qp = p_Vid->updateQP(p_Vid, p_Inp, p_quad, p_gen, 0) - p_quad->bitdepth_qp_scale;
2617     break;
2618   default:
2619     break;
2620   }
2621 }
2622 
2623 /*!
2624  *************************************************************************************
2625  * \brief
2626  *    allocate rate control memory
2627  *************************************************************************************
2628 */
rc_allocate_memory(VideoParameters * p_Vid,InputParameters * p_Inp)2629 void rc_allocate_memory( VideoParameters *p_Vid, InputParameters *p_Inp )
2630 {
2631   switch (p_Inp->RCUpdateMode)
2632   {
2633   case RC_MODE_0:
2634   case RC_MODE_1:
2635   case RC_MODE_2:
2636   case RC_MODE_3:
2637     rc_alloc_generic( p_Vid, &p_Vid->p_rc_gen );
2638     rc_alloc_quadratic( p_Vid, p_Inp, &p_Vid->p_rc_quad );
2639 
2640     if ( p_Inp->RDPictureDecision || p_Inp->MbInterlace == ADAPTIVE_CODING || p_Inp->PicInterlace == ADAPTIVE_CODING )
2641     {
2642       rc_alloc_generic( p_Vid, &p_Vid->p_rc_gen_init );
2643       rc_alloc_quadratic( p_Vid, p_Inp, &p_Vid->p_rc_quad_init );
2644       rc_alloc_generic( p_Vid, &p_Vid->p_rc_gen_best );
2645       rc_alloc_quadratic( p_Vid, p_Inp, &p_Vid->p_rc_quad_best );
2646     }
2647     break;
2648   default:
2649     break;
2650   }
2651 }
2652 
2653 /*!
2654  *************************************************************************************
2655  * \brief
2656  *    free rate control memory
2657  *************************************************************************************
2658 */
rc_free_memory(VideoParameters * p_Vid,InputParameters * p_Inp)2659 void rc_free_memory( VideoParameters *p_Vid, InputParameters *p_Inp )
2660 {
2661   switch (p_Inp->RCUpdateMode)
2662   {
2663   case RC_MODE_0:
2664   case RC_MODE_1:
2665   case RC_MODE_2:
2666   case RC_MODE_3:
2667     rc_free_generic( &p_Vid->p_rc_gen );
2668     rc_free_quadratic( &p_Vid->p_rc_quad );
2669 
2670     if ( p_Inp->RDPictureDecision || p_Inp->MbInterlace == ADAPTIVE_CODING || p_Inp->PicInterlace == ADAPTIVE_CODING )
2671     {
2672       rc_free_generic( &p_Vid->p_rc_gen_init );
2673       rc_free_quadratic( &p_Vid->p_rc_quad_init );
2674       rc_free_generic( &p_Vid->p_rc_gen_best );
2675       rc_free_quadratic( &p_Vid->p_rc_quad_best );
2676     }
2677     break;
2678   default:
2679     break;
2680   }
2681 }
2682 
2683 /*!
2684  *************************************************************************************
2685  * \brief
2686  *    update coding statistics after MB coding
2687  *************************************************************************************
2688 */
rc_update_mb_stats(Macroblock * currMB)2689 void rc_update_mb_stats(Macroblock *currMB)
2690 {
2691   VideoParameters *p_Vid = currMB->p_Vid;
2692   InputParameters *p_Inp = currMB->p_Inp;
2693   BitCounter *mbBits = &currMB->bits;
2694   RCGeneric *p_gen = p_Vid->p_rc_gen;
2695 
2696   // Rate control
2697   p_Vid->NumberofMBHeaderBits = mbBits->mb_mode + mbBits->mb_inter
2698                             + mbBits->mb_cbp + mbBits->mb_delta_quant;
2699   p_Vid->NumberofMBTextureBits = mbBits->mb_y_coeff + mbBits->mb_uv_coeff;
2700 
2701   switch (p_Inp->RCUpdateMode)
2702   {
2703   case RC_MODE_0:  case RC_MODE_1:  case RC_MODE_2:  case RC_MODE_3:
2704     p_gen->NumberofTextureBits += p_Vid->NumberofMBTextureBits;
2705     p_gen->NumberofHeaderBits  += p_Vid->NumberofMBHeaderBits;
2706     // basic unit layer rate control
2707     if(p_Vid->BasicUnit < p_Vid->FrameSizeInMbs)
2708     {
2709       p_gen->NumberofBasicUnitHeaderBits  += p_Vid->NumberofMBHeaderBits;
2710       p_gen->NumberofBasicUnitTextureBits += p_Vid->NumberofMBTextureBits;
2711     }
2712     break;
2713   default:
2714     break;
2715   }
2716 }
2717 
2718 /*!
2719  *************************************************************************************
2720  * \brief
2721  *    save state of rate control model
2722  *************************************************************************************
2723 */
rc_save_state(VideoParameters * p_Vid,InputParameters * p_Inp)2724 void rc_save_state( VideoParameters *p_Vid, InputParameters *p_Inp )
2725 {
2726   switch (p_Inp->RCUpdateMode)
2727   {
2728   case RC_MODE_0:  case RC_MODE_1:  case RC_MODE_2:  case RC_MODE_3:
2729     rc_copy_quadratic( p_Vid, p_Inp, p_Vid->p_rc_quad_best, p_Vid->p_rc_quad );
2730     rc_copy_generic( p_Vid, p_Vid->p_rc_gen_best, p_Vid->p_rc_gen );
2731     break;
2732   default:
2733     break;
2734   }
2735 }
2736 
2737 /*!
2738  *************************************************************************************
2739  * \brief
2740  *    restore state of rate control model
2741  *************************************************************************************
2742 */
rc_restore_state(VideoParameters * p_Vid,InputParameters * p_Inp)2743 void rc_restore_state( VideoParameters *p_Vid, InputParameters *p_Inp )
2744 {
2745   switch (p_Inp->RCUpdateMode)
2746   {
2747   case RC_MODE_0:  case RC_MODE_1:  case RC_MODE_2:  case RC_MODE_3:
2748     rc_copy_quadratic( p_Vid, p_Inp, p_Vid->p_rc_quad, p_Vid->p_rc_quad_best );
2749     rc_copy_generic( p_Vid, p_Vid->p_rc_gen, p_Vid->p_rc_gen_best );
2750     break;
2751   default:
2752     break;
2753   }
2754 }
2755