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

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

-VSP compensation part migration, not fully tested, intermediate version

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