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

Last change on this file since 531 was 531, checked in by tech, 12 years ago

Merged HTM-DEV-0.3-dev1 Rev. 520.

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