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

Last change on this file since 504 was 504, checked in by zhang, 11 years ago

Merge Dev2.a to Dev2 and simulation results updated

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