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

Last change on this file since 486 was 486, checked in by tech, 11 years ago

Integrated DoNBDV provided by Mediatek and applied clean ups.

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