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

Last change on this file since 499 was 499, checked in by zhang, 11 years ago

Changes include: DV-MVP(H_3D_IDV), TMVP merging candidate(H_3D_TMVP, target reference index changes, scaling based on view order index) and cleanups (H_3D_CLEANUPS)

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