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

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