source: 3DVCSoftware/trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp @ 872

Last change on this file since 872 was 872, checked in by tech, 10 years ago

Merged HTM-10.0-dev0@871. (MV-HEVC 7 HLS)

File size: 44.0 KB
Line 
1/* The copyright in this software is being made available under the BSD
2 * License, included below. This software may be subject to other third party
3 * and contributor rights, including patent rights, and no such rights are
4 * granted under this license. 
5 *
6* Copyright (c) 2010-2014, ITU/ISO/IEC
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
11 *
12 *  * Redistributions of source code must retain the above copyright notice,
13 *    this list of conditions and the following disclaimer.
14 *  * Redistributions in binary form must reproduce the above copyright notice,
15 *    this list of conditions and the following disclaimer in the documentation
16 *    and/or other materials provided with the distribution.
17 *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
18 *    be used to endorse or promote products derived from this software without
19 *    specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31 * THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34/** \file     TEncRateCtrl.cpp
35    \brief    Rate control manager class
36*/
37#include "TEncRateCtrl.h"
38#include "../TLibCommon/TComPic.h"
39
40#include <cmath>
41
42using namespace std;
43
44//sequence level
45TEncRCSeq::TEncRCSeq()
46{
47  m_totalFrames         = 0;
48  m_targetRate          = 0;
49  m_frameRate           = 0;
50  m_targetBits          = 0;
51  m_GOPSize             = 0;
52  m_picWidth            = 0;
53  m_picHeight           = 0;
54  m_LCUWidth            = 0;
55  m_LCUHeight           = 0;
56  m_numberOfLevel       = 0;
57  m_numberOfLCU         = 0;
58  m_averageBits         = 0;
59  m_bitsRatio           = NULL;
60  m_GOPID2Level         = NULL;
61  m_picPara             = NULL;
62  m_LCUPara             = NULL;
63  m_numberOfPixel       = 0;
64  m_framesLeft          = 0;
65  m_bitsLeft            = 0;
66  m_useLCUSeparateModel = false;
67  m_adaptiveBit         = 0;
68  m_lastLambda          = 0.0;
69}
70
71TEncRCSeq::~TEncRCSeq()
72{
73  destroy();
74}
75
76Void TEncRCSeq::create( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int numberOfLevel, Bool useLCUSeparateModel, Int adaptiveBit )
77{
78  destroy();
79  m_totalFrames         = totalFrames;
80  m_targetRate          = targetBitrate;
81  m_frameRate           = frameRate;
82  m_GOPSize             = GOPSize;
83  m_picWidth            = picWidth;
84  m_picHeight           = picHeight;
85  m_LCUWidth            = LCUWidth;
86  m_LCUHeight           = LCUHeight;
87  m_numberOfLevel       = numberOfLevel;
88  m_useLCUSeparateModel = useLCUSeparateModel;
89
90  m_numberOfPixel   = m_picWidth * m_picHeight;
91  m_targetBits      = (Int64)m_totalFrames * (Int64)m_targetRate / (Int64)m_frameRate;
92  m_seqTargetBpp = (Double)m_targetRate / (Double)m_frameRate / (Double)m_numberOfPixel;
93  if ( m_seqTargetBpp < 0.03 )
94  {
95    m_alphaUpdate = 0.01;
96    m_betaUpdate  = 0.005;
97  }
98  else if ( m_seqTargetBpp < 0.08 )
99  {
100    m_alphaUpdate = 0.05;
101    m_betaUpdate  = 0.025;
102  }
103  else if ( m_seqTargetBpp < 0.2 )
104  {
105    m_alphaUpdate = 0.1;
106    m_betaUpdate  = 0.05;
107  }
108  else if ( m_seqTargetBpp < 0.5 )
109  {
110    m_alphaUpdate = 0.2;
111    m_betaUpdate  = 0.1;
112  }
113  else
114  {
115    m_alphaUpdate = 0.4;
116    m_betaUpdate  = 0.2;
117  }
118  m_averageBits     = (Int)(m_targetBits / totalFrames);
119  Int picWidthInBU  = ( m_picWidth  % m_LCUWidth  ) == 0 ? m_picWidth  / m_LCUWidth  : m_picWidth  / m_LCUWidth  + 1;
120  Int picHeightInBU = ( m_picHeight % m_LCUHeight ) == 0 ? m_picHeight / m_LCUHeight : m_picHeight / m_LCUHeight + 1;
121  m_numberOfLCU     = picWidthInBU * picHeightInBU;
122
123  m_bitsRatio   = new Int[m_GOPSize];
124  for ( Int i=0; i<m_GOPSize; i++ )
125  {
126    m_bitsRatio[i] = 1;
127  }
128
129  m_GOPID2Level = new Int[m_GOPSize];
130  for ( Int i=0; i<m_GOPSize; i++ )
131  {
132    m_GOPID2Level[i] = 1;
133  }
134
135  m_picPara = new TRCParameter[m_numberOfLevel];
136  for ( Int i=0; i<m_numberOfLevel; i++ )
137  {
138    m_picPara[i].m_alpha = 0.0;
139    m_picPara[i].m_beta  = 0.0;
140  }
141
142  if ( m_useLCUSeparateModel )
143  {
144    m_LCUPara = new TRCParameter*[m_numberOfLevel];
145    for ( Int i=0; i<m_numberOfLevel; i++ )
146    {
147      m_LCUPara[i] = new TRCParameter[m_numberOfLCU];
148      for ( Int j=0; j<m_numberOfLCU; j++)
149      {
150        m_LCUPara[i][j].m_alpha = 0.0;
151        m_LCUPara[i][j].m_beta  = 0.0;
152      }
153    }
154  }
155
156  m_framesLeft = m_totalFrames;
157  m_bitsLeft   = m_targetBits;
158  m_adaptiveBit = adaptiveBit;
159  m_lastLambda = 0.0;
160}
161
162Void TEncRCSeq::destroy()
163{
164  if (m_bitsRatio != NULL)
165  {
166    delete[] m_bitsRatio;
167    m_bitsRatio = NULL;
168  }
169
170  if ( m_GOPID2Level != NULL )
171  {
172    delete[] m_GOPID2Level;
173    m_GOPID2Level = NULL;
174  }
175
176  if ( m_picPara != NULL )
177  {
178    delete[] m_picPara;
179    m_picPara = NULL;
180  }
181
182  if ( m_LCUPara != NULL )
183  {
184    for ( Int i=0; i<m_numberOfLevel; i++ )
185    {
186      delete[] m_LCUPara[i];
187    }
188    delete[] m_LCUPara;
189    m_LCUPara = NULL;
190  }
191}
192
193Void TEncRCSeq::initBitsRatio( Int bitsRatio[])
194{
195  for (Int i=0; i<m_GOPSize; i++)
196  {
197    m_bitsRatio[i] = bitsRatio[i];
198  }
199}
200
201Void TEncRCSeq::initGOPID2Level( Int GOPID2Level[] )
202{
203  for ( Int i=0; i<m_GOPSize; i++ )
204  {
205    m_GOPID2Level[i] = GOPID2Level[i];
206  }
207}
208
209Void TEncRCSeq::initPicPara( TRCParameter* picPara )
210{
211  assert( m_picPara != NULL );
212
213  if ( picPara == NULL )
214  {
215    for ( Int i=0; i<m_numberOfLevel; i++ )
216    {
217      if (i>0)
218      {
219        m_picPara[i].m_alpha = 3.2003;
220        m_picPara[i].m_beta  = -1.367;
221      }
222      else
223      {
224        m_picPara[i].m_alpha = ALPHA;   
225        m_picPara[i].m_beta  = BETA2;
226      }
227    }
228  }
229  else
230  {
231    for ( Int i=0; i<m_numberOfLevel; i++ )
232    {
233      m_picPara[i] = picPara[i];
234    }
235  }
236}
237
238Void TEncRCSeq::initLCUPara( TRCParameter** LCUPara )
239{
240  if ( m_LCUPara == NULL )
241  {
242    return;
243  }
244  if ( LCUPara == NULL )
245  {
246    for ( Int i=0; i<m_numberOfLevel; i++ )
247    {
248      for ( Int j=0; j<m_numberOfLCU; j++)
249      {
250        m_LCUPara[i][j].m_alpha = m_picPara[i].m_alpha;
251        m_LCUPara[i][j].m_beta  = m_picPara[i].m_beta;
252      }
253    }
254  }
255  else
256  {
257    for ( Int i=0; i<m_numberOfLevel; i++ )
258    {
259      for ( Int j=0; j<m_numberOfLCU; j++)
260      {
261        m_LCUPara[i][j] = LCUPara[i][j];
262      }
263    }
264  }
265}
266
267Void TEncRCSeq::updateAfterPic ( Int bits )
268{
269  m_bitsLeft -= bits;
270  m_framesLeft--;
271}
272
273Void TEncRCSeq::setAllBitRatio( Double basicLambda, Double* equaCoeffA, Double* equaCoeffB )
274{
275  Int* bitsRatio = new Int[m_GOPSize];
276  for ( Int i=0; i<m_GOPSize; i++ )
277  {
278    bitsRatio[i] = (Int)( equaCoeffA[i] * pow( basicLambda, equaCoeffB[i] ) * m_numberOfPixel );
279  }
280  initBitsRatio( bitsRatio );
281  delete[] bitsRatio;
282}
283
284//GOP level
285TEncRCGOP::TEncRCGOP()
286{
287  m_encRCSeq  = NULL;
288  m_picTargetBitInGOP = NULL;
289  m_numPic     = 0;
290  m_targetBits = 0;
291  m_picLeft    = 0;
292  m_bitsLeft   = 0;
293}
294
295TEncRCGOP::~TEncRCGOP()
296{
297  destroy();
298}
299
300Void TEncRCGOP::create( TEncRCSeq* encRCSeq, Int numPic )
301{
302  destroy();
303  Int targetBits = xEstGOPTargetBits( encRCSeq, numPic );
304
305  if ( encRCSeq->getAdaptiveBits() > 0 && encRCSeq->getLastLambda() > 0.1 )
306  {
307    Double targetBpp = (Double)targetBits / encRCSeq->getNumPixel();
308    Double basicLambda = 0.0;
309    Double* lambdaRatio = new Double[encRCSeq->getGOPSize()];
310    Double* equaCoeffA = new Double[encRCSeq->getGOPSize()];
311    Double* equaCoeffB = new Double[encRCSeq->getGOPSize()];
312
313    if ( encRCSeq->getAdaptiveBits() == 1 )   // for GOP size =4, low delay case
314    {
315      if ( encRCSeq->getLastLambda() < 120.0 )
316      {
317        lambdaRatio[1] = 0.725 * log( encRCSeq->getLastLambda() ) + 0.5793;
318        lambdaRatio[0] = 1.3 * lambdaRatio[1];
319        lambdaRatio[2] = 1.3 * lambdaRatio[1];
320        lambdaRatio[3] = 1.0;
321      }
322      else
323      {
324        lambdaRatio[0] = 5.0;
325        lambdaRatio[1] = 4.0;
326        lambdaRatio[2] = 5.0;
327        lambdaRatio[3] = 1.0;
328      }
329    }
330    else if ( encRCSeq->getAdaptiveBits() == 2 )  // for GOP size = 8, random access case
331    {
332      if ( encRCSeq->getLastLambda() < 90.0 )
333      {
334        lambdaRatio[0] = 1.0;
335        lambdaRatio[1] = 0.725 * log( encRCSeq->getLastLambda() ) + 0.7963;
336        lambdaRatio[2] = 1.3 * lambdaRatio[1];
337        lambdaRatio[3] = 3.25 * lambdaRatio[1];
338        lambdaRatio[4] = 3.25 * lambdaRatio[1];
339        lambdaRatio[5] = 1.3  * lambdaRatio[1];
340        lambdaRatio[6] = 3.25 * lambdaRatio[1];
341        lambdaRatio[7] = 3.25 * lambdaRatio[1];
342      }
343      else
344      {
345        lambdaRatio[0] = 1.0;
346        lambdaRatio[1] = 4.0;
347        lambdaRatio[2] = 5.0;
348        lambdaRatio[3] = 12.3;
349        lambdaRatio[4] = 12.3;
350        lambdaRatio[5] = 5.0;
351        lambdaRatio[6] = 12.3;
352        lambdaRatio[7] = 12.3;
353      }
354    }
355
356    xCalEquaCoeff( encRCSeq, lambdaRatio, equaCoeffA, equaCoeffB, encRCSeq->getGOPSize() );
357    basicLambda = xSolveEqua( targetBpp, equaCoeffA, equaCoeffB, encRCSeq->getGOPSize() );
358    encRCSeq->setAllBitRatio( basicLambda, equaCoeffA, equaCoeffB );
359
360    delete []lambdaRatio;
361    delete []equaCoeffA;
362    delete []equaCoeffB;
363  }
364
365  m_picTargetBitInGOP = new Int[numPic];
366  Int i;
367  Int totalPicRatio = 0;
368  Int currPicRatio = 0;
369  for ( i=0; i<numPic; i++ )
370  {
371    totalPicRatio += encRCSeq->getBitRatio( i );
372  }
373  for ( i=0; i<numPic; i++ )
374  {
375    currPicRatio = encRCSeq->getBitRatio( i );
376    m_picTargetBitInGOP[i] = (Int)( ((Double)targetBits) * currPicRatio / totalPicRatio );
377  }
378
379  m_encRCSeq    = encRCSeq;
380  m_numPic       = numPic;
381  m_targetBits   = targetBits;
382  m_picLeft      = m_numPic;
383  m_bitsLeft     = m_targetBits;
384}
385
386Void TEncRCGOP::xCalEquaCoeff( TEncRCSeq* encRCSeq, Double* lambdaRatio, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize )
387{
388  for ( Int i=0; i<GOPSize; i++ )
389  {
390    Int frameLevel = encRCSeq->getGOPID2Level(i);
391    Double alpha   = encRCSeq->getPicPara(frameLevel).m_alpha;
392    Double beta    = encRCSeq->getPicPara(frameLevel).m_beta;
393    equaCoeffA[i] = pow( 1.0/alpha, 1.0/beta ) * pow( lambdaRatio[i], 1.0/beta );
394    equaCoeffB[i] = 1.0/beta;
395  }
396}
397
398Double TEncRCGOP::xSolveEqua( Double targetBpp, Double* equaCoeffA, Double* equaCoeffB, Int GOPSize )
399{
400  Double solution = 100.0;
401  Double minNumber = 0.1;
402  Double maxNumber = 10000.0;
403  for ( Int i=0; i<g_RCIterationNum; i++ )
404  { 
405    Double fx = 0.0;
406    for ( Int j=0; j<GOPSize; j++ )
407    {
408      fx += equaCoeffA[j] * pow( solution, equaCoeffB[j] );
409    }
410
411    if ( fabs( fx - targetBpp ) < 0.000001 )
412    {
413      break;
414    }
415
416    if ( fx > targetBpp )
417    {
418      minNumber = solution;
419      solution = ( solution + maxNumber ) / 2.0;
420    }
421    else
422    {
423      maxNumber = solution;
424      solution = ( solution + minNumber ) / 2.0;
425    }
426  }
427
428  solution = Clip3( 0.1, 10000.0, solution );
429  return solution;
430}
431
432Void TEncRCGOP::destroy()
433{
434  m_encRCSeq = NULL;
435  if ( m_picTargetBitInGOP != NULL )
436  {
437    delete[] m_picTargetBitInGOP;
438    m_picTargetBitInGOP = NULL;
439  }
440}
441
442Void TEncRCGOP::updateAfterPicture( Int bitsCost )
443{
444  m_bitsLeft -= bitsCost;
445  m_picLeft--;
446}
447
448Int TEncRCGOP::xEstGOPTargetBits( TEncRCSeq* encRCSeq, Int GOPSize )
449{
450  Int realInfluencePicture = min( g_RCSmoothWindowSize, encRCSeq->getFramesLeft() );
451  Int averageTargetBitsPerPic = (Int)( encRCSeq->getTargetBits() / encRCSeq->getTotalFrames() );
452  Int currentTargetBitsPerPic = (Int)( ( encRCSeq->getBitsLeft() - averageTargetBitsPerPic * (encRCSeq->getFramesLeft() - realInfluencePicture) ) / realInfluencePicture );
453  Int targetBits = currentTargetBitsPerPic * GOPSize;
454
455  if ( targetBits < 200 )
456  {
457    targetBits = 200;   // at least allocate 200 bits for one GOP
458  }
459
460  return targetBits;
461}
462
463//picture level
464TEncRCPic::TEncRCPic()
465{
466  m_encRCSeq = NULL;
467  m_encRCGOP = NULL;
468
469  m_frameLevel    = 0;
470  m_numberOfPixel = 0;
471  m_numberOfLCU   = 0;
472  m_targetBits    = 0;
473  m_estHeaderBits = 0;
474  m_estPicQP      = 0;
475  m_estPicLambda  = 0.0;
476
477  m_LCULeft       = 0;
478  m_bitsLeft      = 0;
479  m_pixelsLeft    = 0;
480
481  m_LCUs         = NULL;
482#if KWU_RC_MADPRED_E0227
483  m_lastIVPicture = NULL;
484#endif
485
486  m_picActualHeaderBits = 0;
487  m_picActualBits       = 0;
488  m_picQP               = 0;
489  m_picLambda           = 0.0;
490
491#if KWU_RC_MADPRED_E0227
492  m_IVtotalMAD            = 0.0;
493#endif
494}
495
496TEncRCPic::~TEncRCPic()
497{
498  destroy();
499}
500
501Int TEncRCPic::xEstPicTargetBits( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP )
502{
503  Int targetBits        = 0;
504  Int GOPbitsLeft       = encRCGOP->getBitsLeft();
505
506  Int i;
507  Int currPicPosition = encRCGOP->getNumPic()-encRCGOP->getPicLeft();
508  Int currPicRatio    = encRCSeq->getBitRatio( currPicPosition );
509  Int totalPicRatio   = 0;
510  for ( i=currPicPosition; i<encRCGOP->getNumPic(); i++ )
511  {
512    totalPicRatio += encRCSeq->getBitRatio( i );
513  }
514
515  targetBits  = Int( ((Double)GOPbitsLeft) * currPicRatio / totalPicRatio );
516
517  if ( targetBits < 100 )
518  {
519    targetBits = 100;   // at least allocate 100 bits for one picture
520  }
521
522  if ( m_encRCSeq->getFramesLeft() > 16 )
523  {
524    targetBits = Int( g_RCWeightPicRargetBitInBuffer * targetBits + g_RCWeightPicTargetBitInGOP * m_encRCGOP->getTargetBitInGOP( currPicPosition ) );
525  }
526
527  return targetBits;
528}
529
530Int TEncRCPic::xEstPicHeaderBits( list<TEncRCPic*>& listPreviousPictures, Int frameLevel )
531{
532  Int numPreviousPics   = 0;
533  Int totalPreviousBits = 0;
534
535  list<TEncRCPic*>::iterator it;
536  for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ )
537  {
538    if ( (*it)->getFrameLevel() == frameLevel )
539    {
540      totalPreviousBits += (*it)->getPicActualHeaderBits();
541      numPreviousPics++;
542    }
543  }
544
545  Int estHeaderBits = 0;
546  if ( numPreviousPics > 0 )
547  {
548    estHeaderBits = totalPreviousBits / numPreviousPics;
549  }
550
551  return estHeaderBits;
552}
553
554Void TEncRCPic::addToPictureLsit( list<TEncRCPic*>& listPreviousPictures )
555{
556  if ( listPreviousPictures.size() > g_RCMaxPicListSize )
557  {
558    TEncRCPic* p = listPreviousPictures.front();
559    listPreviousPictures.pop_front();
560    p->destroy();
561    delete p;
562  }
563
564  listPreviousPictures.push_back( this );
565}
566
567#if KWU_RC_MADPRED_E0227
568Void TEncRCPic::addToPictureLsitIV( list<TEncRCPic*>& listPreviousPictures )
569{
570  m_lastIVPicture = NULL;
571  m_lastIVPicture = this;
572}
573
574Void TEncRCPic::setIVPic( TEncRCPic* BaseRCPic )
575{
576  m_lastIVPicture = BaseRCPic;
577}
578#endif
579
580#if KWU_RC_MADPRED_E0227
581Void TEncRCPic::create( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP, Int frameLevel, list<TEncRCPic*>& listPreviousPictures, Int layerID )
582#else
583Void TEncRCPic::create( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP, Int frameLevel, list<TEncRCPic*>& listPreviousPictures )
584#endif
585{
586  destroy();
587  m_encRCSeq = encRCSeq;
588  m_encRCGOP = encRCGOP;
589
590  Int targetBits    = xEstPicTargetBits( encRCSeq, encRCGOP );
591  Int estHeaderBits = xEstPicHeaderBits( listPreviousPictures, frameLevel );
592
593  if ( targetBits < estHeaderBits + 100 )
594  {
595    targetBits = estHeaderBits + 100;   // at least allocate 100 bits for picture data
596  }
597
598  m_frameLevel       = frameLevel;
599  m_numberOfPixel    = encRCSeq->getNumPixel();
600  m_numberOfLCU      = encRCSeq->getNumberOfLCU();
601  m_estPicLambda     = 100.0;
602  m_targetBits       = targetBits;
603  m_estHeaderBits    = estHeaderBits;
604  m_bitsLeft         = m_targetBits;
605  Int picWidth       = encRCSeq->getPicWidth();
606  Int picHeight      = encRCSeq->getPicHeight();
607  Int LCUWidth       = encRCSeq->getLCUWidth();
608  Int LCUHeight      = encRCSeq->getLCUHeight();
609  Int picWidthInLCU  = ( picWidth  % LCUWidth  ) == 0 ? picWidth  / LCUWidth  : picWidth  / LCUWidth  + 1;
610  Int picHeightInLCU = ( picHeight % LCUHeight ) == 0 ? picHeight / LCUHeight : picHeight / LCUHeight + 1;
611
612  m_LCULeft         = m_numberOfLCU;
613  m_bitsLeft       -= m_estHeaderBits;
614  m_pixelsLeft      = m_numberOfPixel;
615
616  m_LCUs           = new TRCLCU[m_numberOfLCU];
617  Int i, j;
618  Int LCUIdx;
619  for ( i=0; i<picWidthInLCU; i++ )
620  {
621    for ( j=0; j<picHeightInLCU; j++ )
622    {
623      LCUIdx = j*picWidthInLCU + i;
624      m_LCUs[LCUIdx].m_actualBits = 0;
625      m_LCUs[LCUIdx].m_QP         = 0;
626      m_LCUs[LCUIdx].m_lambda     = 0.0;
627      m_LCUs[LCUIdx].m_targetBits = 0;
628      m_LCUs[LCUIdx].m_bitWeight  = 1.0;
629      Int currWidth  = ( (i == picWidthInLCU -1) ? picWidth  - LCUWidth *(picWidthInLCU -1) : LCUWidth  );
630      Int currHeight = ( (j == picHeightInLCU-1) ? picHeight - LCUHeight*(picHeightInLCU-1) : LCUHeight );
631      m_LCUs[LCUIdx].m_numberOfPixel = currWidth * currHeight;
632
633#if KWU_RC_MADPRED_E0227
634      m_LCUs[LCUIdx].m_CUWidth = currWidth;
635      m_LCUs[LCUIdx].m_CUHeight = currHeight;
636      m_LCUs[LCUIdx].m_IVMAD = -1.0;
637#endif
638    }
639  }
640  m_picActualHeaderBits = 0;
641  m_picActualBits       = 0;
642  m_picQP               = 0;
643  m_picLambda           = 0.0;
644
645
646#if KWU_RC_MADPRED_E0227
647  m_LayerID = layerID;
648  m_lastIVPicture = NULL;
649  m_IVtotalMAD            = 0.0;
650#endif
651
652
653#if KWU_RC_MADPRED_E0227
654  list<TEncRCPic*>::reverse_iterator it;
655  if( m_LayerID != 0)
656  {
657    m_lastIVPicture = NULL;
658    for ( it = listPreviousPictures.rbegin(); it != listPreviousPictures.rend(); it++ )
659    {
660      if ( (*it)->getLayerID() == 0 )
661      {
662        m_lastIVPicture = (*it);
663        break;
664      }
665    }
666  }
667
668  m_lastPicture = NULL;
669  for ( it = listPreviousPictures.rbegin(); it != listPreviousPictures.rend(); it++ )
670  {
671    if ( (*it)->getFrameLevel() == m_frameLevel )
672    {
673      m_lastPicture = (*it);
674      break;
675    }
676  }
677#endif
678}
679
680Void TEncRCPic::destroy()
681{
682  if( m_LCUs != NULL )
683  {
684    delete[] m_LCUs;
685    m_LCUs = NULL;
686  }
687  m_encRCSeq = NULL;
688  m_encRCGOP = NULL;
689}
690
691
692Double TEncRCPic::estimatePicLambda( list<TEncRCPic*>& listPreviousPictures, SliceType eSliceType)
693{
694  Double alpha         = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
695  Double beta          = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
696  Double bpp       = (Double)m_targetBits/(Double)m_numberOfPixel;
697  Double estLambda;
698  if (eSliceType == I_SLICE)
699  {
700    estLambda = calculateLambdaIntra(alpha, beta, pow(m_totalCostIntra/(Double)m_numberOfPixel, BETA1), bpp); 
701  }
702  else
703  {
704    estLambda = alpha * pow( bpp, beta );
705  }
706 
707  Double lastLevelLambda = -1.0;
708  Double lastPicLambda   = -1.0;
709  Double lastValidLambda = -1.0;
710  list<TEncRCPic*>::iterator it;
711  for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ )
712  {
713    if ( (*it)->getFrameLevel() == m_frameLevel )
714    {
715      lastLevelLambda = (*it)->getPicActualLambda();
716    }
717    lastPicLambda     = (*it)->getPicActualLambda();
718
719    if ( lastPicLambda > 0.0 )
720    {
721      lastValidLambda = lastPicLambda;
722    }
723  }
724
725  if ( lastLevelLambda > 0.0 )
726  {
727    lastLevelLambda = Clip3( 0.1, 10000.0, lastLevelLambda );
728    estLambda = Clip3( lastLevelLambda * pow( 2.0, -3.0/3.0 ), lastLevelLambda * pow( 2.0, 3.0/3.0 ), estLambda );
729  }
730
731  if ( lastPicLambda > 0.0 )
732  {
733    lastPicLambda = Clip3( 0.1, 2000.0, lastPicLambda );
734    estLambda = Clip3( lastPicLambda * pow( 2.0, -10.0/3.0 ), lastPicLambda * pow( 2.0, 10.0/3.0 ), estLambda );
735  }
736  else if ( lastValidLambda > 0.0 )
737  {
738    lastValidLambda = Clip3( 0.1, 2000.0, lastValidLambda );
739    estLambda = Clip3( lastValidLambda * pow(2.0, -10.0/3.0), lastValidLambda * pow(2.0, 10.0/3.0), estLambda );
740  }
741  else
742  {
743    estLambda = Clip3( 0.1, 10000.0, estLambda );
744  }
745
746  if ( estLambda < 0.1 )
747  {
748    estLambda = 0.1;
749  }
750
751  m_estPicLambda = estLambda;
752
753  Double totalWeight = 0.0;
754  // initial BU bit allocation weight
755  for ( Int i=0; i<m_numberOfLCU; i++ )
756  {
757    Double alphaLCU, betaLCU;
758    if ( m_encRCSeq->getUseLCUSeparateModel() )
759    {
760      alphaLCU = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_alpha;
761      betaLCU  = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_beta;
762    }
763    else
764    {
765      alphaLCU = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
766      betaLCU  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
767    }
768
769    m_LCUs[i].m_bitWeight =  m_LCUs[i].m_numberOfPixel * pow( estLambda/alphaLCU, 1.0/betaLCU );
770
771    if ( m_LCUs[i].m_bitWeight < 0.01 )
772    {
773      m_LCUs[i].m_bitWeight = 0.01;
774    }
775    totalWeight += m_LCUs[i].m_bitWeight;
776  }
777  for ( Int i=0; i<m_numberOfLCU; i++ )
778  {
779    Double BUTargetBits = m_targetBits * m_LCUs[i].m_bitWeight / totalWeight;
780    m_LCUs[i].m_bitWeight = BUTargetBits;
781  }
782
783  return estLambda;
784}
785
786Int TEncRCPic::estimatePicQP( Double lambda, list<TEncRCPic*>& listPreviousPictures )
787{
788  Int QP = Int( 4.2005 * log( lambda ) + 13.7122 + 0.5 ); 
789
790  Int lastLevelQP = g_RCInvalidQPValue;
791  Int lastPicQP   = g_RCInvalidQPValue;
792  Int lastValidQP = g_RCInvalidQPValue;
793  list<TEncRCPic*>::iterator it;
794  for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ )
795  {
796    if ( (*it)->getFrameLevel() == m_frameLevel )
797    {
798      lastLevelQP = (*it)->getPicActualQP();
799    }
800    lastPicQP = (*it)->getPicActualQP();
801    if ( lastPicQP > g_RCInvalidQPValue )
802    {
803      lastValidQP = lastPicQP;
804    }
805  }
806
807  if ( lastLevelQP > g_RCInvalidQPValue )
808  {
809    QP = Clip3( lastLevelQP - 3, lastLevelQP + 3, QP );
810  }
811
812  if( lastPicQP > g_RCInvalidQPValue )
813  {
814    QP = Clip3( lastPicQP - 10, lastPicQP + 10, QP );
815  }
816  else if( lastValidQP > g_RCInvalidQPValue )
817  {
818    QP = Clip3( lastValidQP - 10, lastValidQP + 10, QP );
819  }
820
821  return QP;
822}
823
824
825#if KWU_RC_MADPRED_E0227
826Double TEncRCPic::estimatePicLambdaIV( list<TEncRCPic*>& listPreviousPictures, Int CurPOC )
827{
828  Double alpha         = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
829  Double beta          = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
830  Double bpp       = (Double)m_targetBits/(Double)m_numberOfPixel;
831  Double estLambda = alpha * pow( bpp, beta );
832  Double lastLevelLambda = -1.0;
833  Double lastPicLambda   = -1.0;
834  Double lastValidLambda = -1.0;
835  list<TEncRCPic*>::iterator it;
836
837  if(listPreviousPictures.size() == 0 || CurPOC%8 == 0)
838  {
839    lastLevelLambda = m_lastIVPicture->getPicActualLambda();
840    lastPicLambda     = m_lastIVPicture->getPicActualLambda();
841  }
842  else
843  {
844    for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ )
845    {
846      if ( (*it)->getFrameLevel() == m_frameLevel )
847      {
848        lastLevelLambda = (*it)->getPicActualLambda();
849      }
850      lastPicLambda     = (*it)->getPicActualLambda();
851
852      if ( lastPicLambda > 0.0 )
853      {
854        lastValidLambda = lastPicLambda;
855      }
856    }
857  }
858
859  if ( lastLevelLambda > 0.0 )
860  {
861    lastLevelLambda = Clip3( 0.1, 10000.0, lastLevelLambda );
862    estLambda = Clip3( lastLevelLambda * pow( 2.0, -3.0/3.0 ), lastLevelLambda * pow( 2.0, 3.0/3.0 ), estLambda );
863  }
864
865  if ( lastPicLambda > 0.0 )
866  {
867    lastPicLambda = Clip3( 0.1, 2000.0, lastPicLambda );
868    estLambda = Clip3( lastPicLambda * pow( 2.0, -10.0/3.0 ), lastPicLambda * pow( 2.0, 10.0/3.0 ), estLambda );
869  }
870  else if ( lastValidLambda > 0.0 )
871  {
872    lastValidLambda = Clip3( 0.1, 2000.0, lastValidLambda );
873    estLambda = Clip3( lastValidLambda * pow(2.0, -10.0/3.0), lastValidLambda * pow(2.0, 10.0/3.0), estLambda );
874  }
875  else
876  {
877    estLambda = Clip3( 0.1, 10000.0, estLambda );
878  }
879
880  if ( estLambda < 0.1 )
881  {
882    estLambda = 0.1;
883  }
884
885  m_estPicLambda = estLambda;
886  return estLambda;
887}
888#endif
889
890
891Double TEncRCPic::getLCUTargetBpp(SliceType eSliceType) 
892{
893  Int   LCUIdx    = getLCUCoded();
894  Double bpp      = -1.0;
895  Int avgBits     = 0;
896
897  if (eSliceType == I_SLICE)
898  {
899    Int noOfLCUsLeft = m_numberOfLCU - LCUIdx + 1;
900    Int bitrateWindow = min(4,noOfLCUsLeft);
901    Double MAD      = getLCU(LCUIdx).m_costIntra;
902
903    if (m_remainingCostIntra > 0.1 )
904    {
905      Double weightedBitsLeft = (m_bitsLeft*bitrateWindow+(m_bitsLeft-getLCU(LCUIdx).m_targetBitsLeft)*noOfLCUsLeft)/(Double)bitrateWindow;
906      avgBits = Int( MAD*weightedBitsLeft/m_remainingCostIntra );
907    }
908    else
909    {
910      avgBits = Int( m_bitsLeft / m_LCULeft );
911    }
912    m_remainingCostIntra -= MAD;
913  }
914  else
915  {
916  Double totalWeight = 0;
917  for ( Int i=LCUIdx; i<m_numberOfLCU; i++ )
918  {
919    totalWeight += m_LCUs[i].m_bitWeight;
920  }
921  Int realInfluenceLCU = min( g_RCLCUSmoothWindowSize, getLCULeft() );
922  avgBits = (Int)( m_LCUs[LCUIdx].m_bitWeight - ( totalWeight - m_bitsLeft ) / realInfluenceLCU + 0.5 );
923  }
924
925  if ( avgBits < 1 )
926  {
927    avgBits = 1;
928  }
929
930  bpp = ( Double )avgBits/( Double )m_LCUs[ LCUIdx ].m_numberOfPixel;
931  m_LCUs[ LCUIdx ].m_targetBits = avgBits;
932
933  return bpp;
934}
935
936
937#if KWU_RC_MADPRED_E0227
938Double TEncRCPic::getLCUTargetBppforInterView( list<TEncRCPic*>& listPreviousPictures, TComDataCU* pcCU, Double basePos, Double curPos, Double focalLen, Double znear, Double zfar, Int direction, Int* disparity )
939{
940  Int   LCUIdx    = getLCUCoded();
941  Double bpp      = -1.0;
942  Int avgBits     = 0;
943#if !M0036_RC_IMPROVEMENT
944  Double totalMAD = -1.0;
945  Double MAD      = -1.0;
946#endif
947
948  Double totalMAD = -1.0;
949  Double MAD      = -1.0;
950
951  Double IVMAD      = -1.0;
952  Double SAD = 0.0;
953  Int     x, y;
954  Int Sum = 0;
955
956  {
957    Pel*  pOrg    = pcCU->getSlice()->getIvPic(false, 0)->getPicYuvOrg()->getLumaAddr(pcCU->getAddr(), 0);
958    Pel*  pRec    = pcCU->getSlice()->getIvPic(false, 0)->getPicYuvRec()->getLumaAddr(pcCU->getAddr(), 0);
959    Pel*  pDep    = pcCU->getSlice()->getIvPic(true, pcCU->getSlice()->getViewIndex())->getPicYuvOrg()->getLumaAddr(pcCU->getAddr(), 0);
960    Int   iStride = pcCU->getSlice()->getIvPic(true, pcCU->getSlice()->getViewIndex())->getPicYuvOrg()->getStride();
961
962    Int   width  = m_LCUs[ LCUIdx ].m_CUWidth;
963    Int   height = m_LCUs[ LCUIdx ].m_CUHeight;
964
965    for( y = 0 ; y < pcCU->getSlice()->getSPS()->getMaxCUHeight() ; y+=8)
966    {
967      for( x = 0 ; x < pcCU->getSlice()->getSPS()->getMaxCUWidth() ; x+=8)
968      {
969        Sum += pDep[x];
970      }
971      pDep += iStride;
972    }
973
974    Double AvgDepth = (Double)Sum/((pcCU->getSlice()->getSPS()->getMaxCUHeight()/8)*(pcCU->getSlice()->getSPS()->getMaxCUWidth()/8));
975
976    Double fL = focalLen * abs( basePos - curPos );
977    Double z  = abs( 1.0 / znear - 1.0 / zfar ) * ((Double)(AvgDepth) / (( 1 << g_bitDepthY ) - 1) ) + abs(1.0 / zfar);
978    *disparity = (Int)(direction*fL * z);
979    Int shift = DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthY-8);
980
981    Int disp = *disparity;
982    Int posX, posY;
983    pcCU->getPosInPic(0, posX, posY);
984    if((posX + *disparity) < 0 || (posX + *disparity + width) >= pcCU->getSlice()->getSPS()->getMaxCUWidth())
985    {
986      disp = 0;
987    }
988
989    for( y = 0; y < height; y++ )
990    {
991      for( x = 0; x < width; x++ )
992      {
993        SAD += abs( pOrg[Clip3(0, (Int)(pcCU->getPic()->getPicYuvOrg()->getWidth() - pcCU->getSlice()->getSPS()->getMaxCUWidth()), x + disp)]
994                  - pRec[Clip3(0, (Int)(pcCU->getPic()->getPicYuvOrg()->getWidth() - pcCU->getSlice()->getSPS()->getMaxCUWidth()), x + disp)] )>>shift;
995      }
996      pOrg += iStride;
997      pRec += iStride;
998    }
999    IVMAD = SAD / (Double)(height * width);
1000    IVMAD = IVMAD * IVMAD;
1001
1002    m_LCUs[ LCUIdx ].m_IVMAD = IVMAD;
1003    if(m_lastPicture)
1004    {
1005      m_LCUs[ LCUIdx ].m_MAD = m_lastPicture->getLCU(LCUIdx).m_MAD;
1006    }
1007
1008    MAD = m_LCUs[ LCUIdx ].m_IVMAD;
1009
1010    if(m_lastPicture)
1011    {
1012      totalMAD = m_lastPicture->getTotalMAD();      // get total MAD of temporal frame
1013      for ( Int i=0; i<LCUIdx; i++ )
1014      {
1015        totalMAD -= m_lastPicture->getLCU(i).m_MAD;
1016      }
1017    }
1018    else
1019    {
1020      totalMAD = m_lastIVPicture->getTotalMAD();      // get total MAD of inter-view frame
1021      for ( Int i=0; i<LCUIdx; i++ )
1022      {
1023        totalMAD -= m_lastIVPicture->getLCU(i).m_MAD;
1024      }
1025    }
1026
1027
1028    if ( totalMAD > 0.1 )
1029    {
1030      avgBits = Int( (m_bitsLeft * MAD) / totalMAD );
1031    }
1032    else
1033    {
1034      avgBits = Int( (m_bitsLeft) / m_LCULeft );
1035    }
1036  }
1037
1038  if ( avgBits < 5 )
1039  {
1040    avgBits = 5;
1041  }
1042
1043  bpp = ( Double )avgBits/( Double )m_LCUs[ LCUIdx ].m_numberOfPixel;
1044  m_LCUs[ LCUIdx ].m_targetBits = avgBits;
1045
1046  return bpp;
1047}
1048#endif
1049
1050
1051
1052
1053Double TEncRCPic::getLCUEstLambda( Double bpp )
1054{
1055  Int   LCUIdx = getLCUCoded();
1056  Double alpha;
1057  Double beta;
1058  if ( m_encRCSeq->getUseLCUSeparateModel() )
1059  {
1060    alpha = m_encRCSeq->getLCUPara( m_frameLevel, LCUIdx ).m_alpha;
1061    beta  = m_encRCSeq->getLCUPara( m_frameLevel, LCUIdx ).m_beta;
1062  }
1063  else
1064  {
1065    alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
1066    beta  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
1067  }
1068
1069  Double estLambda = alpha * pow( bpp, beta );
1070  //for Lambda clip, picture level clip
1071  Double clipPicLambda = m_estPicLambda;
1072
1073  //for Lambda clip, LCU level clip
1074  Double clipNeighbourLambda = -1.0;
1075  for ( int i=LCUIdx - 1; i>=0; i-- )
1076  {
1077    if ( m_LCUs[i].m_lambda > 0 )
1078    {
1079      clipNeighbourLambda = m_LCUs[i].m_lambda;
1080      break;
1081    }
1082  }
1083
1084  if ( clipNeighbourLambda > 0.0 )
1085  {
1086    estLambda = Clip3( clipNeighbourLambda * pow( 2.0, -1.0/3.0 ), clipNeighbourLambda * pow( 2.0, 1.0/3.0 ), estLambda );
1087  } 
1088
1089  if ( clipPicLambda > 0.0 )
1090  {
1091    estLambda = Clip3( clipPicLambda * pow( 2.0, -2.0/3.0 ), clipPicLambda * pow( 2.0, 2.0/3.0 ), estLambda );
1092  }
1093  else
1094  {
1095    estLambda = Clip3( 10.0, 1000.0, estLambda );
1096  }
1097
1098  if ( estLambda < 0.1 )
1099  {
1100    estLambda = 0.1;
1101  }
1102
1103  return estLambda;
1104}
1105
1106Int TEncRCPic::getLCUEstQP( Double lambda, Int clipPicQP )
1107{
1108  Int LCUIdx = getLCUCoded();
1109  Int estQP = Int( 4.2005 * log( lambda ) + 13.7122 + 0.5 );
1110
1111  //for Lambda clip, LCU level clip
1112  Int clipNeighbourQP = g_RCInvalidQPValue;
1113  for ( int i=LCUIdx - 1; i>=0; i-- )
1114  {
1115    if ( (getLCU(i)).m_QP > g_RCInvalidQPValue )
1116    {
1117      clipNeighbourQP = getLCU(i).m_QP;
1118      break;
1119    }
1120  }
1121
1122  if ( clipNeighbourQP > g_RCInvalidQPValue )
1123  {
1124    estQP = Clip3( clipNeighbourQP - 1, clipNeighbourQP + 1, estQP );
1125  }
1126
1127  estQP = Clip3( clipPicQP - 2, clipPicQP + 2, estQP );
1128
1129  return estQP;
1130}
1131
1132Void TEncRCPic::updateAfterLCU( Int LCUIdx, Int bits, Int QP, Double lambda, Bool updateLCUParameter )
1133{
1134  m_LCUs[LCUIdx].m_actualBits = bits;
1135  m_LCUs[LCUIdx].m_QP         = QP;
1136  m_LCUs[LCUIdx].m_lambda     = lambda;
1137
1138  m_LCULeft--;
1139  m_bitsLeft   -= bits;
1140  m_pixelsLeft -= m_LCUs[LCUIdx].m_numberOfPixel;
1141
1142  if ( !updateLCUParameter )
1143  {
1144    return;
1145  }
1146
1147  if ( !m_encRCSeq->getUseLCUSeparateModel() )
1148  {
1149    return;
1150  }
1151
1152  Double alpha = m_encRCSeq->getLCUPara( m_frameLevel, LCUIdx ).m_alpha;
1153  Double beta  = m_encRCSeq->getLCUPara( m_frameLevel, LCUIdx ).m_beta;
1154
1155  Int LCUActualBits   = m_LCUs[LCUIdx].m_actualBits;
1156  Int LCUTotalPixels  = m_LCUs[LCUIdx].m_numberOfPixel;
1157  Double bpp         = ( Double )LCUActualBits/( Double )LCUTotalPixels;
1158  Double calLambda   = alpha * pow( bpp, beta );
1159  Double inputLambda = m_LCUs[LCUIdx].m_lambda;
1160
1161  if( inputLambda < 0.01 || calLambda < 0.01 || bpp < 0.0001 )
1162  {
1163    alpha *= ( 1.0 - m_encRCSeq->getAlphaUpdate() / 2.0 );
1164    beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
1165
1166    alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
1167    beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
1168
1169    TRCParameter rcPara;
1170    rcPara.m_alpha = alpha;
1171    rcPara.m_beta  = beta;
1172    m_encRCSeq->setLCUPara( m_frameLevel, LCUIdx, rcPara );
1173
1174    return;
1175  }
1176
1177  calLambda = Clip3( inputLambda / 10.0, inputLambda * 10.0, calLambda );
1178  alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
1179  double lnbpp = log( bpp );
1180  lnbpp = Clip3( -5.0, -0.1, lnbpp );
1181  beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
1182
1183  alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
1184  beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
1185  TRCParameter rcPara;
1186  rcPara.m_alpha = alpha;
1187  rcPara.m_beta  = beta;
1188  m_encRCSeq->setLCUPara( m_frameLevel, LCUIdx, rcPara );
1189
1190}
1191
1192Double TEncRCPic::calAverageQP()
1193{
1194  Int totalQPs = 0;
1195  Int numTotalLCUs = 0;
1196
1197  Int i;
1198  for ( i=0; i<m_numberOfLCU; i++ )
1199  {
1200    if ( m_LCUs[i].m_QP > 0 )
1201    {
1202      totalQPs += m_LCUs[i].m_QP;
1203      numTotalLCUs++;
1204    }
1205  }
1206
1207  Double avgQP = 0.0;
1208  if ( numTotalLCUs == 0 )
1209  {
1210    avgQP = g_RCInvalidQPValue;
1211  }
1212  else
1213  {
1214    avgQP = ((Double)totalQPs) / ((Double)numTotalLCUs);
1215  }
1216  return avgQP;
1217}
1218
1219Double TEncRCPic::calAverageLambda()
1220{
1221  Double totalLambdas = 0.0;
1222  Int numTotalLCUs = 0;
1223
1224  Int i;
1225  for ( i=0; i<m_numberOfLCU; i++ )
1226  {
1227    if ( m_LCUs[i].m_lambda > 0.01 )
1228    {
1229      totalLambdas += log( m_LCUs[i].m_lambda );
1230      numTotalLCUs++;
1231    }
1232  }
1233
1234  Double avgLambda; 
1235  if( numTotalLCUs == 0 )
1236  {
1237    avgLambda = -1.0;
1238  }
1239  else
1240  {
1241    avgLambda = pow( 2.7183, totalLambdas / numTotalLCUs );
1242  }
1243  return avgLambda;
1244}
1245
1246Void TEncRCPic::updateAfterPicture( Int actualHeaderBits, Int actualTotalBits, Double averageQP, Double averageLambda, SliceType eSliceType)
1247{
1248  m_picActualHeaderBits = actualHeaderBits;
1249  m_picActualBits       = actualTotalBits;
1250  if ( averageQP > 0.0 )
1251  {
1252    m_picQP             = Int( averageQP + 0.5 );
1253  }
1254  else
1255  {
1256    m_picQP             = g_RCInvalidQPValue;
1257  }
1258  m_picLambda           = averageLambda;
1259#if KWU_RC_MADPRED_E0227
1260  m_totalMAD = 0;
1261  for ( Int i=0; i<m_numberOfLCU; i++ )
1262  {
1263    m_totalMAD += m_LCUs[i].m_MAD;
1264  }
1265#endif
1266
1267  Double alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
1268  Double beta  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
1269  if (eSliceType == I_SLICE)
1270  {
1271    updateAlphaBetaIntra(&alpha, &beta);
1272  }
1273  else
1274  {
1275  // update parameters
1276  Double picActualBits = ( Double )m_picActualBits;
1277  Double picActualBpp  = picActualBits/(Double)m_numberOfPixel;
1278  Double calLambda     = alpha * pow( picActualBpp, beta );
1279  Double inputLambda   = m_picLambda;
1280
1281  if ( inputLambda < 0.01 || calLambda < 0.01 || picActualBpp < 0.0001 )
1282  {
1283    alpha *= ( 1.0 - m_encRCSeq->getAlphaUpdate() / 2.0 );
1284    beta  *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 );
1285
1286    alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
1287    beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
1288    TRCParameter rcPara;
1289    rcPara.m_alpha = alpha;
1290    rcPara.m_beta  = beta;
1291    m_encRCSeq->setPicPara( m_frameLevel, rcPara );
1292
1293    return;
1294  }
1295
1296  calLambda = Clip3( inputLambda / 10.0, inputLambda * 10.0, calLambda );
1297  alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha;
1298  double lnbpp = log( picActualBpp );
1299  lnbpp = Clip3( -5.0, -0.1, lnbpp );
1300  beta  += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp;
1301
1302  alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha );
1303  beta  = Clip3( g_RCBetaMinValue,  g_RCBetaMaxValue,  beta  );
1304  }
1305
1306  TRCParameter rcPara;
1307  rcPara.m_alpha = alpha;
1308  rcPara.m_beta  = beta;
1309
1310  m_encRCSeq->setPicPara( m_frameLevel, rcPara );
1311
1312  if ( m_frameLevel == 1 )
1313  {
1314    Double currLambda = Clip3( 0.1, 10000.0, m_picLambda );
1315    Double updateLastLambda = g_RCWeightHistoryLambda * m_encRCSeq->getLastLambda() + g_RCWeightCurrentLambda * currLambda;
1316    m_encRCSeq->setLastLambda( updateLastLambda );
1317  }
1318}
1319
1320Int TEncRCPic::getRefineBitsForIntra( Int orgBits )
1321{
1322  Double alpha=0.25, beta=0.5582;
1323  Int iIntraBits;
1324
1325  if (orgBits*40 < m_numberOfPixel)
1326  {
1327    alpha=0.25;
1328  }
1329  else
1330  {
1331    alpha=0.30;
1332  }
1333
1334  iIntraBits = (Int)(alpha* pow(m_totalCostIntra*4.0/(Double)orgBits, beta)*(Double)orgBits+0.5);
1335 
1336  return iIntraBits;
1337}
1338
1339Double TEncRCPic::calculateLambdaIntra(double alpha, double beta, double MADPerPixel, double bitsPerPixel)
1340{
1341  return ( (alpha/256.0) * pow( MADPerPixel/bitsPerPixel, beta ) );
1342}
1343
1344Void TEncRCPic::updateAlphaBetaIntra(double *alpha, double *beta)
1345{
1346  Double lnbpp = log(pow(m_totalCostIntra / (Double)m_numberOfPixel, BETA1));
1347  Double diffLambda = (*beta)*(log((Double)m_picActualBits)-log((Double)m_targetBits));
1348
1349  diffLambda = Clip3(-0.125, 0.125, 0.25*diffLambda);
1350  *alpha    =  (*alpha) * exp(diffLambda);
1351  *beta     =  (*beta) + diffLambda / lnbpp;
1352}
1353
1354
1355Void TEncRCPic::getLCUInitTargetBits() 
1356{
1357  Int iAvgBits     = 0;
1358
1359  m_remainingCostIntra = m_totalCostIntra;
1360  for (Int i=m_numberOfLCU-1; i>=0; i--)
1361  {
1362    iAvgBits += Int(m_targetBits * getLCU(i).m_costIntra/m_totalCostIntra);
1363    getLCU(i).m_targetBitsLeft = iAvgBits;
1364  }
1365}
1366
1367
1368Double TEncRCPic::getLCUEstLambdaAndQP(Double bpp, Int clipPicQP, Int *estQP) 
1369{
1370  Int   LCUIdx = getLCUCoded();
1371
1372  Double   alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha;
1373  Double   beta  = m_encRCSeq->getPicPara( m_frameLevel ).m_beta;
1374
1375  Double costPerPixel = getLCU(LCUIdx).m_costIntra/(Double)getLCU(LCUIdx).m_numberOfPixel;
1376  costPerPixel = pow(costPerPixel, BETA1);
1377  Double estLambda = calculateLambdaIntra(alpha, beta, costPerPixel, bpp);
1378
1379  Int clipNeighbourQP = g_RCInvalidQPValue;
1380  for (int i=LCUIdx-1; i>=0; i--)
1381  {
1382    if ((getLCU(i)).m_QP > g_RCInvalidQPValue)
1383    {
1384      clipNeighbourQP = getLCU(i).m_QP;
1385      break;
1386    }
1387  }
1388
1389  Int minQP = clipPicQP - 2;
1390  Int maxQP = clipPicQP + 2;
1391
1392  if ( clipNeighbourQP > g_RCInvalidQPValue )
1393  {
1394    maxQP = min(clipNeighbourQP + 1, maxQP); 
1395    minQP = max(clipNeighbourQP - 1, minQP); 
1396  }
1397
1398  Double maxLambda=exp(((Double)(maxQP+0.49)-13.7122)/4.2005);
1399  Double minLambda=exp(((Double)(minQP-0.49)-13.7122)/4.2005);
1400
1401  estLambda = Clip3(minLambda, maxLambda, estLambda);
1402
1403  *estQP = Int( 4.2005 * log(estLambda) + 13.7122 + 0.5 );
1404  *estQP = Clip3(minQP, maxQP, *estQP);
1405
1406  return estLambda;
1407}
1408
1409TEncRateCtrl::TEncRateCtrl()
1410{
1411  m_encRCSeq = NULL;
1412  m_encRCGOP = NULL;
1413  m_encRCPic = NULL;
1414}
1415
1416TEncRateCtrl::~TEncRateCtrl()
1417{
1418  destroy();
1419}
1420
1421Void TEncRateCtrl::destroy()
1422{
1423  if ( m_encRCSeq != NULL )
1424  {
1425    delete m_encRCSeq;
1426    m_encRCSeq = NULL;
1427  }
1428  if ( m_encRCGOP != NULL )
1429  {
1430    delete m_encRCGOP;
1431    m_encRCGOP = NULL;
1432  }
1433  while ( m_listRCPictures.size() > 0 )
1434  {
1435    TEncRCPic* p = m_listRCPictures.front();
1436    m_listRCPictures.pop_front();
1437    delete p;
1438  }
1439}
1440
1441#if KWU_RC_MADPRED_E0227
1442Void TEncRateCtrl::init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Bool keepHierBits, Bool useLCUSeparateModel, GOPEntry  GOPList[MAX_GOP], Int layerID )
1443#else
1444Void TEncRateCtrl::init( Int totalFrames, Int targetBitrate, Int frameRate, Int GOPSize, Int picWidth, Int picHeight, Int LCUWidth, Int LCUHeight, Int keepHierBits, Bool useLCUSeparateModel, GOPEntry  GOPList[MAX_GOP] )
1445#endif
1446{
1447  destroy();
1448
1449  Bool isLowdelay = true;
1450  for ( Int i=0; i<GOPSize-1; i++ )
1451  {
1452    if ( GOPList[i].m_POC > GOPList[i+1].m_POC )
1453    {
1454      isLowdelay = false;
1455      break;
1456    }
1457  }
1458
1459  Int numberOfLevel = 1;
1460  Int adaptiveBit = 0;
1461  if ( keepHierBits > 0 )
1462  {
1463    numberOfLevel = Int( log((Double)GOPSize)/log(2.0) + 0.5 ) + 1;
1464  }
1465  if ( !isLowdelay && GOPSize == 8 )
1466  {
1467    numberOfLevel = Int( log((Double)GOPSize)/log(2.0) + 0.5 ) + 1;
1468  }
1469  numberOfLevel++;    // intra picture
1470  numberOfLevel++;    // non-reference picture
1471
1472
1473  Int* bitsRatio;
1474  bitsRatio = new Int[ GOPSize ];
1475  for ( Int i=0; i<GOPSize; i++ )
1476  {
1477    bitsRatio[i] = 10;
1478    if ( !GOPList[i].m_refPic )
1479    {
1480      bitsRatio[i] = 2;
1481    }
1482  }
1483
1484  if ( keepHierBits > 0 )
1485  {
1486    Double bpp = (Double)( targetBitrate / (Double)( frameRate*picWidth*picHeight ) );
1487    if ( GOPSize == 4 && isLowdelay )
1488    {
1489      if ( bpp > 0.2 )
1490      {
1491        bitsRatio[0] = 2;
1492        bitsRatio[1] = 3;
1493        bitsRatio[2] = 2;
1494        bitsRatio[3] = 6;
1495      }
1496      else if( bpp > 0.1 )
1497      {
1498        bitsRatio[0] = 2;
1499        bitsRatio[1] = 3;
1500        bitsRatio[2] = 2;
1501        bitsRatio[3] = 10;
1502      }
1503      else if ( bpp > 0.05 )
1504      {
1505        bitsRatio[0] = 2;
1506        bitsRatio[1] = 3;
1507        bitsRatio[2] = 2;
1508        bitsRatio[3] = 12;
1509      }
1510      else
1511      {
1512        bitsRatio[0] = 2;
1513        bitsRatio[1] = 3;
1514        bitsRatio[2] = 2;
1515        bitsRatio[3] = 14;
1516      }
1517      if ( keepHierBits == 2 )
1518      {
1519        adaptiveBit = 1;
1520      }
1521    }
1522    else if ( GOPSize == 8 && !isLowdelay )
1523    {
1524      if ( bpp > 0.2 )
1525      {
1526        bitsRatio[0] = 15;
1527        bitsRatio[1] = 5;
1528        bitsRatio[2] = 4;
1529        bitsRatio[3] = 1;
1530        bitsRatio[4] = 1;
1531        bitsRatio[5] = 4;
1532        bitsRatio[6] = 1;
1533        bitsRatio[7] = 1;
1534      }
1535      else if ( bpp > 0.1 )
1536      {
1537        bitsRatio[0] = 20;
1538        bitsRatio[1] = 6;
1539        bitsRatio[2] = 4;
1540        bitsRatio[3] = 1;
1541        bitsRatio[4] = 1;
1542        bitsRatio[5] = 4;
1543        bitsRatio[6] = 1;
1544        bitsRatio[7] = 1;
1545      }
1546      else if ( bpp > 0.05 )
1547      {
1548        bitsRatio[0] = 25;
1549        bitsRatio[1] = 7;
1550        bitsRatio[2] = 4;
1551        bitsRatio[3] = 1;
1552        bitsRatio[4] = 1;
1553        bitsRatio[5] = 4;
1554        bitsRatio[6] = 1;
1555        bitsRatio[7] = 1;
1556      }
1557      else
1558      {
1559        bitsRatio[0] = 30;
1560        bitsRatio[1] = 8;
1561        bitsRatio[2] = 4;
1562        bitsRatio[3] = 1;
1563        bitsRatio[4] = 1;
1564        bitsRatio[5] = 4;
1565        bitsRatio[6] = 1;
1566        bitsRatio[7] = 1;
1567      }
1568      if ( keepHierBits == 2 )
1569      {
1570        adaptiveBit = 2;
1571      }
1572    }
1573    else
1574    {
1575      printf( "\n hierarchical bit allocation is not support for the specified coding structure currently.\n" );
1576    }
1577  }
1578
1579  Int* GOPID2Level = new int[ GOPSize ];
1580  for ( int i=0; i<GOPSize; i++ )
1581  {
1582    GOPID2Level[i] = 1;
1583    if ( !GOPList[i].m_refPic )
1584    {
1585      GOPID2Level[i] = 2;
1586    }
1587  }
1588  if ( keepHierBits > 0 )
1589  {
1590    if ( GOPSize == 4 && isLowdelay )
1591    {
1592      GOPID2Level[0] = 3;
1593      GOPID2Level[1] = 2;
1594      GOPID2Level[2] = 3;
1595      GOPID2Level[3] = 1;
1596    }
1597    else if ( GOPSize == 8 && !isLowdelay )
1598    {
1599      GOPID2Level[0] = 1;
1600      GOPID2Level[1] = 2;
1601      GOPID2Level[2] = 3;
1602      GOPID2Level[3] = 4;
1603      GOPID2Level[4] = 4;
1604      GOPID2Level[5] = 3;
1605      GOPID2Level[6] = 4;
1606      GOPID2Level[7] = 4;
1607    }
1608  }
1609
1610  if ( !isLowdelay && GOPSize == 8 )
1611  {
1612    GOPID2Level[0] = 1;
1613    GOPID2Level[1] = 2;
1614    GOPID2Level[2] = 3;
1615    GOPID2Level[3] = 4;
1616    GOPID2Level[4] = 4;
1617    GOPID2Level[5] = 3;
1618    GOPID2Level[6] = 4;
1619    GOPID2Level[7] = 4;
1620  }
1621
1622  m_encRCSeq = new TEncRCSeq;
1623  m_encRCSeq->create( totalFrames, targetBitrate, frameRate, GOPSize, picWidth, picHeight, LCUWidth, LCUHeight, numberOfLevel, useLCUSeparateModel, adaptiveBit );
1624  m_encRCSeq->initBitsRatio( bitsRatio );
1625  m_encRCSeq->initGOPID2Level( GOPID2Level );
1626  m_encRCSeq->initPicPara();
1627  if ( useLCUSeparateModel )
1628  {
1629    m_encRCSeq->initLCUPara();
1630  }
1631
1632#if KWU_RC_MADPRED_E0227
1633  setLayerID(layerID);
1634#endif
1635
1636  delete[] bitsRatio;
1637  delete[] GOPID2Level;
1638}
1639
1640Void TEncRateCtrl::initRCPic( Int frameLevel )
1641{
1642  m_encRCPic = new TEncRCPic;
1643#if KWU_RC_MADPRED_E0227
1644  m_encRCPic->create( m_encRCSeq, m_encRCGOP, frameLevel, m_listRCPictures, m_LayerID );
1645#else
1646  m_encRCPic->create( m_encRCSeq, m_encRCGOP, frameLevel, m_listRCPictures );
1647#endif
1648}
1649
1650Void TEncRateCtrl::initRCGOP( Int numberOfPictures )
1651{
1652  m_encRCGOP = new TEncRCGOP;
1653  m_encRCGOP->create( m_encRCSeq, numberOfPictures );
1654}
1655
1656Void TEncRateCtrl::destroyRCGOP()
1657{
1658  delete m_encRCGOP;
1659  m_encRCGOP = NULL;
1660}
1661
Note: See TracBrowser for help on using the repository browser.