source: 3DVCSoftware/branches/HTM-DEV-2.0-dev1-Mediatek/source/Lib/TLibEncoder/TEncGOP.cpp @ 566

Last change on this file since 566 was 566, checked in by mediatek-htm, 11 years ago

Integration of JCT3V-E0172. The MACRO is "MTK_RVS_BUGFIX_E0172".

By Na Zhang (na.zhang@…)

  • Property svn:eol-style set to native
File size: 111.7 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-2013, 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     TEncGOP.cpp
35    \brief    GOP encoder class
36*/
37
38#include <list>
39#include <algorithm>
40#include <functional>
41
42#include "TEncTop.h"
43#include "TEncGOP.h"
44#include "TEncAnalyze.h"
45#include "libmd5/MD5.h"
46#include "TLibCommon/SEI.h"
47#include "TLibCommon/NAL.h"
48#include "NALwrite.h"
49#include <time.h>
50#include <math.h>
51
52using namespace std;
53//! \ingroup TLibEncoder
54//! \{
55
56// ====================================================================================================================
57// Constructor / destructor / initialization / destroy
58// ====================================================================================================================
59Int getLSB(Int poc, Int maxLSB)
60{
61  if (poc >= 0)
62  {
63    return poc % maxLSB;
64  }
65  else
66  {
67    return (maxLSB - ((-poc) % maxLSB)) % maxLSB;
68  }
69}
70
71TEncGOP::TEncGOP()
72{
73  m_iLastIDR            = 0;
74  m_iGopSize            = 0;
75  m_iNumPicCoded        = 0; //Niko
76  m_bFirst              = true;
77 
78  m_pcCfg               = NULL;
79  m_pcSliceEncoder      = NULL;
80  m_pcListPic           = NULL;
81 
82  m_pcEntropyCoder      = NULL;
83  m_pcCavlcCoder        = NULL;
84  m_pcSbacCoder         = NULL;
85  m_pcBinCABAC          = NULL;
86 
87  m_bSeqFirst           = true;
88 
89  m_bRefreshPending     = 0;
90  m_pocCRA            = 0;
91  m_numLongTermRefPicSPS = 0;
92  ::memset(m_ltRefPicPocLsbSps, 0, sizeof(m_ltRefPicPocLsbSps));
93  ::memset(m_ltRefPicUsedByCurrPicFlag, 0, sizeof(m_ltRefPicUsedByCurrPicFlag));
94  m_cpbRemovalDelay   = 0;
95  m_lastBPSEI         = 0;
96  xResetNonNestedSEIPresentFlags();
97  xResetNestedSEIPresentFlags();
98#if H_MV
99  m_layerId      = 0;
100  m_viewId       = 0;
101  m_pocLastCoded = -1; 
102#if H_3D
103  m_viewIndex  =   0; 
104  m_isDepth = false;
105#endif
106#endif
107  return;
108}
109
110TEncGOP::~TEncGOP()
111{
112}
113
114/** Create list to contain pointers to LCU start addresses of slice.
115 */
116Void  TEncGOP::create()
117{
118  m_bLongtermTestPictureHasBeenCoded = 0;
119  m_bLongtermTestPictureHasBeenCoded2 = 0;
120}
121
122Void  TEncGOP::destroy()
123{
124}
125
126Void TEncGOP::init ( TEncTop* pcTEncTop )
127{
128  m_pcEncTop     = pcTEncTop;
129  m_pcCfg                = pcTEncTop;
130  m_pcSliceEncoder       = pcTEncTop->getSliceEncoder();
131  m_pcListPic            = pcTEncTop->getListPic();
132 
133  m_pcEntropyCoder       = pcTEncTop->getEntropyCoder();
134  m_pcCavlcCoder         = pcTEncTop->getCavlcCoder();
135  m_pcSbacCoder          = pcTEncTop->getSbacCoder();
136  m_pcBinCABAC           = pcTEncTop->getBinCABAC();
137  m_pcLoopFilter         = pcTEncTop->getLoopFilter();
138  m_pcBitCounter         = pcTEncTop->getBitCounter();
139 
140  //--Adaptive Loop filter
141  m_pcSAO                = pcTEncTop->getSAO();
142  m_pcRateCtrl           = pcTEncTop->getRateCtrl();
143  m_lastBPSEI          = 0;
144  m_totalCoded         = 0;
145
146#if H_MV
147  m_ivPicLists           = pcTEncTop->getIvPicLists(); 
148  m_layerId              = pcTEncTop->getLayerId();
149  m_viewId               = pcTEncTop->getViewId();
150#if H_3D
151  m_viewIndex            = pcTEncTop->getViewIndex();
152  m_isDepth              = pcTEncTop->getIsDepth();
153#endif
154#endif
155}
156
157SEIActiveParameterSets* TEncGOP::xCreateSEIActiveParameterSets (TComSPS *sps)
158{
159  SEIActiveParameterSets *seiActiveParameterSets = new SEIActiveParameterSets(); 
160  seiActiveParameterSets->activeVPSId = m_pcCfg->getVPS()->getVPSId(); 
161  seiActiveParameterSets->m_fullRandomAccessFlag = false;
162  seiActiveParameterSets->m_noParamSetUpdateFlag = false;
163  seiActiveParameterSets->numSpsIdsMinus1 = 0;
164  seiActiveParameterSets->activeSeqParamSetId.resize(seiActiveParameterSets->numSpsIdsMinus1 + 1); 
165  seiActiveParameterSets->activeSeqParamSetId[0] = sps->getSPSId();
166  return seiActiveParameterSets;
167}
168
169SEIFramePacking* TEncGOP::xCreateSEIFramePacking()
170{
171  SEIFramePacking *seiFramePacking = new SEIFramePacking();
172  seiFramePacking->m_arrangementId = m_pcCfg->getFramePackingArrangementSEIId();
173  seiFramePacking->m_arrangementCancelFlag = 0;
174  seiFramePacking->m_arrangementType = m_pcCfg->getFramePackingArrangementSEIType();
175  assert((seiFramePacking->m_arrangementType > 2) && (seiFramePacking->m_arrangementType < 6) );
176  seiFramePacking->m_quincunxSamplingFlag = m_pcCfg->getFramePackingArrangementSEIQuincunx();
177  seiFramePacking->m_contentInterpretationType = m_pcCfg->getFramePackingArrangementSEIInterpretation();
178  seiFramePacking->m_spatialFlippingFlag = 0;
179  seiFramePacking->m_frame0FlippedFlag = 0;
180  seiFramePacking->m_fieldViewsFlag = (seiFramePacking->m_arrangementType == 2);
181  seiFramePacking->m_currentFrameIsFrame0Flag = ((seiFramePacking->m_arrangementType == 5) && m_iNumPicCoded&1);
182  seiFramePacking->m_frame0SelfContainedFlag = 0;
183  seiFramePacking->m_frame1SelfContainedFlag = 0;
184  seiFramePacking->m_frame0GridPositionX = 0;
185  seiFramePacking->m_frame0GridPositionY = 0;
186  seiFramePacking->m_frame1GridPositionX = 0;
187  seiFramePacking->m_frame1GridPositionY = 0;
188  seiFramePacking->m_arrangementReservedByte = 0;
189  seiFramePacking->m_arrangementPersistenceFlag = true;
190  seiFramePacking->m_upsampledAspectRatio = 0;
191  return seiFramePacking;
192}
193
194SEIDisplayOrientation* TEncGOP::xCreateSEIDisplayOrientation()
195{
196  SEIDisplayOrientation *seiDisplayOrientation = new SEIDisplayOrientation();
197  seiDisplayOrientation->cancelFlag = false;
198  seiDisplayOrientation->horFlip = false;
199  seiDisplayOrientation->verFlip = false;
200  seiDisplayOrientation->anticlockwiseRotation = m_pcCfg->getDisplayOrientationSEIAngle();
201  return seiDisplayOrientation;
202}
203
204SEIToneMappingInfo*  TEncGOP::xCreateSEIToneMappingInfo()
205{
206  SEIToneMappingInfo *seiToneMappingInfo = new SEIToneMappingInfo();
207  seiToneMappingInfo->m_toneMapId = m_pcCfg->getTMISEIToneMapId();
208  seiToneMappingInfo->m_toneMapCancelFlag = m_pcCfg->getTMISEIToneMapCancelFlag();
209  seiToneMappingInfo->m_toneMapPersistenceFlag = m_pcCfg->getTMISEIToneMapPersistenceFlag();
210
211  seiToneMappingInfo->m_codedDataBitDepth = m_pcCfg->getTMISEICodedDataBitDepth();
212  assert(seiToneMappingInfo->m_codedDataBitDepth >= 8 && seiToneMappingInfo->m_codedDataBitDepth <= 14);
213  seiToneMappingInfo->m_targetBitDepth = m_pcCfg->getTMISEITargetBitDepth();
214  assert( seiToneMappingInfo->m_targetBitDepth >= 1 && seiToneMappingInfo->m_targetBitDepth <= 17 );
215  seiToneMappingInfo->m_modelId = m_pcCfg->getTMISEIModelID();
216  assert(seiToneMappingInfo->m_modelId >=0 &&seiToneMappingInfo->m_modelId<=4);
217
218  switch( seiToneMappingInfo->m_modelId)
219  {
220  case 0:
221    {
222      seiToneMappingInfo->m_minValue = m_pcCfg->getTMISEIMinValue();
223      seiToneMappingInfo->m_maxValue = m_pcCfg->getTMISEIMaxValue();
224      break;
225    }
226  case 1:
227    {
228      seiToneMappingInfo->m_sigmoidMidpoint = m_pcCfg->getTMISEISigmoidMidpoint();
229      seiToneMappingInfo->m_sigmoidWidth = m_pcCfg->getTMISEISigmoidWidth();
230      break;
231    }
232  case 2:
233    {
234      UInt num = 1u<<(seiToneMappingInfo->m_targetBitDepth);
235      seiToneMappingInfo->m_startOfCodedInterval.resize(num);
236      Int* ptmp = m_pcCfg->getTMISEIStartOfCodedInterva();
237      if(ptmp)
238      {
239        for(int i=0; i<num;i++)
240        {
241          seiToneMappingInfo->m_startOfCodedInterval[i] = ptmp[i];
242        }
243      }
244      break;
245    }
246  case 3:
247    {
248      seiToneMappingInfo->m_numPivots = m_pcCfg->getTMISEINumPivots();
249      seiToneMappingInfo->m_codedPivotValue.resize(seiToneMappingInfo->m_numPivots);
250      seiToneMappingInfo->m_targetPivotValue.resize(seiToneMappingInfo->m_numPivots);
251      Int* ptmpcoded = m_pcCfg->getTMISEICodedPivotValue();
252      Int* ptmptarget = m_pcCfg->getTMISEITargetPivotValue();
253      if(ptmpcoded&&ptmptarget)
254      {
255        for(int i=0; i<(seiToneMappingInfo->m_numPivots);i++)
256        {
257          seiToneMappingInfo->m_codedPivotValue[i]=ptmpcoded[i];
258          seiToneMappingInfo->m_targetPivotValue[i]=ptmptarget[i];
259         }
260       }
261       break;
262     }
263  case 4:
264     {
265       seiToneMappingInfo->m_cameraIsoSpeedIdc = m_pcCfg->getTMISEICameraIsoSpeedIdc();
266       seiToneMappingInfo->m_cameraIsoSpeedValue = m_pcCfg->getTMISEICameraIsoSpeedValue();
267       assert( seiToneMappingInfo->m_cameraIsoSpeedValue !=0 );
268       seiToneMappingInfo->m_exposureCompensationValueSignFlag = m_pcCfg->getTMISEIExposureCompensationValueSignFlag();
269       seiToneMappingInfo->m_exposureCompensationValueNumerator = m_pcCfg->getTMISEIExposureCompensationValueNumerator();
270       seiToneMappingInfo->m_exposureCompensationValueDenomIdc = m_pcCfg->getTMISEIExposureCompensationValueDenomIdc();
271       seiToneMappingInfo->m_refScreenLuminanceWhite = m_pcCfg->getTMISEIRefScreenLuminanceWhite();
272       seiToneMappingInfo->m_extendedRangeWhiteLevel = m_pcCfg->getTMISEIExtendedRangeWhiteLevel();
273       assert( seiToneMappingInfo->m_extendedRangeWhiteLevel >= 100 );
274       seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue = m_pcCfg->getTMISEINominalBlackLevelLumaCodeValue();
275       seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue = m_pcCfg->getTMISEINominalWhiteLevelLumaCodeValue();
276       assert( seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue > seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue );
277       seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue = m_pcCfg->getTMISEIExtendedWhiteLevelLumaCodeValue();
278       assert( seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue >= seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue );
279       break;
280    }
281  default:
282    {
283      assert(!"Undefined SEIToneMapModelId");
284      break;
285    }
286  }
287  return seiToneMappingInfo;
288}
289
290Void TEncGOP::xCreateLeadingSEIMessages (/*SEIMessages seiMessages,*/ AccessUnit &accessUnit, TComSPS *sps)
291{
292  OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
293
294  if(m_pcCfg->getActiveParameterSetsSEIEnabled())
295  {
296    SEIActiveParameterSets *sei = xCreateSEIActiveParameterSets (sps);
297
298    //nalu = NALUnit(NAL_UNIT_SEI);
299    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
300    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
301    writeRBSPTrailingBits(nalu.m_Bitstream);
302    accessUnit.push_back(new NALUnitEBSP(nalu));
303    delete sei;
304    m_activeParameterSetSEIPresentInAU = true;
305  }
306
307  if(m_pcCfg->getFramePackingArrangementSEIEnabled())
308  {
309    SEIFramePacking *sei = xCreateSEIFramePacking ();
310
311    nalu = NALUnit(NAL_UNIT_PREFIX_SEI);
312    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
313    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps);
314    writeRBSPTrailingBits(nalu.m_Bitstream);
315    accessUnit.push_back(new NALUnitEBSP(nalu));
316    delete sei;
317  }
318  if (m_pcCfg->getDisplayOrientationSEIAngle())
319  {
320    SEIDisplayOrientation *sei = xCreateSEIDisplayOrientation();
321
322    nalu = NALUnit(NAL_UNIT_PREFIX_SEI); 
323    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
324    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
325    writeRBSPTrailingBits(nalu.m_Bitstream);
326    accessUnit.push_back(new NALUnitEBSP(nalu));
327    delete sei;
328  }
329  if(m_pcCfg->getToneMappingInfoSEIEnabled())
330  {
331    SEIToneMappingInfo *sei = xCreateSEIToneMappingInfo ();
332     
333    nalu = NALUnit(NAL_UNIT_PREFIX_SEI); 
334    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
335    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
336    writeRBSPTrailingBits(nalu.m_Bitstream);
337    accessUnit.push_back(new NALUnitEBSP(nalu));
338    delete sei;
339  }
340}
341
342// ====================================================================================================================
343// Public member functions
344// ====================================================================================================================
345#if H_MV
346Void TEncGOP::initGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP)
347{
348  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut );
349  m_iNumPicCoded = 0;
350}
351#endif
352#if H_MV
353Void TEncGOP::compressPicInGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Int iGOPid)
354#else
355Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP)
356#endif
357{
358  TComPic*        pcPic;
359  TComPicYuv*     pcPicYuvRecOut;
360  TComSlice*      pcSlice;
361  TComOutputBitstream  *pcBitstreamRedirect;
362  pcBitstreamRedirect = new TComOutputBitstream;
363  AccessUnit::iterator  itLocationToPushSliceHeaderNALU; // used to store location where NALU containing slice header is to be inserted
364  UInt                  uiOneBitstreamPerSliceLength = 0;
365  TEncSbac* pcSbacCoders = NULL;
366  TComOutputBitstream* pcSubstreamsOut = NULL;
367
368#if !H_MV
369  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut );
370 
371  m_iNumPicCoded = 0;
372#endif
373  SEIPictureTiming pictureTimingSEI;
374  Bool writeSOP = m_pcCfg->getSOPDescriptionSEIEnabled();
375  // Initialize Scalable Nesting SEI with single layer values
376  SEIScalableNesting scalableNestingSEI;
377  scalableNestingSEI.m_bitStreamSubsetFlag           = 1;      // If the nested SEI messages are picture buffereing SEI mesages, picure timing SEI messages or sub-picture timing SEI messages, bitstream_subset_flag shall be equal to 1
378  scalableNestingSEI.m_nestingOpFlag                 = 0;
379  scalableNestingSEI.m_nestingNumOpsMinus1           = 0;      //nesting_num_ops_minus1
380  scalableNestingSEI.m_allLayersFlag                 = 0;
381  scalableNestingSEI.m_nestingNoOpMaxTemporalIdPlus1 = 6 + 1;  //nesting_no_op_max_temporal_id_plus1
382  scalableNestingSEI.m_nestingNumLayersMinus1        = 1 - 1;  //nesting_num_layers_minus1
383  scalableNestingSEI.m_nestingLayerId[0]             = 0;
384  scalableNestingSEI.m_callerOwnsSEIs                = true;
385  Int picSptDpbOutputDuDelay = 0;
386  UInt *accumBitsDU = NULL;
387  UInt *accumNalsDU = NULL;
388  SEIDecodingUnitInfo decodingUnitInfoSEI;
389#if !H_MV
390  for ( Int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
391#endif
392  {
393    UInt uiColDir = 1;
394    //-- For time output for each slice
395    long iBeforeTime = clock();
396
397    //select uiColDir
398    Int iCloseLeft=1, iCloseRight=-1;
399    for(Int i = 0; i<m_pcCfg->getGOPEntry(iGOPid).m_numRefPics; i++) 
400    {
401      Int iRef = m_pcCfg->getGOPEntry(iGOPid).m_referencePics[i];
402      if(iRef>0&&(iRef<iCloseRight||iCloseRight==-1))
403      {
404        iCloseRight=iRef;
405      }
406      else if(iRef<0&&(iRef>iCloseLeft||iCloseLeft==1))
407      {
408        iCloseLeft=iRef;
409      }
410    }
411    if(iCloseRight>-1)
412    {
413      iCloseRight=iCloseRight+m_pcCfg->getGOPEntry(iGOPid).m_POC-1;
414    }
415    if(iCloseLeft<1) 
416    {
417      iCloseLeft=iCloseLeft+m_pcCfg->getGOPEntry(iGOPid).m_POC-1;
418      while(iCloseLeft<0)
419      {
420        iCloseLeft+=m_iGopSize;
421      }
422    }
423    Int iLeftQP=0, iRightQP=0;
424    for(Int i=0; i<m_iGopSize; i++)
425    {
426      if(m_pcCfg->getGOPEntry(i).m_POC==(iCloseLeft%m_iGopSize)+1)
427      {
428        iLeftQP= m_pcCfg->getGOPEntry(i).m_QPOffset;
429      }
430      if (m_pcCfg->getGOPEntry(i).m_POC==(iCloseRight%m_iGopSize)+1)
431      {
432        iRightQP=m_pcCfg->getGOPEntry(i).m_QPOffset;
433      }
434    }
435    if(iCloseRight>-1&&iRightQP<iLeftQP)
436    {
437      uiColDir=0;
438    }
439
440    /////////////////////////////////////////////////////////////////////////////////////////////////// Initial to start encoding
441    Int pocCurr = iPOCLast -iNumPicRcvd+ m_pcCfg->getGOPEntry(iGOPid).m_POC;
442    Int iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
443    if(iPOCLast == 0)
444    {
445      pocCurr=0;
446      iTimeOffset = 1;
447    }
448    if(pocCurr>=m_pcCfg->getFramesToBeEncoded())
449    {
450#if H_MV
451      delete pcBitstreamRedirect;
452      return;
453#else
454      continue;
455#endif
456    }
457
458    if( getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_N_LP )
459    {
460      m_iLastIDR = pocCurr;
461    }       
462    // start a new access unit: create an entry in the list of output access units
463    accessUnitsInGOP.push_back(AccessUnit());
464    AccessUnit& accessUnit = accessUnitsInGOP.back();
465    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr );
466
467    //  Slice data initialization
468    pcPic->clearSliceBuffer();
469    assert(pcPic->getNumAllocatedSlice() == 1);
470    m_pcSliceEncoder->setSliceIdx(0);
471    pcPic->setCurrSliceIdx(0);
472
473#if H_3D
474    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getVPS(), m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), getLayerId() );     
475#else
476    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS() );
477#endif
478    pcSlice->setLastIDR(m_iLastIDR);
479    pcSlice->setSliceIdx(0);
480#if H_MV
481    pcSlice->setRefPicSetInterLayer ( &m_refPicSetInterLayer ); 
482    pcPic  ->setLayerId     ( getLayerId()   );
483    pcPic  ->setViewId      ( getViewId()    );   
484#if !H_3D
485    pcSlice->setLayerId     ( getLayerId() );
486    pcSlice->setViewId      ( getViewId()  );   
487    pcSlice->setVPS         ( m_pcEncTop->getVPS() );
488#else
489    pcPic  ->setViewIndex   ( getViewIndex() ); 
490    pcPic  ->setIsDepth( getIsDepth() );
491    pcSlice->setCamparaSlice( pcPic->getCodedScale(), pcPic->getCodedOffset() );   
492#endif
493#endif
494    //set default slice level flag to the same as SPS level flag
495    pcSlice->setLFCrossSliceBoundaryFlag(  pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag()  );
496    pcSlice->setScalingList ( m_pcEncTop->getScalingList()  );
497    pcSlice->getScalingList()->setUseTransformSkip(m_pcEncTop->getPPS()->getUseTransformSkip());
498    if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_OFF)
499    {
500      m_pcEncTop->getTrQuant()->setFlatScalingList();
501      m_pcEncTop->getTrQuant()->setUseScalingList(false);
502      m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
503      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
504    }
505    else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_DEFAULT)
506    {
507      pcSlice->setDefaultScalingList ();
508      m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
509      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
510      m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList());
511      m_pcEncTop->getTrQuant()->setUseScalingList(true);
512    }
513    else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_FILE_READ)
514    {
515      if(pcSlice->getScalingList()->xParseScalingList(m_pcCfg->getScalingListFile()))
516      {
517        pcSlice->setDefaultScalingList ();
518      }
519      pcSlice->getScalingList()->checkDcOfMatrix();
520      m_pcEncTop->getSPS()->setScalingListPresentFlag(pcSlice->checkDefaultScalingList());
521      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
522      m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList());
523      m_pcEncTop->getTrQuant()->setUseScalingList(true);
524    }
525    else
526    {
527      printf("error : ScalingList == %d no support\n",m_pcEncTop->getUseScalingListId());
528      assert(0);
529    }
530
531#if H_MV
532    // Set the nal unit type
533    pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR));
534    if( pcSlice->getSliceType() == B_SLICE )
535    {
536      if( m_pcCfg->getGOPEntry( ( pcSlice->getRapPicFlag() && getLayerId() > 0 ) ? MAX_GOP : iGOPid ).m_sliceType == 'P' ) 
537      { 
538        pcSlice->setSliceType( P_SLICE );
539      }
540    }
541#else
542    if(pcSlice->getSliceType()==B_SLICE&&m_pcCfg->getGOPEntry(iGOPid).m_sliceType=='P')
543    {
544      pcSlice->setSliceType(P_SLICE);
545    }
546    // Set the nal unit type
547    pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR));
548#endif
549    if(pcSlice->getTemporalLayerNonReferenceFlag())
550    {
551      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_TRAIL_R)
552      {
553        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TRAIL_N);
554      }
555      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_RADL_R)
556      {
557        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_RADL_N);
558      }
559      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_RASL_R)
560      {
561        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_RASL_N);
562      }
563    }
564
565    // Do decoding refresh marking if any
566    pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic);
567    m_pcEncTop->selectReferencePictureSet(pcSlice, pocCurr, iGOPid);
568    pcSlice->getRPS()->setNumberOfLongtermPictures(0);
569
570#if FIX1071
571    if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0) || (pcSlice->isIRAP()))
572    {
573      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP());
574    }
575#else
576    if(pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0)
577    {
578      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS());
579    }
580#endif
581    pcSlice->applyReferencePictureSet(rcListPic, pcSlice->getRPS());
582
583    if(pcSlice->getTLayer() > 0)
584    {
585      if(pcSlice->isTemporalLayerSwitchingPoint(rcListPic) || pcSlice->getSPS()->getTemporalIdNestingFlag())
586      {
587        if(pcSlice->getTemporalLayerNonReferenceFlag())
588        {
589          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_N);
590        }
591        else
592        {
593          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA_R);
594        }
595      }
596      else if(pcSlice->isStepwiseTemporalLayerSwitchingPointCandidate(rcListPic))
597      {
598        Bool isSTSA=true;
599        for(Int ii=iGOPid+1;(ii<m_pcCfg->getGOPSize() && isSTSA==true);ii++)
600        {
601          Int lTid= m_pcCfg->getGOPEntry(ii).m_temporalId;
602          if(lTid==pcSlice->getTLayer()) 
603          {
604            TComReferencePictureSet* nRPS = pcSlice->getSPS()->getRPSList()->getReferencePictureSet(ii);
605            for(Int jj=0;jj<nRPS->getNumberOfPictures();jj++)
606            {
607              if(nRPS->getUsed(jj)) 
608              {
609                Int tPoc=m_pcCfg->getGOPEntry(ii).m_POC+nRPS->getDeltaPOC(jj);
610                Int kk=0;
611                for(kk=0;kk<m_pcCfg->getGOPSize();kk++)
612                {
613                  if(m_pcCfg->getGOPEntry(kk).m_POC==tPoc)
614                    break;
615                }
616                Int tTid=m_pcCfg->getGOPEntry(kk).m_temporalId;
617                if(tTid >= pcSlice->getTLayer())
618                {
619                  isSTSA=false;
620                  break;
621                }
622              }
623            }
624          }
625        }
626        if(isSTSA==true)
627        {   
628          if(pcSlice->getTemporalLayerNonReferenceFlag())
629          {
630            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_N);
631          }
632          else
633          {
634            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_R);
635          }
636        }
637      }
638    }
639    arrangeLongtermPicturesInRPS(pcSlice, rcListPic);
640    TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
641    refPicListModification->setRefPicListModificationFlagL0(0);
642    refPicListModification->setRefPicListModificationFlagL1(0);
643#if H_MV
644    if ( pcSlice->getPPS()->getNumExtraSliceHeaderBits() > 0 )
645    {
646      pcSlice->setDiscardableFlag           ( false );     
647    }   
648
649    TComVPS*           vps = pcSlice->getVPS(); 
650    Int       layerIdInVps = vps    ->getLayerIdInVps( getLayerId()); 
651    Int numDirectRefLayers = vps    ->getNumDirectRefLayers( layerIdInVps ); 
652    GOPEntry gopEntry      = m_pcCfg->getGOPEntry( (pcSlice->getRapPicFlag() && getLayerId() > 0) ? MAX_GOP : iGOPid );     
653   
654    if ( getLayerId() > 0 && numDirectRefLayers > 0 )
655    {         
656      pcSlice->setInterLayerPredEnabledFlag ( gopEntry.m_numActiveRefLayerPics > 0 );     
657      if ( pcSlice->getInterLayerPredEnabledFlag() && numDirectRefLayers > 1 )
658      {
659        if ( !vps->getMaxOneActiveRefLayerFlag() )
660        {   
661          pcSlice->setNumInterLayerRefPicsMinus1( gopEntry.m_numActiveRefLayerPics - 1 ); 
662        }
663        for (Int i = 0; i < gopEntry.m_numActiveRefLayerPics; i++ )
664        {
665          pcSlice->setInterLayerPredLayerIdc( i, gopEntry.m_interLayerPredLayerIdc[ i ] ); 
666        }
667      }
668    }
669    assert( pcSlice->getNumActiveRefLayerPics() == gopEntry.m_numActiveRefLayerPics ); 
670   
671    if ( vps->getNumSamplePredRefLayers( layerIdInVps ) > 0 && pcSlice->getNumActiveRefLayerPics() > 0)
672    {
673      pcSlice->setInterLayerSamplePredOnlyFlag( gopEntry.m_numRefPics == 0 ); 
674    }   
675
676    pcSlice->createAndApplyIvReferencePictureSet( m_ivPicLists, m_refPicSetInterLayer ); 
677    pcSlice->setNumRefIdx(REF_PIC_LIST_0,min(gopEntry.m_numRefPicsActive,( pcSlice->getRPS()->getNumberOfPictures() + (Int) m_refPicSetInterLayer.size() ) ) );
678    pcSlice->setNumRefIdx(REF_PIC_LIST_1,min(gopEntry.m_numRefPicsActive,( pcSlice->getRPS()->getNumberOfPictures() + (Int) m_refPicSetInterLayer.size() ) ) );
679
680    xSetRefPicListModificationsMv( pcSlice, iGOPid );   
681
682    pcSlice->setActiveMotionPredRefLayers( );
683
684    if ( getLayerId() > 0 && pcSlice->getNumActiveMotionPredRefLayers() > 0 && pcSlice->getEnableTMVPFlag() && 
685        ( pcSlice->getSliceType() == B_SLICE || pcSlice->getSliceType() == P_SLICE ))
686    {
687      pcSlice->setAltCollocatedIndicationFlag( gopEntry.m_collocatedRefLayerIdx >= 0 );
688      if ( pcSlice->getNumActiveRefLayerPics() && pcSlice->getNumActiveMotionPredRefLayers() > 0 )
689      {
690        pcSlice->setCollocatedRefLayerIdx( gopEntry.m_collocatedRefLayerIdx );
691      }
692    }
693
694#else
695    pcSlice->setNumRefIdx(REF_PIC_LIST_0,min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive,pcSlice->getRPS()->getNumberOfPictures()));
696    pcSlice->setNumRefIdx(REF_PIC_LIST_1,min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive,pcSlice->getRPS()->getNumberOfPictures()));
697#endif
698
699#if ADAPTIVE_QP_SELECTION
700    pcSlice->setTrQuant( m_pcEncTop->getTrQuant() );
701#endif     
702
703    //  Set reference list
704#if H_MV   
705    pcSlice->setRefPicList( rcListPic, m_refPicSetInterLayer );
706#if H_3D_ARP
707    pcSlice->setARPStepNum();
708    if(pcSlice->getARPStepNum() > 1)
709    {
710      for(Int iLayerId = 0; iLayerId < getLayerId(); iLayerId ++ )
711      {
712        Int  iViewIdx =   pcSlice->getVPS()->getViewIndex(iLayerId);
713        Bool bIsDepth = ( pcSlice->getVPS()->getDepthId  ( iLayerId ) == 1 );
714        if( iViewIdx<getViewIndex() && !bIsDepth )
715        {
716          pcSlice->setBaseViewRefPicList( m_ivPicLists->getPicList( iLayerId ), iViewIdx );
717        }
718      }
719    }
720#endif
721#else
722    pcSlice->setRefPicList ( rcListPic );
723#endif
724
725#if H_3D
726    pcSlice->setIvPicLists( m_ivPicLists );         
727#if H_3D_IV_MERGE   
728    assert( !m_pcEncTop->getIsDepth() || ( pcSlice->getTexturePic() != 0 ) );
729#endif   
730#endif
731    //  Slice info. refinement
732#if H_MV
733    if ( pcSlice->getSliceType() == B_SLICE )
734    {
735      if( m_pcCfg->getGOPEntry( ( pcSlice->getRapPicFlag() == true && getLayerId() > 0 ) ? MAX_GOP : iGOPid ).m_sliceType == 'P' ) 
736      { 
737        pcSlice->setSliceType( P_SLICE ); 
738      }
739    }
740#else
741    if ( (pcSlice->getSliceType() == B_SLICE) && (pcSlice->getNumRefIdx(REF_PIC_LIST_1) == 0) )
742    {
743      pcSlice->setSliceType ( P_SLICE );
744    }
745#endif
746    if (pcSlice->getSliceType() == B_SLICE)
747    {
748      pcSlice->setColFromL0Flag(1-uiColDir);
749      Bool bLowDelay = true;
750      Int  iCurrPOC  = pcSlice->getPOC();
751      Int iRefIdx = 0;
752
753      for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_0) && bLowDelay; iRefIdx++)
754      {
755        if ( pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx)->getPOC() > iCurrPOC )
756        {
757          bLowDelay = false;
758        }
759      }
760      for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_1) && bLowDelay; iRefIdx++)
761      {
762        if ( pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx)->getPOC() > iCurrPOC )
763        {
764          bLowDelay = false;
765        }
766      }
767
768      pcSlice->setCheckLDC(bLowDelay); 
769    }
770    else
771    {
772      pcSlice->setCheckLDC(true); 
773    }
774
775    uiColDir = 1-uiColDir;
776
777    //-------------------------------------------------------------
778    pcSlice->setRefPOCList();
779
780    pcSlice->setList1IdxToList0Idx();
781#if H_3D_TMVP
782    if(pcSlice->getLayerId())
783      pcSlice->generateAlterRefforTMVP();
784#endif
785    if (m_pcEncTop->getTMVPModeId() == 2)
786    {
787      if (iGOPid == 0) // first picture in SOP (i.e. forward B)
788      {
789        pcSlice->setEnableTMVPFlag(0);
790      }
791      else
792      {
793        // Note: pcSlice->getColFromL0Flag() is assumed to be always 0 and getcolRefIdx() is always 0.
794        pcSlice->setEnableTMVPFlag(1);
795      }
796      pcSlice->getSPS()->setTMVPFlagsPresent(1);
797    }
798    else if (m_pcEncTop->getTMVPModeId() == 1)
799    {
800      pcSlice->getSPS()->setTMVPFlagsPresent(1);
801      pcSlice->setEnableTMVPFlag(1);
802    }
803    else
804    {
805      pcSlice->getSPS()->setTMVPFlagsPresent(0);
806      pcSlice->setEnableTMVPFlag(0);
807    }
808#if H_MV
809    if( pcSlice->getIdrPicFlag() )
810    {
811      pcSlice->setEnableTMVPFlag(0);
812    }
813#endif
814
815#if H_3D_VSO
816  // Should be moved to TEncTop !!!
817  Bool bUseVSO = m_pcEncTop->getUseVSO();
818 
819  TComRdCost* pcRdCost = m_pcEncTop->getRdCost();   
820
821  pcRdCost->setUseVSO( bUseVSO );
822
823  // SAIT_VSO_EST_A0033
824  pcRdCost->setUseEstimatedVSD( m_pcEncTop->getUseEstimatedVSD() );
825
826  if ( bUseVSO )
827  {
828    Int iVSOMode = m_pcEncTop->getVSOMode();
829    pcRdCost->setVSOMode( iVSOMode  );
830    pcRdCost->setAllowNegDist( m_pcEncTop->getAllowNegDist() );
831
832    // SAIT_VSO_EST_A0033
833    pcRdCost->setVideoRecPicYuv( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), false , pcSlice->getPOC(), true ) );
834    pcRdCost->setDepthPicYuv   ( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), true  , pcSlice->getPOC(), false ) );
835
836    // LGE_WVSO_A0119
837    Bool bUseWVSO  = m_pcEncTop->getUseWVSO();
838    pcRdCost->setUseWVSO( bUseWVSO );
839
840  }
841#endif
842    /////////////////////////////////////////////////////////////////////////////////////////////////// Compress a slice
843    //  Slice compression
844    if (m_pcCfg->getUseASR())
845    {
846      m_pcSliceEncoder->setSearchRange(pcSlice);
847    }
848
849    Bool bGPBcheck=false;
850    if ( pcSlice->getSliceType() == B_SLICE)
851    {
852      if ( pcSlice->getNumRefIdx(RefPicList( 0 ) ) == pcSlice->getNumRefIdx(RefPicList( 1 ) ) )
853      {
854        bGPBcheck=true;
855        Int i;
856        for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
857        {
858          if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) ) 
859          {
860            bGPBcheck=false;
861            break;
862          }
863        }
864      }
865    }
866    if(bGPBcheck)
867    {
868      pcSlice->setMvdL1ZeroFlag(true);
869    }
870    else
871    {
872      pcSlice->setMvdL1ZeroFlag(false);
873    }
874    pcPic->getSlice(pcSlice->getSliceIdx())->setMvdL1ZeroFlag(pcSlice->getMvdL1ZeroFlag());
875
876#if RATE_CONTROL_LAMBDA_DOMAIN
877    Double lambda            = 0.0;
878    Int actualHeadBits       = 0;
879    Int actualTotalBits      = 0;
880    Int estimatedBits        = 0;
881    Int tmpBitsBeforeWriting = 0;
882    if ( m_pcCfg->getUseRateCtrl() )
883    {
884      Int frameLevel = m_pcRateCtrl->getRCSeq()->getGOPID2Level( iGOPid );
885      if ( pcPic->getSlice(0)->getSliceType() == I_SLICE )
886      {
887        frameLevel = 0;
888      }
889      m_pcRateCtrl->initRCPic( frameLevel );
890      estimatedBits = m_pcRateCtrl->getRCPic()->getTargetBits();
891
892      Int sliceQP = m_pcCfg->getInitialQP();
893      if ( ( pcSlice->getPOC() == 0 && m_pcCfg->getInitialQP() > 0 ) || ( frameLevel == 0 && m_pcCfg->getForceIntraQP() ) ) // QP is specified
894      {
895        Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
896        Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)NumberBFrames );
897        Double dQPFactor     = 0.57*dLambda_scale;
898        Int    SHIFT_QP      = 12;
899        Int    bitdepth_luma_qp_scale = 0;
900        Double qp_temp = (Double) sliceQP + bitdepth_luma_qp_scale - SHIFT_QP;
901        lambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
902      }
903      else if ( frameLevel == 0 )   // intra case, but use the model
904      {
905#if RATE_CONTROL_INTRA
906        m_pcSliceEncoder->calCostSliceI(pcPic);
907#endif
908        if ( m_pcCfg->getIntraPeriod() != 1 )   // do not refine allocated bits for all intra case
909        {
910          Int bits = m_pcRateCtrl->getRCSeq()->getLeftAverageBits();
911#if RATE_CONTROL_INTRA
912          bits = m_pcRateCtrl->getRCPic()->getRefineBitsForIntra( bits );
913#else
914          bits = m_pcRateCtrl->getRCSeq()->getRefineBitsForIntra( bits );
915#endif
916          if ( bits < 200 )
917          {
918            bits = 200;
919          }
920          m_pcRateCtrl->getRCPic()->setTargetBits( bits );
921        }
922
923        list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
924#if RATE_CONTROL_INTRA
925        m_pcRateCtrl->getRCPic()->getLCUInitTargetBits();
926        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
927#else
928        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture );
929#endif
930        sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
931      }
932      else    // normal case
933      {
934        list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
935#if RATE_CONTROL_INTRA
936        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
937#else
938        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture );
939#endif
940        sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
941      }
942
943      sliceQP = Clip3( -pcSlice->getSPS()->getQpBDOffsetY(), MAX_QP, sliceQP );
944      m_pcRateCtrl->getRCPic()->setPicEstQP( sliceQP );
945
946      m_pcSliceEncoder->resetQP( pcPic, sliceQP, lambda );
947    }
948#endif
949
950    UInt uiNumSlices = 1;
951
952    UInt uiInternalAddress = pcPic->getNumPartInCU()-4;
953    UInt uiExternalAddress = pcPic->getPicSym()->getNumberOfCUsInFrame()-1;
954    UInt uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
955    UInt uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
956    UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
957    UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
958    while(uiPosX>=uiWidth||uiPosY>=uiHeight) 
959    {
960      uiInternalAddress--;
961      uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
962      uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
963    }
964    uiInternalAddress++;
965    if(uiInternalAddress==pcPic->getNumPartInCU()) 
966    {
967      uiInternalAddress = 0;
968      uiExternalAddress++;
969    }
970    UInt uiRealEndAddress = uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress;
971
972    UInt uiCummulativeTileWidth;
973    UInt uiCummulativeTileHeight;
974    Int  p, j;
975    UInt uiEncCUAddr;
976
977    //set NumColumnsMinus1 and NumRowsMinus1
978    pcPic->getPicSym()->setNumColumnsMinus1( pcSlice->getPPS()->getNumColumnsMinus1() );
979    pcPic->getPicSym()->setNumRowsMinus1( pcSlice->getPPS()->getNumRowsMinus1() );
980
981    //create the TComTileArray
982    pcPic->getPicSym()->xCreateTComTileArray();
983
984    if( pcSlice->getPPS()->getUniformSpacingFlag() == 1 )
985    {
986      //set the width for each tile
987      for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
988      {
989        for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1()+1; p++)
990        {
991          pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->
992            setTileWidth( (p+1)*pcPic->getPicSym()->getFrameWidthInCU()/(pcPic->getPicSym()->getNumColumnsMinus1()+1) 
993            - (p*pcPic->getPicSym()->getFrameWidthInCU())/(pcPic->getPicSym()->getNumColumnsMinus1()+1) );
994        }
995      }
996
997      //set the height for each tile
998      for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
999      {
1000        for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1()+1; p++)
1001        {
1002          pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->
1003            setTileHeight( (p+1)*pcPic->getPicSym()->getFrameHeightInCU()/(pcPic->getPicSym()->getNumRowsMinus1()+1) 
1004            - (p*pcPic->getPicSym()->getFrameHeightInCU())/(pcPic->getPicSym()->getNumRowsMinus1()+1) );   
1005        }
1006      }
1007    }
1008    else
1009    {
1010      //set the width for each tile
1011      for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
1012      {
1013        uiCummulativeTileWidth = 0;
1014        for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1(); p++)
1015        {
1016          pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->setTileWidth( pcSlice->getPPS()->getColumnWidth(p) );
1017          uiCummulativeTileWidth += pcSlice->getPPS()->getColumnWidth(p);
1018        }
1019        pcPic->getPicSym()->getTComTile(j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p)->setTileWidth( pcPic->getPicSym()->getFrameWidthInCU()-uiCummulativeTileWidth );
1020      }
1021
1022      //set the height for each tile
1023      for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
1024      {
1025        uiCummulativeTileHeight = 0;
1026        for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1(); p++)
1027        {
1028          pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->setTileHeight( pcSlice->getPPS()->getRowHeight(p) );
1029          uiCummulativeTileHeight += pcSlice->getPPS()->getRowHeight(p);
1030        }
1031        pcPic->getPicSym()->getTComTile(p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcPic->getPicSym()->getFrameHeightInCU()-uiCummulativeTileHeight );
1032      }
1033    }
1034    //intialize each tile of the current picture
1035    pcPic->getPicSym()->xInitTiles();
1036
1037    // Allocate some coders, now we know how many tiles there are.
1038    Int iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
1039
1040    //generate the Coding Order Map and Inverse Coding Order Map
1041    for(p=0, uiEncCUAddr=0; p<pcPic->getPicSym()->getNumberOfCUsInFrame(); p++, uiEncCUAddr = pcPic->getPicSym()->xCalculateNxtCUAddr(uiEncCUAddr))
1042    {
1043      pcPic->getPicSym()->setCUOrderMap(p, uiEncCUAddr);
1044      pcPic->getPicSym()->setInverseCUOrderMap(uiEncCUAddr, p);
1045    }
1046    pcPic->getPicSym()->setCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());   
1047    pcPic->getPicSym()->setInverseCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());
1048
1049    // Allocate some coders, now we know how many tiles there are.
1050    m_pcEncTop->createWPPCoders(iNumSubstreams);
1051    pcSbacCoders = m_pcEncTop->getSbacCoders();
1052    pcSubstreamsOut = new TComOutputBitstream[iNumSubstreams];
1053
1054    UInt startCUAddrSliceIdx = 0; // used to index "m_uiStoredStartCUAddrForEncodingSlice" containing locations of slice boundaries
1055    UInt startCUAddrSlice    = 0; // used to keep track of current slice's starting CU addr.
1056    pcSlice->setSliceCurStartCUAddr( startCUAddrSlice ); // Setting "start CU addr" for current slice
1057    m_storedStartCUAddrForEncodingSlice.clear();
1058
1059    UInt startCUAddrSliceSegmentIdx = 0; // used to index "m_uiStoredStartCUAddrForEntropyEncodingSlice" containing locations of slice boundaries
1060    UInt startCUAddrSliceSegment    = 0; // used to keep track of current Dependent slice's starting CU addr.
1061    pcSlice->setSliceSegmentCurStartCUAddr( startCUAddrSliceSegment ); // Setting "start CU addr" for current Dependent slice
1062
1063    m_storedStartCUAddrForEncodingSliceSegment.clear();
1064    UInt nextCUAddr = 0;
1065    m_storedStartCUAddrForEncodingSlice.push_back (nextCUAddr);
1066    startCUAddrSliceIdx++;
1067    m_storedStartCUAddrForEncodingSliceSegment.push_back(nextCUAddr);
1068    startCUAddrSliceSegmentIdx++;
1069#if H_3D_NBDV
1070      if(pcSlice->getViewIndex() && !pcSlice->getIsDepth()) //Notes from QC: this condition shall be changed once the configuration is completed, e.g. in pcSlice->getSPS()->getMultiviewMvPredMode() || ARP in prev. HTM. Remove this comment once it is done.
1071      {
1072        Int iColPoc = pcSlice->getRefPOC(RefPicList(1-pcSlice->getColFromL0Flag()), pcSlice->getColRefIdx());
1073        pcPic->setNumDdvCandPics(pcPic->getDisCandRefPictures(iColPoc));
1074      }
1075#if H_3D
1076      pcSlice->setDepthToDisparityLUTs(); 
1077
1078#endif
1079#endif
1080#if MTK_NBDV_TN_FIX_E0172
1081      if(pcSlice->getViewIndex() && !pcSlice->getIsDepth() && !pcSlice->isIntra()) //Notes from QC: this condition shall be changed once the configuration is completed, e.g. in pcSlice->getSPS()->getMultiviewMvPredMode() || ARP in prev. HTM. Remove this comment once it is done.
1082      {
1083        pcPic->checkTemporalIVRef();
1084      }
1085#endif
1086    while(nextCUAddr<uiRealEndAddress) // determine slice boundaries
1087    {
1088      pcSlice->setNextSlice       ( false );
1089      pcSlice->setNextSliceSegment( false );
1090      assert(pcPic->getNumAllocatedSlice() == startCUAddrSliceIdx);
1091      m_pcSliceEncoder->precompressSlice( pcPic );
1092      m_pcSliceEncoder->compressSlice   ( pcPic );
1093
1094      Bool bNoBinBitConstraintViolated = (!pcSlice->isNextSlice() && !pcSlice->isNextSliceSegment());
1095      if (pcSlice->isNextSlice() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_LCU))
1096      {
1097        startCUAddrSlice = pcSlice->getSliceCurEndCUAddr();
1098        // Reconstruction slice
1099        m_storedStartCUAddrForEncodingSlice.push_back(startCUAddrSlice);
1100        startCUAddrSliceIdx++;
1101        // Dependent slice
1102        if (startCUAddrSliceSegmentIdx>0 && m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx-1] != startCUAddrSlice)
1103        {
1104          m_storedStartCUAddrForEncodingSliceSegment.push_back(startCUAddrSlice);
1105          startCUAddrSliceSegmentIdx++;
1106        }
1107
1108        if (startCUAddrSlice < uiRealEndAddress)
1109        {
1110          pcPic->allocateNewSlice();         
1111          pcPic->setCurrSliceIdx                  ( startCUAddrSliceIdx-1 );
1112          m_pcSliceEncoder->setSliceIdx           ( startCUAddrSliceIdx-1 );
1113          pcSlice = pcPic->getSlice               ( startCUAddrSliceIdx-1 );
1114          pcSlice->copySliceInfo                  ( pcPic->getSlice(0)      );
1115          pcSlice->setSliceIdx                    ( startCUAddrSliceIdx-1 );
1116          pcSlice->setSliceCurStartCUAddr         ( startCUAddrSlice      );
1117          pcSlice->setSliceSegmentCurStartCUAddr  ( startCUAddrSlice      );
1118          pcSlice->setSliceBits(0);
1119          uiNumSlices ++;
1120        }
1121      }
1122      else if (pcSlice->isNextSliceSegment() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_LCU))
1123      {
1124        startCUAddrSliceSegment                                                     = pcSlice->getSliceSegmentCurEndCUAddr();
1125        m_storedStartCUAddrForEncodingSliceSegment.push_back(startCUAddrSliceSegment);
1126        startCUAddrSliceSegmentIdx++;
1127        pcSlice->setSliceSegmentCurStartCUAddr( startCUAddrSliceSegment );
1128      }
1129      else
1130      {
1131        startCUAddrSlice                                                            = pcSlice->getSliceCurEndCUAddr();
1132        startCUAddrSliceSegment                                                     = pcSlice->getSliceSegmentCurEndCUAddr();
1133      }       
1134
1135      nextCUAddr = (startCUAddrSlice > startCUAddrSliceSegment) ? startCUAddrSlice : startCUAddrSliceSegment;
1136    }
1137    m_storedStartCUAddrForEncodingSlice.push_back( pcSlice->getSliceCurEndCUAddr());
1138    startCUAddrSliceIdx++;
1139    m_storedStartCUAddrForEncodingSliceSegment.push_back(pcSlice->getSliceCurEndCUAddr());
1140    startCUAddrSliceSegmentIdx++;
1141
1142    pcSlice = pcPic->getSlice(0);
1143
1144    // SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
1145    if( m_pcCfg->getSaoLcuBasedOptimization() && m_pcCfg->getSaoLcuBoundary() )
1146    {
1147      m_pcSAO->resetStats();
1148      m_pcSAO->calcSaoStatsCu_BeforeDblk( pcPic );
1149    }
1150
1151    //-- Loop filter
1152    Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
1153    m_pcLoopFilter->setCfg(bLFCrossTileBoundary);
1154    if ( m_pcCfg->getDeblockingFilterMetric() )
1155    {
1156      dblMetric(pcPic, uiNumSlices);
1157    }
1158    m_pcLoopFilter->loopFilterPic( pcPic );
1159
1160    pcSlice = pcPic->getSlice(0);
1161    if(pcSlice->getSPS()->getUseSAO())
1162    {
1163      std::vector<Bool> LFCrossSliceBoundaryFlag;
1164      for(Int s=0; s< uiNumSlices; s++)
1165      {
1166        LFCrossSliceBoundaryFlag.push_back(  ((uiNumSlices==1)?true:pcPic->getSlice(s)->getLFCrossSliceBoundaryFlag()) );
1167      }
1168      m_storedStartCUAddrForEncodingSlice.resize(uiNumSlices+1);
1169      pcPic->createNonDBFilterInfo(m_storedStartCUAddrForEncodingSlice, 0, &LFCrossSliceBoundaryFlag ,pcPic->getPicSym()->getNumTiles() ,bLFCrossTileBoundary);
1170    }
1171
1172
1173    pcSlice = pcPic->getSlice(0);
1174
1175    if(pcSlice->getSPS()->getUseSAO())
1176    {
1177      m_pcSAO->createPicSaoInfo(pcPic);
1178    }
1179
1180    /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
1181    // Set entropy coder
1182    m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
1183
1184    /* write various header sets. */
1185    if ( m_bSeqFirst )
1186    {
1187      OutputNALUnit nalu(NAL_UNIT_VPS);
1188#if H_MV
1189      if( getLayerId() == 0 )
1190      {
1191#endif
1192      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1193      m_pcEntropyCoder->encodeVPS(m_pcEncTop->getVPS());
1194      writeRBSPTrailingBits(nalu.m_Bitstream);
1195      accessUnit.push_back(new NALUnitEBSP(nalu));
1196#if RATE_CONTROL_LAMBDA_DOMAIN
1197      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
1198#endif
1199
1200#if H_MV
1201      }
1202      nalu = NALUnit(NAL_UNIT_SPS, 0, getLayerId());
1203#else
1204      nalu = NALUnit(NAL_UNIT_SPS);
1205#endif
1206      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1207      if (m_bSeqFirst)
1208      {
1209        pcSlice->getSPS()->setNumLongTermRefPicSPS(m_numLongTermRefPicSPS);
1210        for (Int k = 0; k < m_numLongTermRefPicSPS; k++)
1211        {
1212          pcSlice->getSPS()->setLtRefPicPocLsbSps(k, m_ltRefPicPocLsbSps[k]);
1213          pcSlice->getSPS()->setUsedByCurrPicLtSPSFlag(k, m_ltRefPicUsedByCurrPicFlag[k]);
1214        }
1215      }
1216      if( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() )
1217      {
1218        UInt maxCU = m_pcCfg->getSliceArgument() >> ( pcSlice->getSPS()->getMaxCUDepth() << 1);
1219        UInt numDU = ( m_pcCfg->getSliceMode() == 1 ) ? ( pcPic->getNumCUsInFrame() / maxCU ) : ( 0 );
1220        if( pcPic->getNumCUsInFrame() % maxCU != 0 || numDU == 0 )
1221        {
1222          numDU ++;
1223        }
1224        pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->setNumDU( numDU );
1225        pcSlice->getSPS()->setHrdParameters( m_pcCfg->getFrameRate(), numDU, m_pcCfg->getTargetBitrate(), ( m_pcCfg->getIntraPeriod() > 0 ) );
1226      }
1227      if( m_pcCfg->getBufferingPeriodSEIEnabled() || m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() )
1228      {
1229        pcSlice->getSPS()->getVuiParameters()->setHrdParametersPresentFlag( true );
1230      }
1231#if !H_3D
1232      m_pcEntropyCoder->encodeSPS(pcSlice->getSPS());
1233#else
1234      m_pcEntropyCoder->encodeSPS(pcSlice->getSPS(), pcSlice->getViewIndex(), pcSlice->getIsDepth() );
1235#endif
1236      writeRBSPTrailingBits(nalu.m_Bitstream);
1237      accessUnit.push_back(new NALUnitEBSP(nalu));
1238#if RATE_CONTROL_LAMBDA_DOMAIN
1239      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
1240#endif
1241
1242#if H_MV
1243      nalu = NALUnit(NAL_UNIT_PPS, 0, getLayerId());
1244#else
1245      nalu = NALUnit(NAL_UNIT_PPS);
1246#endif
1247      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1248      m_pcEntropyCoder->encodePPS(pcSlice->getPPS());
1249      writeRBSPTrailingBits(nalu.m_Bitstream);
1250      accessUnit.push_back(new NALUnitEBSP(nalu));
1251#if RATE_CONTROL_LAMBDA_DOMAIN
1252      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
1253#endif
1254
1255      xCreateLeadingSEIMessages(accessUnit, pcSlice->getSPS());
1256
1257      m_bSeqFirst = false;
1258    }
1259
1260    if (writeSOP) // write SOP description SEI (if enabled) at the beginning of GOP
1261    {
1262      Int SOPcurrPOC = pocCurr;
1263
1264      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
1265      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1266      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1267
1268      SEISOPDescription SOPDescriptionSEI;
1269      SOPDescriptionSEI.m_sopSeqParameterSetId = pcSlice->getSPS()->getSPSId();
1270
1271      UInt i = 0;
1272      UInt prevEntryId = iGOPid;
1273      for (j = iGOPid; j < m_iGopSize; j++)
1274      {
1275        Int deltaPOC = m_pcCfg->getGOPEntry(j).m_POC - m_pcCfg->getGOPEntry(prevEntryId).m_POC;
1276        if ((SOPcurrPOC + deltaPOC) < m_pcCfg->getFramesToBeEncoded())
1277        {
1278          SOPcurrPOC += deltaPOC;
1279          SOPDescriptionSEI.m_sopDescVclNaluType[i] = getNalUnitType(SOPcurrPOC, m_iLastIDR);
1280          SOPDescriptionSEI.m_sopDescTemporalId[i] = m_pcCfg->getGOPEntry(j).m_temporalId;
1281          SOPDescriptionSEI.m_sopDescStRpsIdx[i] = m_pcEncTop->getReferencePictureSetIdxForSOP(pcSlice, SOPcurrPOC, j);
1282          SOPDescriptionSEI.m_sopDescPocDelta[i] = deltaPOC;
1283
1284          prevEntryId = j;
1285          i++;
1286        }
1287      }
1288
1289      SOPDescriptionSEI.m_numPicsInSopMinus1 = i - 1;
1290
1291      m_seiWriter.writeSEImessage( nalu.m_Bitstream, SOPDescriptionSEI, pcSlice->getSPS());
1292      writeRBSPTrailingBits(nalu.m_Bitstream);
1293      accessUnit.push_back(new NALUnitEBSP(nalu));
1294
1295      writeSOP = false;
1296    }
1297
1298    if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
1299        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
1300        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
1301       || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
1302    {
1303      if( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() )
1304      {
1305        UInt numDU = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNumDU();
1306        pictureTimingSEI.m_numDecodingUnitsMinus1     = ( numDU - 1 );
1307        pictureTimingSEI.m_duCommonCpbRemovalDelayFlag = false;
1308
1309        if( pictureTimingSEI.m_numNalusInDuMinus1 == NULL )
1310        {
1311          pictureTimingSEI.m_numNalusInDuMinus1       = new UInt[ numDU ];
1312        }
1313        if( pictureTimingSEI.m_duCpbRemovalDelayMinus1  == NULL )
1314        {
1315          pictureTimingSEI.m_duCpbRemovalDelayMinus1  = new UInt[ numDU ];
1316        }
1317        if( accumBitsDU == NULL )
1318        {
1319          accumBitsDU                                  = new UInt[ numDU ];
1320        }
1321        if( accumNalsDU == NULL )
1322        {
1323          accumNalsDU                                  = new UInt[ numDU ];
1324        }
1325      }
1326      pictureTimingSEI.m_auCpbRemovalDelay = std::max<Int>(1, m_totalCoded - m_lastBPSEI); // Syntax element signalled as minus, hence the .
1327      pictureTimingSEI.m_picDpbOutputDelay = pcSlice->getSPS()->getNumReorderPics(0) + pcSlice->getPOC() - m_totalCoded;
1328      Int factor = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2;
1329      pictureTimingSEI.m_picDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
1330      if( m_pcCfg->getDecodingUnitInfoSEIEnabled() )
1331      {
1332        picSptDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
1333      }
1334    }
1335
1336    if( ( m_pcCfg->getBufferingPeriodSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) &&
1337        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) && 
1338        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
1339       || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
1340    {
1341      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
1342      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1343      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1344
1345      SEIBufferingPeriod sei_buffering_period;
1346     
1347      UInt uiInitialCpbRemovalDelay = (90000/2);                      // 0.5 sec
1348      sei_buffering_period.m_initialCpbRemovalDelay      [0][0]     = uiInitialCpbRemovalDelay;
1349      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][0]     = uiInitialCpbRemovalDelay;
1350      sei_buffering_period.m_initialCpbRemovalDelay      [0][1]     = uiInitialCpbRemovalDelay;
1351      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][1]     = uiInitialCpbRemovalDelay;
1352
1353      Double dTmp = (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getNumUnitsInTick() / (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getTimeScale();
1354
1355      UInt uiTmp = (UInt)( dTmp * 90000.0 ); 
1356      uiInitialCpbRemovalDelay -= uiTmp;
1357      uiInitialCpbRemovalDelay -= uiTmp / ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2 );
1358      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][0]  = uiInitialCpbRemovalDelay;
1359      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][0]  = uiInitialCpbRemovalDelay;
1360      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][1]  = uiInitialCpbRemovalDelay;
1361      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][1]  = uiInitialCpbRemovalDelay;
1362
1363      sei_buffering_period.m_rapCpbParamsPresentFlag              = 0;
1364      //for the concatenation, it can be set to one during splicing.
1365      sei_buffering_period.m_concatenationFlag = 0;
1366      //since the temporal layer HRD is not ready, we assumed it is fixed
1367      sei_buffering_period.m_auCpbRemovalDelayDelta = 1;
1368      sei_buffering_period.m_cpbDelayOffset = 0;
1369      sei_buffering_period.m_dpbDelayOffset = 0;
1370
1371      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_buffering_period, pcSlice->getSPS());
1372      writeRBSPTrailingBits(nalu.m_Bitstream);
1373      {
1374      UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
1375      UInt offsetPosition = m_activeParameterSetSEIPresentInAU;   // Insert BP SEI after APS SEI
1376      AccessUnit::iterator it;
1377      for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
1378      {
1379        it++;
1380      }
1381      accessUnit.insert(it, new NALUnitEBSP(nalu));
1382      m_bufferingPeriodSEIPresentInAU = true;
1383      }
1384
1385      if (m_pcCfg->getScalableNestingSEIEnabled())
1386      {
1387        OutputNALUnit naluTmp(NAL_UNIT_PREFIX_SEI);
1388        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1389        m_pcEntropyCoder->setBitstream(&naluTmp.m_Bitstream);
1390        scalableNestingSEI.m_nestedSEIs.clear();
1391        scalableNestingSEI.m_nestedSEIs.push_back(&sei_buffering_period);
1392        m_seiWriter.writeSEImessage( naluTmp.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
1393        writeRBSPTrailingBits(naluTmp.m_Bitstream);
1394        UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
1395        UInt offsetPosition = m_activeParameterSetSEIPresentInAU + m_bufferingPeriodSEIPresentInAU + m_pictureTimingSEIPresentInAU;   // Insert BP SEI after non-nested APS, BP and PT SEIs
1396        AccessUnit::iterator it;
1397        for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
1398        {
1399          it++;
1400        }
1401        accessUnit.insert(it, new NALUnitEBSP(naluTmp));
1402        m_nestedBufferingPeriodSEIPresentInAU = true;
1403      }
1404
1405      m_lastBPSEI = m_totalCoded;
1406      m_cpbRemovalDelay = 0;
1407    }
1408    m_cpbRemovalDelay ++;
1409    if( ( m_pcEncTop->getRecoveryPointSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) )
1410    {
1411      if( m_pcEncTop->getGradualDecodingRefreshInfoEnabled() && !pcSlice->getRapPicFlag() )
1412      {
1413        // Gradual decoding refresh SEI
1414        OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
1415        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1416        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1417
1418        SEIGradualDecodingRefreshInfo seiGradualDecodingRefreshInfo;
1419        seiGradualDecodingRefreshInfo.m_gdrForegroundFlag = true; // Indicating all "foreground"
1420
1421        m_seiWriter.writeSEImessage( nalu.m_Bitstream, seiGradualDecodingRefreshInfo, pcSlice->getSPS() );
1422        writeRBSPTrailingBits(nalu.m_Bitstream);
1423        accessUnit.push_back(new NALUnitEBSP(nalu));
1424      }
1425    // Recovery point SEI
1426      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
1427      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1428      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1429
1430      SEIRecoveryPoint sei_recovery_point;
1431      sei_recovery_point.m_recoveryPocCnt    = 0;
1432      sei_recovery_point.m_exactMatchingFlag = ( pcSlice->getPOC() == 0 ) ? (true) : (false);
1433      sei_recovery_point.m_brokenLinkFlag    = false;
1434
1435      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_recovery_point, pcSlice->getSPS() );
1436      writeRBSPTrailingBits(nalu.m_Bitstream);
1437      accessUnit.push_back(new NALUnitEBSP(nalu));
1438    }
1439
1440    /* use the main bitstream buffer for storing the marshalled picture */
1441    m_pcEntropyCoder->setBitstream(NULL);
1442
1443    startCUAddrSliceIdx = 0;
1444    startCUAddrSlice    = 0; 
1445
1446    startCUAddrSliceSegmentIdx = 0;
1447    startCUAddrSliceSegment    = 0; 
1448    nextCUAddr                 = 0;
1449    pcSlice = pcPic->getSlice(startCUAddrSliceIdx);
1450
1451    Int processingState = (pcSlice->getSPS()->getUseSAO())?(EXECUTE_INLOOPFILTER):(ENCODE_SLICE);
1452    Bool skippedSlice=false;
1453    while (nextCUAddr < uiRealEndAddress) // Iterate over all slices
1454    {
1455      switch(processingState)
1456      {
1457      case ENCODE_SLICE:
1458        {
1459          pcSlice->setNextSlice       ( false );
1460          pcSlice->setNextSliceSegment( false );
1461          if (nextCUAddr == m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx])
1462          {
1463            pcSlice = pcPic->getSlice(startCUAddrSliceIdx);
1464            if(startCUAddrSliceIdx > 0 && pcSlice->getSliceType()!= I_SLICE)
1465            {
1466              pcSlice->checkColRefIdx(startCUAddrSliceIdx, pcPic);
1467            }
1468            pcPic->setCurrSliceIdx(startCUAddrSliceIdx);
1469            m_pcSliceEncoder->setSliceIdx(startCUAddrSliceIdx);
1470            assert(startCUAddrSliceIdx == pcSlice->getSliceIdx());
1471            // Reconstruction slice
1472            pcSlice->setSliceCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
1473            pcSlice->setSliceCurEndCUAddr  ( m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx+1 ] );
1474            // Dependent slice
1475            pcSlice->setSliceSegmentCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
1476            pcSlice->setSliceSegmentCurEndCUAddr  ( m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx+1 ] );
1477
1478            pcSlice->setNextSlice       ( true );
1479
1480            startCUAddrSliceIdx++;
1481            startCUAddrSliceSegmentIdx++;
1482          } 
1483          else if (nextCUAddr == m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx])
1484          {
1485            // Dependent slice
1486            pcSlice->setSliceSegmentCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
1487            pcSlice->setSliceSegmentCurEndCUAddr  ( m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx+1 ] );
1488
1489            pcSlice->setNextSliceSegment( true );
1490
1491            startCUAddrSliceSegmentIdx++;
1492          }
1493
1494          pcSlice->setRPS(pcPic->getSlice(0)->getRPS());
1495          pcSlice->setRPSidx(pcPic->getSlice(0)->getRPSidx());
1496          UInt uiDummyStartCUAddr;
1497          UInt uiDummyBoundingCUAddr;
1498          m_pcSliceEncoder->xDetermineStartAndBoundingCUAddr(uiDummyStartCUAddr,uiDummyBoundingCUAddr,pcPic,true);
1499
1500          uiInternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) % pcPic->getNumPartInCU();
1501          uiExternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) / pcPic->getNumPartInCU();
1502          uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
1503          uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
1504          uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
1505          uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
1506          while(uiPosX>=uiWidth||uiPosY>=uiHeight)
1507          {
1508            uiInternalAddress--;
1509            uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
1510            uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
1511          }
1512          uiInternalAddress++;
1513          if(uiInternalAddress==pcPic->getNumPartInCU())
1514          {
1515            uiInternalAddress = 0;
1516            uiExternalAddress = pcPic->getPicSym()->getCUOrderMap(pcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
1517          }
1518          UInt endAddress = pcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress);
1519          if(endAddress<=pcSlice->getSliceSegmentCurStartCUAddr()) 
1520          {
1521            UInt boundingAddrSlice, boundingAddrSliceSegment;
1522            boundingAddrSlice          = m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx];         
1523            boundingAddrSliceSegment = m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx];         
1524            nextCUAddr               = min(boundingAddrSlice, boundingAddrSliceSegment);
1525            if(pcSlice->isNextSlice())
1526            {
1527              skippedSlice=true;
1528            }
1529            continue;
1530          }
1531          if(skippedSlice) 
1532          {
1533            pcSlice->setNextSlice       ( true );
1534            pcSlice->setNextSliceSegment( false );
1535          }
1536          skippedSlice=false;
1537          pcSlice->allocSubstreamSizes( iNumSubstreams );
1538          for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
1539          {
1540            pcSubstreamsOut[ui].clear();
1541          }
1542
1543          m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
1544          m_pcEntropyCoder->resetEntropy      ();
1545          /* start slice NALunit */
1546#if H_MV
1547          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer(), getLayerId() );
1548#else
1549          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer() );
1550#endif
1551          Bool sliceSegment = (!pcSlice->isNextSlice());
1552          if (!sliceSegment)
1553          {
1554            uiOneBitstreamPerSliceLength = 0; // start of a new slice
1555          }
1556          m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1557#if RATE_CONTROL_LAMBDA_DOMAIN
1558          tmpBitsBeforeWriting = m_pcEntropyCoder->getNumberOfWrittenBits();
1559#endif
1560          m_pcEntropyCoder->encodeSliceHeader(pcSlice);
1561#if RATE_CONTROL_LAMBDA_DOMAIN
1562          actualHeadBits += ( m_pcEntropyCoder->getNumberOfWrittenBits() - tmpBitsBeforeWriting );
1563#endif
1564
1565          // is it needed?
1566          {
1567            if (!sliceSegment)
1568            {
1569              pcBitstreamRedirect->writeAlignOne();
1570            }
1571            else
1572            {
1573              // We've not completed our slice header info yet, do the alignment later.
1574            }
1575            m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
1576            m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
1577            m_pcEntropyCoder->resetEntropy    ();
1578            for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams() ; ui++ )
1579            {
1580              m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[ui], pcSlice );
1581              m_pcEntropyCoder->resetEntropy    ();
1582            }
1583          }
1584
1585          if(pcSlice->isNextSlice())
1586          {
1587            // set entropy coder for writing
1588            m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
1589            {
1590              for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams() ; ui++ )
1591              {
1592                m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[ui], pcSlice );
1593                m_pcEntropyCoder->resetEntropy    ();
1594              }
1595              pcSbacCoders[0].load(m_pcSbacCoder);
1596              m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[0], pcSlice );  //ALF is written in substream #0 with CABAC coder #0 (see ALF param encoding below)
1597            }
1598            m_pcEntropyCoder->resetEntropy    ();
1599            // File writing
1600            if (!sliceSegment)
1601            {
1602              m_pcEntropyCoder->setBitstream(pcBitstreamRedirect);
1603            }
1604            else
1605            {
1606              m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1607            }
1608            // for now, override the TILES_DECODER setting in order to write substreams.
1609            m_pcEntropyCoder->setBitstream    ( &pcSubstreamsOut[0] );
1610
1611          }
1612          pcSlice->setFinalized(true);
1613
1614          m_pcSbacCoder->load( &pcSbacCoders[0] );
1615
1616          pcSlice->setTileOffstForMultES( uiOneBitstreamPerSliceLength );
1617            pcSlice->setTileLocationCount ( 0 );
1618          m_pcSliceEncoder->encodeSlice(pcPic, pcSubstreamsOut);
1619
1620          {
1621            // Construct the final bitstream by flushing and concatenating substreams.
1622            // The final bitstream is either nalu.m_Bitstream or pcBitstreamRedirect;
1623            UInt* puiSubstreamSizes = pcSlice->getSubstreamSizes();
1624            UInt uiTotalCodedSize = 0; // for padding calcs.
1625            UInt uiNumSubstreamsPerTile = iNumSubstreams;
1626            if (iNumSubstreams > 1)
1627            {
1628              uiNumSubstreamsPerTile /= pcPic->getPicSym()->getNumTiles();
1629            }
1630            for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
1631            {
1632              // Flush all substreams -- this includes empty ones.
1633              // Terminating bit and flush.
1634              m_pcEntropyCoder->setEntropyCoder   ( &pcSbacCoders[ui], pcSlice );
1635              m_pcEntropyCoder->setBitstream      (  &pcSubstreamsOut[ui] );
1636              m_pcEntropyCoder->encodeTerminatingBit( 1 );
1637              m_pcEntropyCoder->encodeSliceFinish();
1638
1639              pcSubstreamsOut[ui].writeByteAlignment();   // Byte-alignment in slice_data() at end of sub-stream
1640              // Byte alignment is necessary between tiles when tiles are independent.
1641              uiTotalCodedSize += pcSubstreamsOut[ui].getNumberOfWrittenBits();
1642
1643              Bool bNextSubstreamInNewTile = ((ui+1) < iNumSubstreams)&& ((ui+1)%uiNumSubstreamsPerTile == 0);
1644              if (bNextSubstreamInNewTile)
1645              {
1646                pcSlice->setTileLocation(ui/uiNumSubstreamsPerTile, pcSlice->getTileOffstForMultES()+(uiTotalCodedSize>>3));
1647              }
1648              if (ui+1 < pcSlice->getPPS()->getNumSubstreams())
1649              {
1650                puiSubstreamSizes[ui] = pcSubstreamsOut[ui].getNumberOfWrittenBits() + (pcSubstreamsOut[ui].countStartCodeEmulations()<<3);
1651              }
1652            }
1653
1654            // Complete the slice header info.
1655            m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
1656            m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1657            m_pcEntropyCoder->encodeTilesWPPEntryPoint( pcSlice );
1658
1659            // Substreams...
1660            TComOutputBitstream *pcOut = pcBitstreamRedirect;
1661          Int offs = 0;
1662          Int nss = pcSlice->getPPS()->getNumSubstreams();
1663          if (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
1664          {
1665            // 1st line present for WPP.
1666            offs = pcSlice->getSliceSegmentCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU()/pcSlice->getPic()->getFrameWidthInCU();
1667            nss  = pcSlice->getNumEntryPointOffsets()+1;
1668          }
1669          for ( UInt ui = 0 ; ui < nss; ui++ )
1670          {
1671            pcOut->addSubstream(&pcSubstreamsOut[ui+offs]);
1672            }
1673          }
1674
1675          UInt boundingAddrSlice, boundingAddrSliceSegment;
1676          boundingAddrSlice        = m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx];         
1677          boundingAddrSliceSegment = m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx];         
1678          nextCUAddr               = min(boundingAddrSlice, boundingAddrSliceSegment);
1679          // If current NALU is the first NALU of slice (containing slice header) and more NALUs exist (due to multiple dependent slices) then buffer it.
1680          // If current NALU is the last NALU of slice and a NALU was buffered, then (a) Write current NALU (b) Update an write buffered NALU at approproate location in NALU list.
1681          Bool bNALUAlignedWrittenToList    = false; // used to ensure current NALU is not written more than once to the NALU list.
1682          xAttachSliceDataToNalUnit(nalu, pcBitstreamRedirect);
1683          accessUnit.push_back(new NALUnitEBSP(nalu));
1684#if RATE_CONTROL_LAMBDA_DOMAIN
1685          actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
1686#endif
1687          bNALUAlignedWrittenToList = true; 
1688          uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits(); // length of bitstream after byte-alignment
1689
1690          if (!bNALUAlignedWrittenToList)
1691          {
1692            {
1693              nalu.m_Bitstream.writeAlignZero();
1694            }
1695            accessUnit.push_back(new NALUnitEBSP(nalu));
1696            uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits() + 24; // length of bitstream after byte-alignment + 3 byte startcode 0x000001
1697          }
1698
1699          if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
1700              ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
1701              ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
1702             || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) &&
1703              ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() ) )
1704          {
1705              UInt numNalus = 0;
1706            UInt numRBSPBytes = 0;
1707            for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
1708            {
1709              UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
1710              if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
1711              {
1712                numRBSPBytes += numRBSPBytes_nal;
1713                numNalus ++;
1714              }
1715            }
1716            accumBitsDU[ pcSlice->getSliceIdx() ] = ( numRBSPBytes << 3 );
1717            accumNalsDU[ pcSlice->getSliceIdx() ] = numNalus;   // SEI not counted for bit count; hence shouldn't be counted for # of NALUs - only for consistency
1718          }
1719          processingState = ENCODE_SLICE;
1720          }
1721          break;
1722        case EXECUTE_INLOOPFILTER:
1723          {
1724            // set entropy coder for RD
1725            m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
1726            if ( pcSlice->getSPS()->getUseSAO() )
1727            {
1728              m_pcEntropyCoder->resetEntropy();
1729              m_pcEntropyCoder->setBitstream( m_pcBitCounter );
1730              m_pcSAO->startSaoEnc(pcPic, m_pcEntropyCoder, m_pcEncTop->getRDSbacCoder(), m_pcEncTop->getRDGoOnSbacCoder());
1731              SAOParam& cSaoParam = *pcSlice->getPic()->getPicSym()->getSaoParam();
1732
1733#if SAO_CHROMA_LAMBDA
1734#if SAO_ENCODING_CHOICE
1735              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma(), pcPic->getSlice(0)->getDepth());
1736#else
1737              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma());
1738#endif
1739#else
1740              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambda());
1741#endif
1742              m_pcSAO->endSaoEnc();
1743              m_pcSAO->PCMLFDisableProcess(pcPic);
1744            }
1745#if SAO_RDO
1746            m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
1747#endif
1748            processingState = ENCODE_SLICE;
1749
1750            for(Int s=0; s< uiNumSlices; s++)
1751            {
1752              if (pcSlice->getSPS()->getUseSAO())
1753              {
1754                pcPic->getSlice(s)->setSaoEnabledFlag((pcSlice->getPic()->getPicSym()->getSaoParam()->bSaoFlag[0]==1)?true:false);
1755              }
1756            }
1757          }
1758          break;
1759        default:
1760          {
1761            printf("Not a supported encoding state\n");
1762            assert(0);
1763            exit(-1);
1764          }
1765        }
1766      } // end iteration over slices
1767
1768      if(pcSlice->getSPS()->getUseSAO())
1769      {
1770        if(pcSlice->getSPS()->getUseSAO())
1771        {
1772          m_pcSAO->destroyPicSaoInfo();
1773        }
1774        pcPic->destroyNonDBFilterInfo();
1775      }
1776
1777#if !H_3D
1778      pcPic->compressMotion(); 
1779#endif
1780#if H_MV
1781      m_pocLastCoded = pcPic->getPOC();
1782#endif
1783
1784      //-- For time output for each slice
1785      Double dEncTime = (Double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
1786
1787      const Char* digestStr = NULL;
1788      if (m_pcCfg->getDecodedPictureHashSEIEnabled())
1789      {
1790        /* calculate MD5sum for entire reconstructed picture */
1791        SEIDecodedPictureHash sei_recon_picture_digest;
1792        if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
1793        {
1794          sei_recon_picture_digest.method = SEIDecodedPictureHash::MD5;
1795          calcMD5(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
1796          digestStr = digestToString(sei_recon_picture_digest.digest, 16);
1797        }
1798        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
1799        {
1800          sei_recon_picture_digest.method = SEIDecodedPictureHash::CRC;
1801          calcCRC(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
1802          digestStr = digestToString(sei_recon_picture_digest.digest, 2);
1803        }
1804        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
1805        {
1806          sei_recon_picture_digest.method = SEIDecodedPictureHash::CHECKSUM;
1807          calcChecksum(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
1808          digestStr = digestToString(sei_recon_picture_digest.digest, 4);
1809        }
1810        OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer());
1811
1812        /* write the SEI messages */
1813        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1814        m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_recon_picture_digest, pcSlice->getSPS());
1815        writeRBSPTrailingBits(nalu.m_Bitstream);
1816
1817        accessUnit.insert(accessUnit.end(), new NALUnitEBSP(nalu));
1818      }
1819      if (m_pcCfg->getTemporalLevel0IndexSEIEnabled())
1820      {
1821        SEITemporalLevel0Index sei_temporal_level0_index;
1822        if (pcSlice->getRapPicFlag())
1823        {
1824          m_tl0Idx = 0;
1825          m_rapIdx = (m_rapIdx + 1) & 0xFF;
1826        }
1827        else
1828        {
1829          m_tl0Idx = (m_tl0Idx + (pcSlice->getTLayer() ? 0 : 1)) & 0xFF;
1830        }
1831        sei_temporal_level0_index.tl0Idx = m_tl0Idx;
1832        sei_temporal_level0_index.rapIdx = m_rapIdx;
1833
1834        OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI); 
1835
1836        /* write the SEI messages */
1837        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1838        m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_temporal_level0_index, pcSlice->getSPS());
1839        writeRBSPTrailingBits(nalu.m_Bitstream);
1840
1841        /* insert the SEI message NALUnit before any Slice NALUnits */
1842        AccessUnit::iterator it = find_if(accessUnit.begin(), accessUnit.end(), mem_fun(&NALUnit::isSlice));
1843        accessUnit.insert(it, new NALUnitEBSP(nalu));
1844      }
1845
1846      xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime );
1847
1848      if (digestStr)
1849      {
1850        if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
1851        {
1852          printf(" [MD5:%s]", digestStr);
1853        }
1854        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
1855        {
1856          printf(" [CRC:%s]", digestStr);
1857        }
1858        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
1859        {
1860          printf(" [Checksum:%s]", digestStr);
1861        }
1862      }
1863#if RATE_CONTROL_LAMBDA_DOMAIN
1864      if ( m_pcCfg->getUseRateCtrl() )
1865      {
1866#if !M0036_RC_IMPROVEMENT
1867        Double effectivePercentage = m_pcRateCtrl->getRCPic()->getEffectivePercentage();
1868#endif
1869        Double avgQP     = m_pcRateCtrl->getRCPic()->calAverageQP();
1870        Double avgLambda = m_pcRateCtrl->getRCPic()->calAverageLambda();
1871        if ( avgLambda < 0.0 )
1872        {
1873          avgLambda = lambda;
1874        }
1875#if M0036_RC_IMPROVEMENT
1876#if RATE_CONTROL_INTRA
1877        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, pcSlice->getSliceType());
1878#else
1879        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda );
1880#endif
1881#else
1882        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, effectivePercentage );
1883#endif
1884        m_pcRateCtrl->getRCPic()->addToPictureLsit( m_pcRateCtrl->getPicList() );
1885
1886        m_pcRateCtrl->getRCSeq()->updateAfterPic( actualTotalBits );
1887        if ( pcSlice->getSliceType() != I_SLICE )
1888        {
1889          m_pcRateCtrl->getRCGOP()->updateAfterPicture( actualTotalBits );
1890        }
1891        else    // for intra picture, the estimated bits are used to update the current status in the GOP
1892        {
1893          m_pcRateCtrl->getRCGOP()->updateAfterPicture( estimatedBits );
1894        }
1895      }
1896#else
1897      if(m_pcCfg->getUseRateCtrl())
1898      {
1899        UInt  frameBits = m_vRVM_RP[m_vRVM_RP.size()-1];
1900        m_pcRateCtrl->updataRCFrameStatus((Int)frameBits, pcSlice->getSliceType());
1901      }
1902#endif
1903
1904      if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
1905          ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
1906          ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
1907         || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
1908      {
1909        TComVUI *vui = pcSlice->getSPS()->getVuiParameters();
1910        TComHRD *hrd = vui->getHrdParameters();
1911
1912        if( hrd->getSubPicCpbParamsPresentFlag() )
1913        {
1914          Int i;
1915          UInt64 ui64Tmp;
1916          UInt uiPrev = 0;
1917          UInt numDU = ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 );
1918          UInt *pCRD = &pictureTimingSEI.m_duCpbRemovalDelayMinus1[0];
1919          UInt maxDiff = ( hrd->getTickDivisorMinus2() + 2 ) - 1;
1920
1921          for( i = 0; i < numDU; i ++ )
1922          {
1923            pictureTimingSEI.m_numNalusInDuMinus1[ i ]       = ( i == 0 ) ? ( accumNalsDU[ i ] - 1 ) : ( accumNalsDU[ i ] - accumNalsDU[ i - 1] - 1 );
1924          }
1925
1926          if( numDU == 1 )
1927          {
1928            pCRD[ 0 ] = 0; /* don't care */
1929          }
1930          else
1931          {
1932            pCRD[ numDU - 1 ] = 0;/* by definition */
1933            UInt tmp = 0;
1934            UInt accum = 0;
1935
1936            for( i = ( numDU - 2 ); i >= 0; i -- )
1937            {
1938              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
1939              if( (UInt)ui64Tmp > maxDiff )
1940              {
1941                tmp ++;
1942              }
1943            }
1944            uiPrev = 0;
1945
1946            UInt flag = 0;
1947            for( i = ( numDU - 2 ); i >= 0; i -- )
1948            {
1949              flag = 0;
1950              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
1951
1952              if( (UInt)ui64Tmp > maxDiff )
1953              {
1954                if(uiPrev >= maxDiff - tmp)
1955                {
1956                  ui64Tmp = uiPrev + 1;
1957                  flag = 1;
1958                }
1959                else                            ui64Tmp = maxDiff - tmp + 1;
1960              }
1961              pCRD[ i ] = (UInt)ui64Tmp - uiPrev - 1;
1962              if( (Int)pCRD[ i ] < 0 )
1963              {
1964                pCRD[ i ] = 0;
1965              }
1966              else if (tmp > 0 && flag == 1) 
1967              {
1968                tmp --;
1969              }
1970              accum += pCRD[ i ] + 1;
1971              uiPrev = accum;
1972            }
1973          }
1974        }
1975        if( m_pcCfg->getPictureTimingSEIEnabled() )
1976        {
1977          {
1978            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
1979          m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1980          m_seiWriter.writeSEImessage(nalu.m_Bitstream, pictureTimingSEI, pcSlice->getSPS());
1981          writeRBSPTrailingBits(nalu.m_Bitstream);
1982          UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
1983          UInt offsetPosition = m_activeParameterSetSEIPresentInAU
1984                                    + m_bufferingPeriodSEIPresentInAU;    // Insert PT SEI after APS and BP SEI
1985          AccessUnit::iterator it;
1986          for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
1987          {
1988            it++;
1989          }
1990          accessUnit.insert(it, new NALUnitEBSP(nalu));
1991          m_pictureTimingSEIPresentInAU = true;
1992        }
1993          if ( m_pcCfg->getScalableNestingSEIEnabled() ) // put picture timing SEI into scalable nesting SEI
1994          {
1995            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
1996            m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1997            scalableNestingSEI.m_nestedSEIs.clear();
1998            scalableNestingSEI.m_nestedSEIs.push_back(&pictureTimingSEI);
1999            m_seiWriter.writeSEImessage(nalu.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
2000            writeRBSPTrailingBits(nalu.m_Bitstream);
2001            UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
2002            UInt offsetPosition = m_activeParameterSetSEIPresentInAU
2003              + m_bufferingPeriodSEIPresentInAU + m_pictureTimingSEIPresentInAU + m_nestedBufferingPeriodSEIPresentInAU;    // Insert PT SEI after APS and BP SEI
2004            AccessUnit::iterator it;
2005            for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
2006            {
2007              it++;
2008            }
2009            accessUnit.insert(it, new NALUnitEBSP(nalu));
2010            m_nestedPictureTimingSEIPresentInAU = true;
2011          }
2012        }
2013        if( m_pcCfg->getDecodingUnitInfoSEIEnabled() && hrd->getSubPicCpbParamsPresentFlag() )
2014        {             
2015          m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
2016          for( Int i = 0; i < ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 ); i ++ )
2017          {
2018            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
2019
2020            SEIDecodingUnitInfo tempSEI;
2021            tempSEI.m_decodingUnitIdx = i;
2022            tempSEI.m_duSptCpbRemovalDelay = pictureTimingSEI.m_duCpbRemovalDelayMinus1[i] + 1;
2023            tempSEI.m_dpbOutputDuDelayPresentFlag = false;
2024            tempSEI.m_picSptDpbOutputDuDelay = picSptDpbOutputDuDelay;
2025
2026            AccessUnit::iterator it;
2027            // Insert the first one in the right location, before the first slice
2028            if(i == 0)
2029            {
2030              // Insert before the first slice.
2031              m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, pcSlice->getSPS());
2032              writeRBSPTrailingBits(nalu.m_Bitstream);
2033
2034              UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
2035              UInt offsetPosition = m_activeParameterSetSEIPresentInAU
2036                                    + m_bufferingPeriodSEIPresentInAU
2037                                    + m_pictureTimingSEIPresentInAU;  // Insert DU info SEI after APS, BP and PT SEI
2038              for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
2039              {
2040                it++;
2041              }
2042              accessUnit.insert(it, new NALUnitEBSP(nalu));
2043            }
2044            else
2045            {
2046              Int ctr;
2047              // For the second decoding unit onwards we know how many NALUs are present
2048              for (ctr = 0, it = accessUnit.begin(); it != accessUnit.end(); it++)
2049              {           
2050                if(ctr == accumNalsDU[ i - 1 ])
2051                {
2052                  // Insert before the first slice.
2053                  m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, pcSlice->getSPS());
2054                  writeRBSPTrailingBits(nalu.m_Bitstream);
2055
2056                  accessUnit.insert(it, new NALUnitEBSP(nalu));
2057                  break;
2058                }
2059                if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
2060                {
2061                  ctr++;
2062                }
2063              }
2064            }           
2065          }
2066        }
2067      }
2068      xResetNonNestedSEIPresentFlags();
2069      xResetNestedSEIPresentFlags();
2070      pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
2071
2072      pcPic->setReconMark   ( true );
2073#if H_MV
2074      TComSlice::markIvRefPicsAsShortTerm( m_refPicSetInterLayer ); 
2075      std::vector<Int> temp; 
2076      TComSlice::markCurrPic( pcPic ); 
2077      TComSlice::markIvRefPicsAsUnused   ( m_ivPicLists, temp, pcPic->getSlice(0)->getVPS(), m_layerId, pcPic->getPOC() ); 
2078#endif
2079      m_bFirst = false;
2080      m_iNumPicCoded++;
2081      m_totalCoded ++;
2082      /* logging: insert a newline at end of picture period */
2083      printf("\n");
2084      fflush(stdout);
2085
2086      delete[] pcSubstreamsOut;
2087  }
2088#if !RATE_CONTROL_LAMBDA_DOMAIN
2089  if(m_pcCfg->getUseRateCtrl())
2090  {
2091    m_pcRateCtrl->updateRCGOPStatus();
2092  }
2093#endif
2094  delete pcBitstreamRedirect;
2095
2096  if( accumBitsDU != NULL) delete accumBitsDU;
2097  if( accumNalsDU != NULL) delete accumNalsDU;
2098
2099#if !H_MV
2100  assert ( m_iNumPicCoded == iNumPicRcvd );
2101#endif
2102}
2103
2104#if !H_MV
2105Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded)
2106{
2107  assert (uiNumAllPicCoded == m_gcAnalyzeAll.getNumPic());
2108 
2109   
2110  //--CFG_KDY
2111  m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() );
2112  m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() );
2113  m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() );
2114  m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() );
2115 
2116  //-- all
2117  printf( "\n\nSUMMARY --------------------------------------------------------\n" );
2118  m_gcAnalyzeAll.printOut('a');
2119 
2120  printf( "\n\nI Slices--------------------------------------------------------\n" );
2121  m_gcAnalyzeI.printOut('i');
2122 
2123  printf( "\n\nP Slices--------------------------------------------------------\n" );
2124  m_gcAnalyzeP.printOut('p');
2125 
2126  printf( "\n\nB Slices--------------------------------------------------------\n" );
2127  m_gcAnalyzeB.printOut('b');
2128 
2129#if _SUMMARY_OUT_
2130  m_gcAnalyzeAll.printSummaryOut();
2131#endif
2132#if _SUMMARY_PIC_
2133  m_gcAnalyzeI.printSummary('I');
2134  m_gcAnalyzeP.printSummary('P');
2135  m_gcAnalyzeB.printSummary('B');
2136#endif
2137
2138  printf("\nRVM: %.3lf\n" , xCalculateRVM());
2139}
2140#endif
2141#if H_3D_VSO
2142Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, Dist64& ruiDist, UInt64& ruiBits )
2143#else
2144Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits )
2145#endif
2146{
2147  TComSlice* pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
2148  Bool bCalcDist = false;
2149  m_pcLoopFilter->setCfg(m_pcCfg->getLFCrossTileBoundaryFlag());
2150  m_pcLoopFilter->loopFilterPic( pcPic );
2151 
2152  m_pcEntropyCoder->setEntropyCoder ( m_pcEncTop->getRDGoOnSbacCoder(), pcSlice );
2153  m_pcEntropyCoder->resetEntropy    ();
2154  m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
2155  pcSlice = pcPic->getSlice(0);
2156  if(pcSlice->getSPS()->getUseSAO())
2157  {
2158    std::vector<Bool> LFCrossSliceBoundaryFlag(1, true);
2159    std::vector<Int>  sliceStartAddress;
2160    sliceStartAddress.push_back(0);
2161    sliceStartAddress.push_back(pcPic->getNumCUsInFrame()* pcPic->getNumPartInCU());
2162    pcPic->createNonDBFilterInfo(sliceStartAddress, 0, &LFCrossSliceBoundaryFlag);
2163  }
2164 
2165  if( pcSlice->getSPS()->getUseSAO())
2166  {
2167    pcPic->destroyNonDBFilterInfo();
2168  }
2169 
2170  m_pcEntropyCoder->resetEntropy    ();
2171  ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
2172 
2173  if (!bCalcDist)
2174    ruiDist = xFindDistortionFrame(pcPic->getPicYuvOrg(), pcPic->getPicYuvRec());
2175}
2176
2177// ====================================================================================================================
2178// Protected member functions
2179// ====================================================================================================================
2180
2181Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut )
2182{
2183  assert( iNumPicRcvd > 0 );
2184  //  Exception for the first frame
2185  if ( iPOCLast == 0 )
2186  {
2187    m_iGopSize    = 1;
2188  }
2189  else
2190    m_iGopSize    = m_pcCfg->getGOPSize();
2191 
2192  assert (m_iGopSize > 0); 
2193
2194  return;
2195}
2196
2197Void TEncGOP::xGetBuffer( TComList<TComPic*>&      rcListPic,
2198                         TComList<TComPicYuv*>&    rcListPicYuvRecOut,
2199                         Int                       iNumPicRcvd,
2200                         Int                       iTimeOffset,
2201                         TComPic*&                 rpcPic,
2202                         TComPicYuv*&              rpcPicYuvRecOut,
2203                         Int                       pocCurr )
2204{
2205  Int i;
2206  //  Rec. output
2207  TComList<TComPicYuv*>::iterator     iterPicYuvRec = rcListPicYuvRecOut.end();
2208  for ( i = 0; i < iNumPicRcvd - iTimeOffset + 1; i++ )
2209  {
2210    iterPicYuvRec--;
2211  }
2212 
2213  rpcPicYuvRecOut = *(iterPicYuvRec);
2214 
2215  //  Current pic.
2216  TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
2217  while (iterPic != rcListPic.end())
2218  {
2219    rpcPic = *(iterPic);
2220    rpcPic->setCurrSliceIdx(0);
2221    if (rpcPic->getPOC() == pocCurr)
2222    {
2223      break;
2224    }
2225    iterPic++;
2226  }
2227 
2228  assert (rpcPic->getPOC() == pocCurr);
2229 
2230  return;
2231}
2232
2233#if H_3D_VSO
2234Dist64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1)
2235#else
2236UInt64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1)
2237#endif
2238{
2239  Int     x, y;
2240  Pel*  pSrc0   = pcPic0 ->getLumaAddr();
2241  Pel*  pSrc1   = pcPic1 ->getLumaAddr();
2242  UInt  uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthY-8);
2243  Int   iTemp;
2244 
2245  Int   iStride = pcPic0->getStride();
2246  Int   iWidth  = pcPic0->getWidth();
2247  Int   iHeight = pcPic0->getHeight();
2248 
2249#if H_3D_VSO
2250  Dist64  uiTotalDiff = 0;
2251#else
2252  UInt64  uiTotalDiff = 0;
2253#endif
2254 
2255  for( y = 0; y < iHeight; y++ )
2256  {
2257    for( x = 0; x < iWidth; x++ )
2258    {
2259      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
2260    }
2261    pSrc0 += iStride;
2262    pSrc1 += iStride;
2263  }
2264 
2265  uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthC-8);
2266  iHeight >>= 1;
2267  iWidth  >>= 1;
2268  iStride >>= 1;
2269 
2270  pSrc0  = pcPic0->getCbAddr();
2271  pSrc1  = pcPic1->getCbAddr();
2272 
2273  for( y = 0; y < iHeight; y++ )
2274  {
2275    for( x = 0; x < iWidth; x++ )
2276    {
2277      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
2278    }
2279    pSrc0 += iStride;
2280    pSrc1 += iStride;
2281  }
2282 
2283  pSrc0  = pcPic0->getCrAddr();
2284  pSrc1  = pcPic1->getCrAddr();
2285 
2286  for( y = 0; y < iHeight; y++ )
2287  {
2288    for( x = 0; x < iWidth; x++ )
2289    {
2290      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
2291    }
2292    pSrc0 += iStride;
2293    pSrc1 += iStride;
2294  }
2295 
2296  return uiTotalDiff;
2297}
2298
2299#if VERBOSE_RATE
2300static const Char* nalUnitTypeToString(NalUnitType type)
2301{
2302  switch (type)
2303  {
2304    case NAL_UNIT_CODED_SLICE_TRAIL_R: return "TRAIL_R";
2305    case NAL_UNIT_CODED_SLICE_TRAIL_N: return "TRAIL_N";
2306    case NAL_UNIT_CODED_SLICE_TLA_R:      return "TLA_R";
2307    case NAL_UNIT_CODED_SLICE_TSA_N: return "TSA_N";
2308    case NAL_UNIT_CODED_SLICE_STSA_R: return "STSA_R";
2309    case NAL_UNIT_CODED_SLICE_STSA_N: return "STSA_N";
2310    case NAL_UNIT_CODED_SLICE_BLA_W_LP:   return "BLA_W_LP";
2311    case NAL_UNIT_CODED_SLICE_BLA_W_RADL: return "BLA_W_RADL";
2312    case NAL_UNIT_CODED_SLICE_BLA_N_LP: return "BLA_N_LP";
2313    case NAL_UNIT_CODED_SLICE_IDR_W_RADL: return "IDR_W_RADL";
2314    case NAL_UNIT_CODED_SLICE_IDR_N_LP: return "IDR_N_LP";
2315    case NAL_UNIT_CODED_SLICE_CRA: return "CRA";
2316    case NAL_UNIT_CODED_SLICE_RADL_R:     return "RADL_R";
2317    case NAL_UNIT_CODED_SLICE_RASL_R:     return "RASL_R";
2318    case NAL_UNIT_VPS: return "VPS";
2319    case NAL_UNIT_SPS: return "SPS";
2320    case NAL_UNIT_PPS: return "PPS";
2321    case NAL_UNIT_ACCESS_UNIT_DELIMITER: return "AUD";
2322    case NAL_UNIT_EOS: return "EOS";
2323    case NAL_UNIT_EOB: return "EOB";
2324    case NAL_UNIT_FILLER_DATA: return "FILLER";
2325    case NAL_UNIT_PREFIX_SEI:             return "SEI";
2326    case NAL_UNIT_SUFFIX_SEI:             return "SEI";
2327    default: return "UNK";
2328  }
2329}
2330#endif
2331
2332Void TEncGOP::xCalculateAddPSNR( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit& accessUnit, Double dEncTime )
2333{
2334  Int     x, y;
2335  UInt64 uiSSDY  = 0;
2336  UInt64 uiSSDU  = 0;
2337  UInt64 uiSSDV  = 0;
2338 
2339  Double  dYPSNR  = 0.0;
2340  Double  dUPSNR  = 0.0;
2341  Double  dVPSNR  = 0.0;
2342 
2343  //===== calculate PSNR =====
2344  Pel*  pOrg    = pcPic ->getPicYuvOrg()->getLumaAddr();
2345  Pel*  pRec    = pcPicD->getLumaAddr();
2346  Int   iStride = pcPicD->getStride();
2347 
2348  Int   iWidth;
2349  Int   iHeight;
2350 
2351  iWidth  = pcPicD->getWidth () - m_pcEncTop->getPad(0);
2352  iHeight = pcPicD->getHeight() - m_pcEncTop->getPad(1);
2353 
2354  Int   iSize   = iWidth*iHeight;
2355 
2356  for( y = 0; y < iHeight; y++ )
2357  {
2358    for( x = 0; x < iWidth; x++ )
2359    {
2360      Int iDiff = (Int)( pOrg[x] - pRec[x] );
2361      uiSSDY   += iDiff * iDiff;
2362    }
2363    pOrg += iStride;
2364    pRec += iStride;
2365  }
2366 
2367#if H_3D_VSO
2368#if H_3D_VSO_SYNTH_DIST_OUT
2369  if ( m_pcRdCost->getUseRenModel() )
2370  {
2371    unsigned int maxval = 255 * (1<<(g_uiBitDepth + g_uiBitIncrement -8));
2372    Double fRefValueY = (double) maxval * maxval * iSize;
2373    Double fRefValueC = fRefValueY / 4.0;
2374    TRenModel*  pcRenModel = m_pcEncTop->getEncTop()->getRenModel();
2375    Int64 iDistVSOY, iDistVSOU, iDistVSOV;
2376    pcRenModel->getTotalSSE( iDistVSOY, iDistVSOU, iDistVSOV );
2377    dYPSNR = ( iDistVSOY ? 10.0 * log10( fRefValueY / (Double) iDistVSOY ) : 99.99 );
2378    dUPSNR = ( iDistVSOU ? 10.0 * log10( fRefValueC / (Double) iDistVSOU ) : 99.99 );
2379    dVPSNR = ( iDistVSOV ? 10.0 * log10( fRefValueC / (Double) iDistVSOV ) : 99.99 );
2380  }
2381  else
2382  {
2383#endif
2384#endif
2385    iHeight >>= 1;
2386  iWidth  >>= 1;
2387  iStride >>= 1;
2388  pOrg  = pcPic ->getPicYuvOrg()->getCbAddr();
2389  pRec  = pcPicD->getCbAddr();
2390 
2391  for( y = 0; y < iHeight; y++ )
2392  {
2393    for( x = 0; x < iWidth; x++ )
2394    {
2395      Int iDiff = (Int)( pOrg[x] - pRec[x] );
2396      uiSSDU   += iDiff * iDiff;
2397    }
2398    pOrg += iStride;
2399    pRec += iStride;
2400  }
2401 
2402  pOrg  = pcPic ->getPicYuvOrg()->getCrAddr();
2403  pRec  = pcPicD->getCrAddr();
2404 
2405  for( y = 0; y < iHeight; y++ )
2406  {
2407    for( x = 0; x < iWidth; x++ )
2408    {
2409      Int iDiff = (Int)( pOrg[x] - pRec[x] );
2410      uiSSDV   += iDiff * iDiff;
2411    }
2412    pOrg += iStride;
2413    pRec += iStride;
2414  }
2415 
2416  Int maxvalY = 255 << (g_bitDepthY-8);
2417  Int maxvalC = 255 << (g_bitDepthC-8);
2418  Double fRefValueY = (Double) maxvalY * maxvalY * iSize;
2419  Double fRefValueC = (Double) maxvalC * maxvalC * iSize / 4.0;
2420  dYPSNR            = ( uiSSDY ? 10.0 * log10( fRefValueY / (Double)uiSSDY ) : 99.99 );
2421  dUPSNR            = ( uiSSDU ? 10.0 * log10( fRefValueC / (Double)uiSSDU ) : 99.99 );
2422  dVPSNR            = ( uiSSDV ? 10.0 * log10( fRefValueC / (Double)uiSSDV ) : 99.99 );
2423#if H_3D_VSO
2424#if H_3D_VSO_SYNTH_DIST_OUT
2425}
2426#endif
2427#endif
2428  /* calculate the size of the access unit, excluding:
2429   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
2430   *  - SEI NAL units
2431   */
2432  UInt numRBSPBytes = 0;
2433  for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
2434  {
2435    UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
2436#if VERBOSE_RATE
2437    printf("*** %6s numBytesInNALunit: %u\n", nalUnitTypeToString((*it)->m_nalUnitType), numRBSPBytes_nal);
2438#endif
2439    if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
2440    {
2441      numRBSPBytes += numRBSPBytes_nal;
2442    }
2443  }
2444
2445  UInt uibits = numRBSPBytes * 8;
2446  m_vRVM_RP.push_back( uibits );
2447
2448  //===== add PSNR =====
2449#if H_MV
2450  m_pcEncTop->getAnalyzeAll()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2451#else
2452  m_gcAnalyzeAll.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2453#endif
2454  TComSlice*  pcSlice = pcPic->getSlice(0);
2455  if (pcSlice->isIntra())
2456  {
2457#if H_MV
2458    m_pcEncTop->getAnalyzeI()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2459#else
2460    m_gcAnalyzeI.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2461#endif
2462  }
2463  if (pcSlice->isInterP())
2464  {
2465#if H_MV
2466    m_pcEncTop->getAnalyzeP()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2467#else
2468    m_gcAnalyzeP.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2469#endif
2470  }
2471  if (pcSlice->isInterB())
2472  {
2473#if H_MV
2474    m_pcEncTop->getAnalyzeB()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2475#else
2476    m_gcAnalyzeB.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2477#endif
2478  }
2479
2480  Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
2481  if (!pcSlice->isReferenced()) c += 32;
2482
2483#if ADAPTIVE_QP_SELECTION
2484#if H_MV
2485  printf("Layer %3d   POC %4d TId: %1d ( %c-SLICE, nQP %d QP %d ) %10d  bits",
2486    pcSlice->getLayerId(),
2487    pcSlice->getPOC(),
2488    pcSlice->getTLayer(),
2489    c,
2490    pcSlice->getSliceQpBase(),
2491    pcSlice->getSliceQp(),
2492    uibits );
2493#else
2494  printf("POC %4d TId: %1d ( %c-SLICE, nQP %d QP %d ) %10d bits",
2495         pcSlice->getPOC(),
2496         pcSlice->getTLayer(),
2497         c,
2498         pcSlice->getSliceQpBase(),
2499         pcSlice->getSliceQp(),
2500         uibits );
2501#endif
2502#else
2503#if H_MV
2504  printf("Layer %3d   POC %4d TId: %1d ( %c-SLICE, QP %d ) %10d bits",
2505    pcSlice->getLayerId(),
2506    pcSlice->getPOC()-pcSlice->getLastIDR(),
2507    pcSlice->getTLayer(),
2508    c,
2509    pcSlice->getSliceQp(),
2510    uibits );
2511#else
2512  printf("POC %4d TId: %1d ( %c-SLICE, QP %d ) %10d bits",
2513         pcSlice->getPOC()-pcSlice->getLastIDR(),
2514         pcSlice->getTLayer(),
2515         c,
2516         pcSlice->getSliceQp(),
2517         uibits );
2518#endif
2519#endif
2520
2521  printf(" [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", dYPSNR, dUPSNR, dVPSNR );
2522  printf(" [ET %5.0f ]", dEncTime );
2523 
2524  for (Int iRefList = 0; iRefList < 2; iRefList++)
2525  {
2526    printf(" [L%d ", iRefList);
2527    for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(RefPicList(iRefList)); iRefIndex++)
2528    {
2529#if H_MV
2530      if( pcSlice->getLayerId() != pcSlice->getRefLayerId( RefPicList(iRefList), iRefIndex ) )
2531      {
2532        printf( "V%d ", pcSlice->getRefLayerId( RefPicList(iRefList), iRefIndex ) );
2533      }
2534      else
2535      {
2536#endif
2537      printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)-pcSlice->getLastIDR());
2538#if H_MV
2539      }
2540#endif
2541    }
2542    printf("]");
2543  }
2544}
2545
2546/** Function for deciding the nal_unit_type.
2547 * \param pocCurr POC of the current picture
2548 * \returns the nal unit type of the picture
2549 * This function checks the configuration and returns the appropriate nal_unit_type for the picture.
2550 */
2551NalUnitType TEncGOP::getNalUnitType(Int pocCurr, Int lastIDR)
2552{
2553  if (pocCurr == 0)
2554  {
2555    return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
2556  }
2557  if (pocCurr % m_pcCfg->getIntraPeriod() == 0)
2558  {
2559    if (m_pcCfg->getDecodingRefreshType() == 1)
2560    {
2561      return NAL_UNIT_CODED_SLICE_CRA;
2562    }
2563    else if (m_pcCfg->getDecodingRefreshType() == 2)
2564    {
2565      return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
2566    }
2567  }
2568  if(m_pocCRA>0)
2569  {
2570    if(pocCurr<m_pocCRA)
2571    {
2572      // All leading pictures are being marked as TFD pictures here since current encoder uses all
2573      // reference pictures while encoding leading pictures. An encoder can ensure that a leading
2574      // picture can be still decodable when random accessing to a CRA/CRANT/BLA/BLANT picture by
2575      // controlling the reference pictures used for encoding that leading picture. Such a leading
2576      // picture need not be marked as a TFD picture.
2577      return NAL_UNIT_CODED_SLICE_RASL_R;
2578    }
2579  }
2580  if (lastIDR>0)
2581  {
2582    if (pocCurr < lastIDR)
2583    {
2584      return NAL_UNIT_CODED_SLICE_RADL_R;
2585    }
2586  }
2587  return NAL_UNIT_CODED_SLICE_TRAIL_R;
2588}
2589
2590Double TEncGOP::xCalculateRVM()
2591{
2592  Double dRVM = 0;
2593 
2594  if( m_pcCfg->getGOPSize() == 1 && m_pcCfg->getIntraPeriod() != 1 && m_pcCfg->getFramesToBeEncoded() > RVM_VCEGAM10_M * 2 )
2595  {
2596    // calculate RVM only for lowdelay configurations
2597    std::vector<Double> vRL , vB;
2598    size_t N = m_vRVM_RP.size();
2599    vRL.resize( N );
2600    vB.resize( N );
2601   
2602    Int i;
2603    Double dRavg = 0 , dBavg = 0;
2604    vB[RVM_VCEGAM10_M] = 0;
2605    for( i = RVM_VCEGAM10_M + 1 ; i < N - RVM_VCEGAM10_M + 1 ; i++ )
2606    {
2607      vRL[i] = 0;
2608      for( Int j = i - RVM_VCEGAM10_M ; j <= i + RVM_VCEGAM10_M - 1 ; j++ )
2609        vRL[i] += m_vRVM_RP[j];
2610      vRL[i] /= ( 2 * RVM_VCEGAM10_M );
2611      vB[i] = vB[i-1] + m_vRVM_RP[i] - vRL[i];
2612      dRavg += m_vRVM_RP[i];
2613      dBavg += vB[i];
2614    }
2615   
2616    dRavg /= ( N - 2 * RVM_VCEGAM10_M );
2617    dBavg /= ( N - 2 * RVM_VCEGAM10_M );
2618   
2619    Double dSigamB = 0;
2620    for( i = RVM_VCEGAM10_M + 1 ; i < N - RVM_VCEGAM10_M + 1 ; i++ )
2621    {
2622      Double tmp = vB[i] - dBavg;
2623      dSigamB += tmp * tmp;
2624    }
2625    dSigamB = sqrt( dSigamB / ( N - 2 * RVM_VCEGAM10_M ) );
2626   
2627    Double f = sqrt( 12.0 * ( RVM_VCEGAM10_M - 1 ) / ( RVM_VCEGAM10_M + 1 ) );
2628   
2629    dRVM = dSigamB / dRavg * f;
2630  }
2631 
2632  return( dRVM );
2633}
2634
2635/** Attaches the input bitstream to the stream in the output NAL unit
2636    Updates rNalu to contain concatenated bitstream. rpcBitstreamRedirect is cleared at the end of this function call.
2637 *  \param codedSliceData contains the coded slice data (bitstream) to be concatenated to rNalu
2638 *  \param rNalu          target NAL unit
2639 */
2640Void TEncGOP::xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream*& codedSliceData)
2641{
2642  // Byte-align
2643  rNalu.m_Bitstream.writeByteAlignment();   // Slice header byte-alignment
2644
2645  // Perform bitstream concatenation
2646  if (codedSliceData->getNumberOfWrittenBits() > 0)
2647    {
2648    rNalu.m_Bitstream.addSubstream(codedSliceData);
2649  }
2650
2651  m_pcEntropyCoder->setBitstream(&rNalu.m_Bitstream);
2652
2653  codedSliceData->clear();
2654}
2655
2656// Function will arrange the long-term pictures in the decreasing order of poc_lsb_lt,
2657// and among the pictures with the same lsb, it arranges them in increasing delta_poc_msb_cycle_lt value
2658Void TEncGOP::arrangeLongtermPicturesInRPS(TComSlice *pcSlice, TComList<TComPic*>& rcListPic)
2659{
2660  TComReferencePictureSet *rps = pcSlice->getRPS();
2661  if(!rps->getNumberOfLongtermPictures())
2662  {
2663    return;
2664  }
2665
2666  // Arrange long-term reference pictures in the correct order of LSB and MSB,
2667  // and assign values for pocLSBLT and MSB present flag
2668  Int longtermPicsPoc[MAX_NUM_REF_PICS], longtermPicsLSB[MAX_NUM_REF_PICS], indices[MAX_NUM_REF_PICS];
2669  Int longtermPicsMSB[MAX_NUM_REF_PICS];
2670  Bool mSBPresentFlag[MAX_NUM_REF_PICS];
2671  ::memset(longtermPicsPoc, 0, sizeof(longtermPicsPoc));    // Store POC values of LTRP
2672  ::memset(longtermPicsLSB, 0, sizeof(longtermPicsLSB));    // Store POC LSB values of LTRP
2673  ::memset(longtermPicsMSB, 0, sizeof(longtermPicsMSB));    // Store POC LSB values of LTRP
2674  ::memset(indices        , 0, sizeof(indices));            // Indices to aid in tracking sorted LTRPs
2675  ::memset(mSBPresentFlag , 0, sizeof(mSBPresentFlag));     // Indicate if MSB needs to be present
2676
2677  // Get the long-term reference pictures
2678  Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
2679  Int i, ctr = 0;
2680  Int maxPicOrderCntLSB = 1 << pcSlice->getSPS()->getBitsForPOC();
2681  for(i = rps->getNumberOfPictures() - 1; i >= offset; i--, ctr++)
2682  {
2683    longtermPicsPoc[ctr] = rps->getPOC(i);                                  // LTRP POC
2684    longtermPicsLSB[ctr] = getLSB(longtermPicsPoc[ctr], maxPicOrderCntLSB); // LTRP POC LSB
2685    indices[ctr]      = i; 
2686    longtermPicsMSB[ctr] = longtermPicsPoc[ctr] - longtermPicsLSB[ctr];
2687  }
2688  Int numLongPics = rps->getNumberOfLongtermPictures();
2689  assert(ctr == numLongPics);
2690
2691  // Arrange pictures in decreasing order of MSB;
2692  for(i = 0; i < numLongPics; i++)
2693  {
2694    for(Int j = 0; j < numLongPics - 1; j++)
2695    {
2696      if(longtermPicsMSB[j] < longtermPicsMSB[j+1])
2697      {
2698        std::swap(longtermPicsPoc[j], longtermPicsPoc[j+1]);
2699        std::swap(longtermPicsLSB[j], longtermPicsLSB[j+1]);
2700        std::swap(longtermPicsMSB[j], longtermPicsMSB[j+1]);
2701        std::swap(indices[j]        , indices[j+1]        );
2702      }
2703    }
2704  }
2705
2706  for(i = 0; i < numLongPics; i++)
2707  {
2708    // Check if MSB present flag should be enabled.
2709    // Check if the buffer contains any pictures that have the same LSB.
2710    TComList<TComPic*>::iterator  iterPic = rcListPic.begin(); 
2711    TComPic*                      pcPic;
2712    while ( iterPic != rcListPic.end() )
2713    {
2714      pcPic = *iterPic;
2715      if( (getLSB(pcPic->getPOC(), maxPicOrderCntLSB) == longtermPicsLSB[i])   &&     // Same LSB
2716                                      (pcPic->getSlice(0)->isReferenced())     &&    // Reference picture
2717                                        (pcPic->getPOC() != longtermPicsPoc[i])    )  // Not the LTRP itself
2718      {
2719        mSBPresentFlag[i] = true;
2720        break;
2721      }
2722      iterPic++;     
2723    }
2724  }
2725
2726  // tempArray for usedByCurr flag
2727  Bool tempArray[MAX_NUM_REF_PICS]; ::memset(tempArray, 0, sizeof(tempArray));
2728  for(i = 0; i < numLongPics; i++)
2729  {
2730    tempArray[i] = rps->getUsed(indices[i]);
2731  }
2732  // Now write the final values;
2733  ctr = 0;
2734  Int currMSB = 0, currLSB = 0;
2735  // currPicPoc = currMSB + currLSB
2736  currLSB = getLSB(pcSlice->getPOC(), maxPicOrderCntLSB); 
2737  currMSB = pcSlice->getPOC() - currLSB;
2738
2739  for(i = rps->getNumberOfPictures() - 1; i >= offset; i--, ctr++)
2740  {
2741    rps->setPOC                   (i, longtermPicsPoc[ctr]);
2742    rps->setDeltaPOC              (i, - pcSlice->getPOC() + longtermPicsPoc[ctr]);
2743    rps->setUsed                  (i, tempArray[ctr]);
2744    rps->setPocLSBLT              (i, longtermPicsLSB[ctr]);
2745    rps->setDeltaPocMSBCycleLT    (i, (currMSB - (longtermPicsPoc[ctr] - longtermPicsLSB[ctr])) / maxPicOrderCntLSB);
2746    rps->setDeltaPocMSBPresentFlag(i, mSBPresentFlag[ctr]);     
2747
2748    assert(rps->getDeltaPocMSBCycleLT(i) >= 0);   // Non-negative value
2749  }
2750  for(i = rps->getNumberOfPictures() - 1, ctr = 1; i >= offset; i--, ctr++)
2751  {
2752    for(Int j = rps->getNumberOfPictures() - 1 - ctr; j >= offset; j--)
2753    {
2754      // Here at the encoder we know that we have set the full POC value for the LTRPs, hence we
2755      // don't have to check the MSB present flag values for this constraint.
2756      assert( rps->getPOC(i) != rps->getPOC(j) ); // If assert fails, LTRP entry repeated in RPS!!!
2757    }
2758  }
2759}
2760
2761/** Function for finding the position to insert the first of APS and non-nested BP, PT, DU info SEI messages.
2762 * \param accessUnit Access Unit of the current picture
2763 * This function finds the position to insert the first of APS and non-nested BP, PT, DU info SEI messages.
2764 */
2765Int TEncGOP::xGetFirstSeiLocation(AccessUnit &accessUnit)
2766{
2767  // Find the location of the first SEI message
2768  AccessUnit::iterator it;
2769  Int seiStartPos = 0;
2770  for(it = accessUnit.begin(); it != accessUnit.end(); it++, seiStartPos++)
2771  {
2772     if ((*it)->isSei() || (*it)->isVcl())
2773     {
2774       break;
2775     }               
2776  }
2777//  assert(it != accessUnit.end());  // Triggers with some legit configurations
2778  return seiStartPos;
2779}
2780
2781Void TEncGOP::dblMetric( TComPic* pcPic, UInt uiNumSlices )
2782{
2783  TComPicYuv* pcPicYuvRec = pcPic->getPicYuvRec();
2784  Pel* Rec    = pcPicYuvRec->getLumaAddr( 0 );
2785  Pel* tempRec = Rec;
2786  Int  stride = pcPicYuvRec->getStride();
2787  UInt log2maxTB = pcPic->getSlice(0)->getSPS()->getQuadtreeTULog2MaxSize();
2788  UInt maxTBsize = (1<<log2maxTB);
2789  const UInt minBlockArtSize = 8;
2790  const UInt picWidth = pcPicYuvRec->getWidth();
2791  const UInt picHeight = pcPicYuvRec->getHeight();
2792  const UInt noCol = (picWidth>>log2maxTB);
2793  const UInt noRows = (picHeight>>log2maxTB);
2794  assert(noCol > 1);
2795  assert(noRows > 1);
2796  UInt64 *colSAD = (UInt64*)malloc(noCol*sizeof(UInt64));
2797  UInt64 *rowSAD = (UInt64*)malloc(noRows*sizeof(UInt64));
2798  UInt colIdx = 0;
2799  UInt rowIdx = 0;
2800  Pel p0, p1, p2, q0, q1, q2;
2801 
2802  Int qp = pcPic->getSlice(0)->getSliceQp();
2803  Int bitdepthScale = 1 << (g_bitDepthY-8);
2804  Int beta = TComLoopFilter::getBeta( qp ) * bitdepthScale;
2805  const Int thr2 = (beta>>2);
2806  const Int thr1 = 2*bitdepthScale;
2807  UInt a = 0;
2808 
2809  memset(colSAD, 0, noCol*sizeof(UInt64));
2810  memset(rowSAD, 0, noRows*sizeof(UInt64));
2811 
2812  if (maxTBsize > minBlockArtSize)
2813  {
2814    // Analyze vertical artifact edges
2815    for(Int c = maxTBsize; c < picWidth; c += maxTBsize)
2816    {
2817      for(Int r = 0; r < picHeight; r++)
2818      {
2819        p2 = Rec[c-3];
2820        p1 = Rec[c-2];
2821        p0 = Rec[c-1];
2822        q0 = Rec[c];
2823        q1 = Rec[c+1];
2824        q2 = Rec[c+2];
2825        a = ((abs(p2-(p1<<1)+p0)+abs(q0-(q1<<1)+q2))<<1);
2826        if ( thr1 < a && a < thr2)
2827        {
2828          colSAD[colIdx] += abs(p0 - q0);
2829        }
2830        Rec += stride;
2831      }
2832      colIdx++;
2833      Rec = tempRec;
2834    }
2835   
2836    // Analyze horizontal artifact edges
2837    for(Int r = maxTBsize; r < picHeight; r += maxTBsize)
2838    {
2839      for(Int c = 0; c < picWidth; c++)
2840      {
2841        p2 = Rec[c + (r-3)*stride];
2842        p1 = Rec[c + (r-2)*stride];
2843        p0 = Rec[c + (r-1)*stride];
2844        q0 = Rec[c + r*stride];
2845        q1 = Rec[c + (r+1)*stride];
2846        q2 = Rec[c + (r+2)*stride];
2847        a = ((abs(p2-(p1<<1)+p0)+abs(q0-(q1<<1)+q2))<<1);
2848        if (thr1 < a && a < thr2)
2849        {
2850          rowSAD[rowIdx] += abs(p0 - q0);
2851        }
2852      }
2853      rowIdx++;
2854    }
2855  }
2856 
2857  UInt64 colSADsum = 0;
2858  UInt64 rowSADsum = 0;
2859  for(Int c = 0; c < noCol-1; c++)
2860  {
2861    colSADsum += colSAD[c];
2862  }
2863  for(Int r = 0; r < noRows-1; r++)
2864  {
2865    rowSADsum += rowSAD[r];
2866  }
2867 
2868  colSADsum <<= 10;
2869  rowSADsum <<= 10;
2870  colSADsum /= (noCol-1);
2871  colSADsum /= picHeight;
2872  rowSADsum /= (noRows-1);
2873  rowSADsum /= picWidth;
2874 
2875  UInt64 avgSAD = ((colSADsum + rowSADsum)>>1);
2876  avgSAD >>= (g_bitDepthY-8);
2877 
2878  if ( avgSAD > 2048 )
2879  {
2880    avgSAD >>= 9;
2881    Int offset = Clip3(2,6,(Int)avgSAD);
2882    for (Int i=0; i<uiNumSlices; i++)
2883    {
2884      pcPic->getSlice(i)->setDeblockingFilterOverrideFlag(true);
2885      pcPic->getSlice(i)->setDeblockingFilterDisable(false);
2886      pcPic->getSlice(i)->setDeblockingFilterBetaOffsetDiv2( offset );
2887      pcPic->getSlice(i)->setDeblockingFilterTcOffsetDiv2( offset );
2888    }
2889  }
2890  else
2891  {
2892    for (Int i=0; i<uiNumSlices; i++)
2893    {
2894      pcPic->getSlice(i)->setDeblockingFilterOverrideFlag(false);
2895      pcPic->getSlice(i)->setDeblockingFilterDisable(        pcPic->getSlice(i)->getPPS()->getPicDisableDeblockingFilterFlag() );
2896      pcPic->getSlice(i)->setDeblockingFilterBetaOffsetDiv2( pcPic->getSlice(i)->getPPS()->getDeblockingFilterBetaOffsetDiv2() );
2897      pcPic->getSlice(i)->setDeblockingFilterTcOffsetDiv2(   pcPic->getSlice(i)->getPPS()->getDeblockingFilterTcOffsetDiv2()   );
2898    }
2899  }
2900 
2901  free(colSAD);
2902  free(rowSAD);
2903}
2904
2905#if H_MV
2906Void TEncGOP::xSetRefPicListModificationsMv( TComSlice* pcSlice, UInt iGOPid )
2907{ 
2908  Int layer    = pcSlice->getLayerIdInVps( ); 
2909 
2910  if( pcSlice->getSliceType() == I_SLICE || !(pcSlice->getPPS()->getListsModificationPresentFlag()) || pcSlice->getNumActiveRefLayerPics() == 0 )
2911  {
2912    return;
2913  }
2914
2915  // analyze inter-view modifications
2916  GOPEntry ge = m_pcCfg->getGOPEntry( (pcSlice->getRapPicFlag() && ( layer > 0) ) ? MAX_GOP : iGOPid );
2917  assert( ge.m_numActiveRefLayerPics == pcSlice->getNumActiveRefLayerPics() ); 
2918 
2919  Int maxRefListSize  = pcSlice->getNumRpsCurrTempList();
2920  Int numTemporalRefs = maxRefListSize - pcSlice->getNumActiveRefLayerPics();
2921
2922  for (Int li = 0; li < 2; li ++) // Loop over lists L0 and L1
2923  {
2924    // set inter-view modifications   
2925    Int tempList[16];
2926    for( Int k = 0; k < 16; k++ )
2927    {
2928      tempList[ k ] = -1;
2929    }
2930
2931    Bool isModified = false;
2932    if ( maxRefListSize > 1 )
2933    {
2934      for( Int k = 0, orgIdx = numTemporalRefs; k < ge.m_numActiveRefLayerPics; k++, orgIdx++ )
2935      {
2936          Int targetIdx = ge.m_interViewRefPosL[ li ][ k ];
2937
2938        isModified = ( targetIdx != orgIdx ) && ( targetIdx >= 0  );
2939        if ( isModified )
2940            {
2941          assert( tempList[ targetIdx ] == -1 ); // Assert when two inter layer reference pictures are sorted to the same position
2942              tempList[ targetIdx ] = orgIdx;             
2943        }
2944      }
2945    }
2946
2947    TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
2948    refPicListModification->setRefPicListModificationFlagL( li, isModified ); 
2949
2950      if( isModified )
2951      {
2952        Int temporalRefIdx = 0;
2953        for( Int i = 0; i < pcSlice->getNumRefIdx( ( li == 0 ) ? REF_PIC_LIST_0 : REF_PIC_LIST_1 ); i++ )
2954        {
2955          if( tempList[i] >= 0 ) 
2956          {
2957            refPicListModification->setRefPicSetIdxL( li, i, tempList[i] );
2958          }
2959          else
2960          {
2961            refPicListModification->setRefPicSetIdxL( li, i, temporalRefIdx );
2962            temporalRefIdx++;
2963          }
2964        }
2965      }
2966  }
2967}
2968#endif
2969//! \}
Note: See TracBrowser for help on using the repository browser.