source: 3DVCSoftware/branches/HTM-DEV-0.3-dev2/source/Lib/TLibEncoder/TEncGOP.cpp @ 537

Last change on this file since 537 was 537, checked in by tech, 11 years ago

Update to HM 11.0.

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