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

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