source: SHVCSoftware/branches/SHM-4.1-dev/source/Lib/TLibEncoder/TEncGOP.cpp @ 532

Last change on this file since 532 was 532, checked in by seregin, 12 years ago

update to HM-12.1 base

  • Property svn:eol-style set to native
File size: 143.6 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  xResetNonNestedSEIPresentFlags();
97  xResetNestedSEIPresentFlags();
98#if SVC_UPSAMPLING
99  m_pcPredSearch        = NULL;
100#endif
101  return;
102}
103
104TEncGOP::~TEncGOP()
105{
106}
107
108/** Create list to contain pointers to LCU start addresses of slice.
109 */
110#if SVC_EXTENSION
111Void  TEncGOP::create( UInt layerId )
112{
113  m_bLongtermTestPictureHasBeenCoded = 0;
114  m_bLongtermTestPictureHasBeenCoded2 = 0;
115  m_layerId = layerId;
116}
117#else
118Void  TEncGOP::create()
119{
120  m_bLongtermTestPictureHasBeenCoded = 0;
121  m_bLongtermTestPictureHasBeenCoded2 = 0;
122}
123#endif
124
125Void  TEncGOP::destroy()
126{
127}
128
129Void TEncGOP::init ( TEncTop* pcTEncTop )
130{
131  m_pcEncTop     = pcTEncTop;
132  m_pcCfg                = pcTEncTop;
133  m_pcSliceEncoder       = pcTEncTop->getSliceEncoder();
134  m_pcListPic            = pcTEncTop->getListPic(); 
135 
136  m_pcEntropyCoder       = pcTEncTop->getEntropyCoder();
137  m_pcCavlcCoder         = pcTEncTop->getCavlcCoder();
138  m_pcSbacCoder          = pcTEncTop->getSbacCoder();
139  m_pcBinCABAC           = pcTEncTop->getBinCABAC();
140  m_pcLoopFilter         = pcTEncTop->getLoopFilter();
141  m_pcBitCounter         = pcTEncTop->getBitCounter();
142 
143  //--Adaptive Loop filter
144  m_pcSAO                = pcTEncTop->getSAO();
145  m_pcRateCtrl           = pcTEncTop->getRateCtrl();
146  m_lastBPSEI          = 0;
147  m_totalCoded         = 0;
148
149#if SVC_EXTENSION
150  m_ppcTEncTop           = pcTEncTop->getLayerEnc();
151#endif
152#if SVC_UPSAMPLING
153  m_pcPredSearch         = pcTEncTop->getPredSearch();                       ///< encoder search class
154#endif
155}
156
157SEIActiveParameterSets* TEncGOP::xCreateSEIActiveParameterSets (TComSPS *sps)
158{
159  SEIActiveParameterSets *seiActiveParameterSets = new SEIActiveParameterSets(); 
160  seiActiveParameterSets->activeVPSId = m_pcCfg->getVPS()->getVPSId(); 
161  seiActiveParameterSets->m_fullRandomAccessFlag = false;
162  seiActiveParameterSets->m_noParamSetUpdateFlag = false;
163  seiActiveParameterSets->numSpsIdsMinus1 = 0;
164  seiActiveParameterSets->activeSeqParamSetId.resize(seiActiveParameterSets->numSpsIdsMinus1 + 1); 
165  seiActiveParameterSets->activeSeqParamSetId[0] = sps->getSPSId();
166  return seiActiveParameterSets;
167}
168
169#if M0043_LAYERS_PRESENT_SEI
170SEILayersPresent* TEncGOP::xCreateSEILayersPresent ()
171{
172  UInt i = 0;
173  SEILayersPresent *seiLayersPresent = new SEILayersPresent(); 
174  seiLayersPresent->m_activeVpsId = m_pcCfg->getVPS()->getVPSId(); 
175  seiLayersPresent->m_vpsMaxLayers = m_pcCfg->getVPS()->getMaxLayers();
176  for ( ; i < seiLayersPresent->m_vpsMaxLayers; i++)
177  {
178    seiLayersPresent->m_layerPresentFlag[i] = true; 
179  }
180  for ( ; i < MAX_LAYERS; i++)
181  {
182    seiLayersPresent->m_layerPresentFlag[i] = false; 
183  }
184  return seiLayersPresent;
185}
186#endif
187
188SEIFramePacking* TEncGOP::xCreateSEIFramePacking()
189{
190  SEIFramePacking *seiFramePacking = new SEIFramePacking();
191  seiFramePacking->m_arrangementId = m_pcCfg->getFramePackingArrangementSEIId();
192  seiFramePacking->m_arrangementCancelFlag = 0;
193  seiFramePacking->m_arrangementType = m_pcCfg->getFramePackingArrangementSEIType();
194  assert((seiFramePacking->m_arrangementType > 2) && (seiFramePacking->m_arrangementType < 6) );
195  seiFramePacking->m_quincunxSamplingFlag = m_pcCfg->getFramePackingArrangementSEIQuincunx();
196  seiFramePacking->m_contentInterpretationType = m_pcCfg->getFramePackingArrangementSEIInterpretation();
197  seiFramePacking->m_spatialFlippingFlag = 0;
198  seiFramePacking->m_frame0FlippedFlag = 0;
199  seiFramePacking->m_fieldViewsFlag = (seiFramePacking->m_arrangementType == 2);
200  seiFramePacking->m_currentFrameIsFrame0Flag = ((seiFramePacking->m_arrangementType == 5) && m_iNumPicCoded&1);
201  seiFramePacking->m_frame0SelfContainedFlag = 0;
202  seiFramePacking->m_frame1SelfContainedFlag = 0;
203  seiFramePacking->m_frame0GridPositionX = 0;
204  seiFramePacking->m_frame0GridPositionY = 0;
205  seiFramePacking->m_frame1GridPositionX = 0;
206  seiFramePacking->m_frame1GridPositionY = 0;
207  seiFramePacking->m_arrangementReservedByte = 0;
208  seiFramePacking->m_arrangementPersistenceFlag = true;
209  seiFramePacking->m_upsampledAspectRatio = 0;
210  return seiFramePacking;
211}
212
213SEIDisplayOrientation* TEncGOP::xCreateSEIDisplayOrientation()
214{
215  SEIDisplayOrientation *seiDisplayOrientation = new SEIDisplayOrientation();
216  seiDisplayOrientation->cancelFlag = false;
217  seiDisplayOrientation->horFlip = false;
218  seiDisplayOrientation->verFlip = false;
219  seiDisplayOrientation->anticlockwiseRotation = m_pcCfg->getDisplayOrientationSEIAngle();
220  return seiDisplayOrientation;
221}
222
223SEIToneMappingInfo*  TEncGOP::xCreateSEIToneMappingInfo()
224{
225  SEIToneMappingInfo *seiToneMappingInfo = new SEIToneMappingInfo();
226  seiToneMappingInfo->m_toneMapId = m_pcCfg->getTMISEIToneMapId();
227  seiToneMappingInfo->m_toneMapCancelFlag = m_pcCfg->getTMISEIToneMapCancelFlag();
228  seiToneMappingInfo->m_toneMapPersistenceFlag = m_pcCfg->getTMISEIToneMapPersistenceFlag();
229
230  seiToneMappingInfo->m_codedDataBitDepth = m_pcCfg->getTMISEICodedDataBitDepth();
231  assert(seiToneMappingInfo->m_codedDataBitDepth >= 8 && seiToneMappingInfo->m_codedDataBitDepth <= 14);
232  seiToneMappingInfo->m_targetBitDepth = m_pcCfg->getTMISEITargetBitDepth();
233  assert( seiToneMappingInfo->m_targetBitDepth >= 1 && seiToneMappingInfo->m_targetBitDepth <= 17 );
234  seiToneMappingInfo->m_modelId = m_pcCfg->getTMISEIModelID();
235  assert(seiToneMappingInfo->m_modelId >=0 &&seiToneMappingInfo->m_modelId<=4);
236
237  switch( seiToneMappingInfo->m_modelId)
238  {
239  case 0:
240    {
241      seiToneMappingInfo->m_minValue = m_pcCfg->getTMISEIMinValue();
242      seiToneMappingInfo->m_maxValue = m_pcCfg->getTMISEIMaxValue();
243      break;
244    }
245  case 1:
246    {
247      seiToneMappingInfo->m_sigmoidMidpoint = m_pcCfg->getTMISEISigmoidMidpoint();
248      seiToneMappingInfo->m_sigmoidWidth = m_pcCfg->getTMISEISigmoidWidth();
249      break;
250    }
251  case 2:
252    {
253      UInt num = 1u<<(seiToneMappingInfo->m_targetBitDepth);
254      seiToneMappingInfo->m_startOfCodedInterval.resize(num);
255      Int* ptmp = m_pcCfg->getTMISEIStartOfCodedInterva();
256      if(ptmp)
257      {
258        for(int i=0; i<num;i++)
259        {
260          seiToneMappingInfo->m_startOfCodedInterval[i] = ptmp[i];
261        }
262      }
263      break;
264    }
265  case 3:
266    {
267      seiToneMappingInfo->m_numPivots = m_pcCfg->getTMISEINumPivots();
268      seiToneMappingInfo->m_codedPivotValue.resize(seiToneMappingInfo->m_numPivots);
269      seiToneMappingInfo->m_targetPivotValue.resize(seiToneMappingInfo->m_numPivots);
270      Int* ptmpcoded = m_pcCfg->getTMISEICodedPivotValue();
271      Int* ptmptarget = m_pcCfg->getTMISEITargetPivotValue();
272      if(ptmpcoded&&ptmptarget)
273      {
274        for(int i=0; i<(seiToneMappingInfo->m_numPivots);i++)
275        {
276          seiToneMappingInfo->m_codedPivotValue[i]=ptmpcoded[i];
277          seiToneMappingInfo->m_targetPivotValue[i]=ptmptarget[i];
278         }
279       }
280       break;
281     }
282  case 4:
283     {
284       seiToneMappingInfo->m_cameraIsoSpeedIdc = m_pcCfg->getTMISEICameraIsoSpeedIdc();
285       seiToneMappingInfo->m_cameraIsoSpeedValue = m_pcCfg->getTMISEICameraIsoSpeedValue();
286       assert( seiToneMappingInfo->m_cameraIsoSpeedValue !=0 );
287       seiToneMappingInfo->m_exposureCompensationValueSignFlag = m_pcCfg->getTMISEIExposureCompensationValueSignFlag();
288       seiToneMappingInfo->m_exposureCompensationValueNumerator = m_pcCfg->getTMISEIExposureCompensationValueNumerator();
289       seiToneMappingInfo->m_exposureCompensationValueDenomIdc = m_pcCfg->getTMISEIExposureCompensationValueDenomIdc();
290       seiToneMappingInfo->m_refScreenLuminanceWhite = m_pcCfg->getTMISEIRefScreenLuminanceWhite();
291       seiToneMappingInfo->m_extendedRangeWhiteLevel = m_pcCfg->getTMISEIExtendedRangeWhiteLevel();
292       assert( seiToneMappingInfo->m_extendedRangeWhiteLevel >= 100 );
293       seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue = m_pcCfg->getTMISEINominalBlackLevelLumaCodeValue();
294       seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue = m_pcCfg->getTMISEINominalWhiteLevelLumaCodeValue();
295       assert( seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue > seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue );
296       seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue = m_pcCfg->getTMISEIExtendedWhiteLevelLumaCodeValue();
297       assert( seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue >= seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue );
298       break;
299    }
300  default:
301    {
302      assert(!"Undefined SEIToneMapModelId");
303      break;
304    }
305  }
306  return seiToneMappingInfo;
307}
308
309#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
310SEIInterLayerConstrainedTileSets* TEncGOP::xCreateSEIInterLayerConstrainedTileSets()
311{
312  SEIInterLayerConstrainedTileSets *seiInterLayerConstrainedTileSets = new SEIInterLayerConstrainedTileSets();
313  seiInterLayerConstrainedTileSets->m_ilAllTilesExactSampleValueMatchFlag = false;
314  seiInterLayerConstrainedTileSets->m_ilOneTilePerTileSetFlag = false;
315  if (!seiInterLayerConstrainedTileSets->m_ilOneTilePerTileSetFlag)
316  {
317    seiInterLayerConstrainedTileSets->m_ilNumSetsInMessageMinus1 = m_pcCfg->getIlNumSetsInMessage() - 1;
318    if (seiInterLayerConstrainedTileSets->m_ilNumSetsInMessageMinus1)
319    {
320      seiInterLayerConstrainedTileSets->m_skippedTileSetPresentFlag = m_pcCfg->getSkippedTileSetPresentFlag();
321    }
322    else
323    {
324      seiInterLayerConstrainedTileSets->m_skippedTileSetPresentFlag = false;
325    }
326    seiInterLayerConstrainedTileSets->m_ilNumSetsInMessageMinus1 += seiInterLayerConstrainedTileSets->m_skippedTileSetPresentFlag ? 1 : 0;
327    for (UInt i = 0; i < m_pcCfg->getIlNumSetsInMessage(); i++)
328    {
329      seiInterLayerConstrainedTileSets->m_ilctsId[i] = i;
330      seiInterLayerConstrainedTileSets->m_ilNumTileRectsInSetMinus1[i] = 0;
331      for( UInt j = 0; j <= seiInterLayerConstrainedTileSets->m_ilNumTileRectsInSetMinus1[i]; j++)
332      {
333        seiInterLayerConstrainedTileSets->m_ilTopLeftTileIndex[i][j]     = m_pcCfg->getTopLeftTileIndex(i);
334        seiInterLayerConstrainedTileSets->m_ilBottomRightTileIndex[i][j] = m_pcCfg->getBottomRightTileIndex(i);
335      }
336      seiInterLayerConstrainedTileSets->m_ilcIdc[i] = m_pcCfg->getIlcIdc(i);
337      if (seiInterLayerConstrainedTileSets->m_ilAllTilesExactSampleValueMatchFlag)
338      {
339        seiInterLayerConstrainedTileSets->m_ilExactSampleValueMatchFlag[i] = false;
340      }
341    }
342  }
343
344  return seiInterLayerConstrainedTileSets;
345}
346#endif
347
348Void TEncGOP::xCreateLeadingSEIMessages (/*SEIMessages seiMessages,*/ AccessUnit &accessUnit, TComSPS *sps)
349{
350  OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
351
352  if(m_pcCfg->getActiveParameterSetsSEIEnabled())
353  {
354    SEIActiveParameterSets *sei = xCreateSEIActiveParameterSets (sps);
355
356    //nalu = NALUnit(NAL_UNIT_SEI);
357    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
358    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
359    writeRBSPTrailingBits(nalu.m_Bitstream);
360    accessUnit.push_back(new NALUnitEBSP(nalu));
361    delete sei;
362    m_activeParameterSetSEIPresentInAU = true;
363  }
364
365#if M0043_LAYERS_PRESENT_SEI
366  if(m_pcCfg->getLayersPresentSEIEnabled())
367  {
368    SEILayersPresent *sei = xCreateSEILayersPresent ();
369    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
370    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
371    writeRBSPTrailingBits(nalu.m_Bitstream);
372    accessUnit.push_back(new NALUnitEBSP(nalu));
373    delete sei;
374  }
375#endif
376
377  if(m_pcCfg->getFramePackingArrangementSEIEnabled())
378  {
379    SEIFramePacking *sei = xCreateSEIFramePacking ();
380
381    nalu = NALUnit(NAL_UNIT_PREFIX_SEI);
382    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
383    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps);
384    writeRBSPTrailingBits(nalu.m_Bitstream);
385    accessUnit.push_back(new NALUnitEBSP(nalu));
386    delete sei;
387  }
388  if (m_pcCfg->getDisplayOrientationSEIAngle())
389  {
390    SEIDisplayOrientation *sei = xCreateSEIDisplayOrientation();
391
392    nalu = NALUnit(NAL_UNIT_PREFIX_SEI); 
393    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
394    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
395    writeRBSPTrailingBits(nalu.m_Bitstream);
396    accessUnit.push_back(new NALUnitEBSP(nalu));
397    delete sei;
398  }
399  if(m_pcCfg->getToneMappingInfoSEIEnabled())
400  {
401    SEIToneMappingInfo *sei = xCreateSEIToneMappingInfo ();
402     
403    nalu = NALUnit(NAL_UNIT_PREFIX_SEI); 
404    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
405    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
406    writeRBSPTrailingBits(nalu.m_Bitstream);
407    accessUnit.push_back(new NALUnitEBSP(nalu));
408    delete sei;
409  }
410#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
411  if(m_pcCfg->getInterLayerConstrainedTileSetsSEIEnabled())
412  {
413    SEIInterLayerConstrainedTileSets *sei = xCreateSEIInterLayerConstrainedTileSets ();
414
415    nalu = NALUnit(NAL_UNIT_PREFIX_SEI, 0, m_pcCfg->getNumLayer()-1); // For highest layer
416    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
417    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
418    writeRBSPTrailingBits(nalu.m_Bitstream);
419    accessUnit.push_back(new NALUnitEBSP(nalu));
420    delete sei;
421  }
422#endif
423}
424
425// ====================================================================================================================
426// Public member functions
427// ====================================================================================================================
428#if SVC_EXTENSION
429Void TEncGOP::compressGOP( Int iPicIdInGOP, Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff)
430#else
431Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff)
432#endif
433{
434  TComPic*        pcPic;
435  TComPicYuv*     pcPicYuvRecOut;
436  TComSlice*      pcSlice;
437  TComOutputBitstream  *pcBitstreamRedirect;
438  pcBitstreamRedirect = new TComOutputBitstream;
439  AccessUnit::iterator  itLocationToPushSliceHeaderNALU; // used to store location where NALU containing slice header is to be inserted
440  UInt                  uiOneBitstreamPerSliceLength = 0;
441  TEncSbac* pcSbacCoders = NULL;
442  TComOutputBitstream* pcSubstreamsOut = NULL;
443
444  xInitGOP( iPOCLast, iNumPicRcvd, rcListPic, rcListPicYuvRecOut, isField );
445
446  m_iNumPicCoded = 0;
447  SEIPictureTiming pictureTimingSEI;
448  Bool writeSOP = m_pcCfg->getSOPDescriptionSEIEnabled();
449  // Initialize Scalable Nesting SEI with single layer values
450  SEIScalableNesting scalableNestingSEI;
451  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
452  scalableNestingSEI.m_nestingOpFlag                 = 0;
453  scalableNestingSEI.m_nestingNumOpsMinus1           = 0;      //nesting_num_ops_minus1
454  scalableNestingSEI.m_allLayersFlag                 = 0;
455  scalableNestingSEI.m_nestingNoOpMaxTemporalIdPlus1 = 6 + 1;  //nesting_no_op_max_temporal_id_plus1
456  scalableNestingSEI.m_nestingNumLayersMinus1        = 1 - 1;  //nesting_num_layers_minus1
457  scalableNestingSEI.m_nestingLayerId[0]             = 0;
458  scalableNestingSEI.m_callerOwnsSEIs                = true;
459  Int picSptDpbOutputDuDelay = 0;
460  UInt *accumBitsDU = NULL;
461  UInt *accumNalsDU = NULL;
462  SEIDecodingUnitInfo decodingUnitInfoSEI;
463#if SVC_EXTENSION
464  for ( Int iGOPid=iPicIdInGOP; iGOPid < iPicIdInGOP+1; iGOPid++ )
465#else
466  for ( Int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
467#endif
468  {
469    UInt uiColDir = 1;
470    //-- For time output for each slice
471    long iBeforeTime = clock();
472
473    //select uiColDir
474    Int iCloseLeft=1, iCloseRight=-1;
475    for(Int i = 0; i<m_pcCfg->getGOPEntry(iGOPid).m_numRefPics; i++) 
476    {
477      Int iRef = m_pcCfg->getGOPEntry(iGOPid).m_referencePics[i];
478      if(iRef>0&&(iRef<iCloseRight||iCloseRight==-1))
479      {
480        iCloseRight=iRef;
481      }
482      else if(iRef<0&&(iRef>iCloseLeft||iCloseLeft==1))
483      {
484        iCloseLeft=iRef;
485      }
486    }
487    if(iCloseRight>-1)
488    {
489      iCloseRight=iCloseRight+m_pcCfg->getGOPEntry(iGOPid).m_POC-1;
490    }
491    if(iCloseLeft<1) 
492    {
493      iCloseLeft=iCloseLeft+m_pcCfg->getGOPEntry(iGOPid).m_POC-1;
494      while(iCloseLeft<0)
495      {
496        iCloseLeft+=m_iGopSize;
497      }
498    }
499    Int iLeftQP=0, iRightQP=0;
500    for(Int i=0; i<m_iGopSize; i++)
501    {
502      if(m_pcCfg->getGOPEntry(i).m_POC==(iCloseLeft%m_iGopSize)+1)
503      {
504        iLeftQP= m_pcCfg->getGOPEntry(i).m_QPOffset;
505      }
506      if (m_pcCfg->getGOPEntry(i).m_POC==(iCloseRight%m_iGopSize)+1)
507      {
508        iRightQP=m_pcCfg->getGOPEntry(i).m_QPOffset;
509      }
510    }
511    if(iCloseRight>-1&&iRightQP<iLeftQP)
512    {
513      uiColDir=0;
514    }
515
516    /////////////////////////////////////////////////////////////////////////////////////////////////// Initial to start encoding
517    Int iTimeOffset;
518    Int pocCurr;
519   
520    if(iPOCLast == 0) //case first frame or first top field
521    {
522      pocCurr=0;
523      iTimeOffset = 1;
524    }
525    else if(iPOCLast == 1 && isField) //case first bottom field, just like the first frame, the poc computation is not right anymore, we set the right value
526    {
527      pocCurr = 1;
528      iTimeOffset = 1;
529    }
530    else
531    {
532      pocCurr = iPOCLast - iNumPicRcvd + m_pcCfg->getGOPEntry(iGOPid).m_POC - isField;
533      iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
534    }
535
536    if(pocCurr>=m_pcCfg->getFramesToBeEncoded())
537    {
538      continue;
539    }
540
541#if M0040_ADAPTIVE_RESOLUTION_CHANGE
542    if (m_pcEncTop->getAdaptiveResolutionChange() > 0 && ((m_layerId == 1 && pocCurr < m_pcEncTop->getAdaptiveResolutionChange()) ||
543                                                          (m_layerId == 0 && pocCurr > m_pcEncTop->getAdaptiveResolutionChange())) )
544    {
545      continue;
546    }
547#endif
548
549    if( getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_N_LP )
550    {
551      m_iLastIDR = pocCurr;
552    }       
553    // start a new access unit: create an entry in the list of output access units
554    accessUnitsInGOP.push_back(AccessUnit());
555    AccessUnit& accessUnit = accessUnitsInGOP.back();
556    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr, isField );
557
558    //  Slice data initialization
559    pcPic->clearSliceBuffer();
560    assert(pcPic->getNumAllocatedSlice() == 1);
561    m_pcSliceEncoder->setSliceIdx(0);
562    pcPic->setCurrSliceIdx(0);
563#if SVC_EXTENSION
564    pcPic->setLayerId( m_layerId );
565    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), m_pcEncTop->getVPS(), isField );
566#else
567    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), isField );
568#endif
569
570    //Set Frame/Field coding
571    pcSlice->getPic()->setField(isField);
572
573#if POC_RESET_FLAG
574    if( !pcSlice->getPocResetFlag() ) // For picture that are not reset, we should adjust the value of POC calculated from the configuration files.
575    {
576      // Subtract POC adjustment value until now.
577      pcSlice->setPOC( pcSlice->getPOC() - m_pcEncTop->getPocAdjustmentValue() );
578    }
579    else
580    {
581      // Check if this is the first slice in the picture
582      // In the encoder, the POC values are copied along with copySliceInfo, so we only need
583      // to do this for the first slice.
584      Int pocAdjustValue = pcSlice->getPOC() - m_pcEncTop->getPocAdjustmentValue();
585      if( pcSlice->getSliceIdx() == 0 )
586      {
587        TComList<TComPic*>::iterator  iterPic = rcListPic.begin(); 
588
589        // Iterate through all picture in DPB
590        while( iterPic != rcListPic.end() )
591        {             
592          TComPic *dpbPic = *iterPic;
593          if( dpbPic->getPOC() == pocCurr )
594          {
595            if( dpbPic->getReconMark() )
596            {
597              assert( !( dpbPic->getSlice(0)->isReferenced() ) && !( dpbPic->getOutputMark() ) );
598            }
599          }
600          // Check if the picture pointed to by iterPic is either used for reference or
601          // needed for output, are in the same layer, and not the current picture.
602          if( /* ( ( dpbPic->getSlice(0)->isReferenced() ) || ( dpbPic->getOutputMark() ) )
603              && */ ( dpbPic->getLayerId() == pcSlice->getLayerId() )
604              && ( dpbPic->getReconMark() ) 
605            )
606          {
607            for(Int i = dpbPic->getNumAllocatedSlice()-1; i >= 0; i--)
608            {
609              TComSlice *slice = dpbPic->getSlice(i);
610              TComReferencePictureSet *rps = slice->getRPS();
611              slice->setPOC( dpbPic->getSlice(i)->getPOC() - pocAdjustValue );
612
613              // Also adjust the POC value stored in the RPS of each such slice
614              for(Int j = rps->getNumberOfPictures(); j >= 0; j--)
615              {
616                rps->setPOC( j, rps->getPOC(j) - pocAdjustValue );
617              }
618              // Also adjust the value of refPOC
619              for(Int k = 0; k < 2; k++)  // For List 0 and List 1
620              {
621                RefPicList list = (k == 1) ? REF_PIC_LIST_1 : REF_PIC_LIST_0;
622                for(Int j = 0; j < slice->getNumRefIdx(list); j++)
623                {
624                  slice->setRefPOC( slice->getRefPOC(list, j) - pocAdjustValue, list, j);
625                }
626              }
627            }
628          }
629          iterPic++;
630        }
631        m_pcEncTop->setPocAdjustmentValue( m_pcEncTop->getPocAdjustmentValue() + pocAdjustValue );
632      }
633      pcSlice->setPocValueBeforeReset( pcSlice->getPOC() - m_pcEncTop->getPocAdjustmentValue() + pocAdjustValue );
634      pcSlice->setPOC( 0 );
635    }
636#endif
637#if O0149_CROSS_LAYER_BLA_FLAG
638    if( m_layerId == 0 && (getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_N_LP) )
639    {
640      pcSlice->setCrossLayerBLAFlag(m_pcEncTop->getCrossLayerBLAFlag());
641    }
642    else
643    {
644      pcSlice->setCrossLayerBLAFlag(false);
645    }
646#endif
647#if NO_CLRAS_OUTPUT_FLAG
648    if (m_layerId == 0 &&
649        (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
650      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
651      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
652      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
653      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
654      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA))
655    {
656      if (m_bFirst)
657      {
658        m_pcEncTop->setNoClrasOutputFlag(true);
659      }
660      else if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
661            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
662            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP)
663      {
664        m_pcEncTop->setNoClrasOutputFlag(true);
665      }
666#if O0149_CROSS_LAYER_BLA_FLAG
667      else if ((pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP) &&
668               pcSlice->getCrossLayerBLAFlag())
669      {
670        m_pcEncTop->setNoClrasOutputFlag(true);
671      }
672#endif
673      else
674      {
675        m_pcEncTop->setNoClrasOutputFlag(false);
676      }
677      if (m_pcEncTop->getNoClrasOutputFlag())
678      {
679        for (UInt i = 0; i < m_pcCfg->getNumLayer(); i++)
680        {
681          m_ppcTEncTop[i]->setLayerInitializedFlag(false);
682          m_ppcTEncTop[i]->setFirstPicInLayerDecodedFlag(false);
683        }
684      }
685    }
686#endif
687#if M0040_ADAPTIVE_RESOLUTION_CHANGE
688    if (m_pcEncTop->getAdaptiveResolutionChange() > 0 && m_layerId == 1 && pocCurr > m_pcEncTop->getAdaptiveResolutionChange())
689    {
690      pcSlice->setActiveNumILRRefIdx(0);
691      pcSlice->setInterLayerPredEnabledFlag(false);
692#if M0457_COL_PICTURE_SIGNALING
693      pcSlice->setMFMEnabledFlag(false);
694#if !REMOVE_COL_PICTURE_SIGNALING
695      pcSlice->setAltColIndicationFlag(false);
696#endif
697#endif
698    }
699#endif
700
701#if M0457_IL_SAMPLE_PRED_ONLY_FLAG
702    pcSlice->setNumSamplePredRefLayers( m_pcEncTop->getNumSamplePredRefLayers() );
703    pcSlice->setInterLayerSamplePredOnlyFlag( 0 );
704    if( pcSlice->getNumSamplePredRefLayers() > 0 && pcSlice->getActiveNumILRRefIdx() > 0 )
705    {
706      if( m_pcEncTop->getIlSampleOnlyPred() > 0 )
707      {
708        pcSlice->setInterLayerSamplePredOnlyFlag( true );
709      }
710    }
711#endif
712
713    pcSlice->setLastIDR(m_iLastIDR);
714    pcSlice->setSliceIdx(0);
715    //set default slice level flag to the same as SPS level flag
716    pcSlice->setLFCrossSliceBoundaryFlag(  pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag()  );
717    pcSlice->setScalingList ( m_pcEncTop->getScalingList()  );
718    if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_OFF)
719    {
720      m_pcEncTop->getTrQuant()->setFlatScalingList();
721      m_pcEncTop->getTrQuant()->setUseScalingList(false);
722      m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
723      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
724    }
725    else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_DEFAULT)
726    {
727#if SCALINGLIST_INFERRING
728      // inferring of the scaling list can be moved to the config file
729      UInt refLayerId = 0;
730      if( m_layerId > 0 && !m_pcEncTop->getVPS()->getAvcBaseLayerFlag() && m_pcEncTop->getVPS()->getRecursiveRefLayerFlag( m_layerId, refLayerId ) )
731      {
732        m_pcEncTop->getSPS()->setInferScalingListFlag( true );
733        m_pcEncTop->getSPS()->setScalingListRefLayerId( refLayerId );
734        m_pcEncTop->getSPS()->setScalingListPresentFlag( false );
735        m_pcEncTop->getPPS()->setInferScalingListFlag( false );
736        m_pcEncTop->getPPS()->setScalingListPresentFlag( false );
737
738        // infer the scaling list from the reference layer
739        pcSlice->setScalingList ( m_ppcTEncTop[refLayerId]->getScalingList() );
740      }
741      else
742      {
743#endif
744      pcSlice->setDefaultScalingList ();
745      m_pcEncTop->getSPS()->setScalingListPresentFlag(false);
746      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
747
748#if SCALINGLIST_INFERRING
749      }
750#endif
751
752      m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList());
753      m_pcEncTop->getTrQuant()->setUseScalingList(true);
754    }
755    else if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_FILE_READ)
756    {
757#if SCALINGLIST_INFERRING
758      // inferring of the scaling list can be moved to the config file
759      UInt refLayerId = 0;
760      if( m_layerId > 0 && !m_pcEncTop->getVPS()->getAvcBaseLayerFlag() && m_pcEncTop->getVPS()->getRecursiveRefLayerFlag( m_layerId, refLayerId ) )
761      {
762        m_pcEncTop->getSPS()->setInferScalingListFlag( true );
763        m_pcEncTop->getSPS()->setScalingListRefLayerId( refLayerId );
764        m_pcEncTop->getSPS()->setScalingListPresentFlag( false );
765        m_pcEncTop->getPPS()->setInferScalingListFlag( false );
766        m_pcEncTop->getPPS()->setScalingListPresentFlag( false );
767
768        // infer the scaling list from the reference layer
769        pcSlice->setScalingList ( m_ppcTEncTop[refLayerId]->getScalingList() );
770      }
771      else
772      {
773#endif
774
775      if(pcSlice->getScalingList()->xParseScalingList(m_pcCfg->getScalingListFile()))
776      {
777        pcSlice->setDefaultScalingList ();
778      }
779
780      pcSlice->getScalingList()->checkDcOfMatrix();
781      m_pcEncTop->getSPS()->setScalingListPresentFlag(pcSlice->checkDefaultScalingList());
782      m_pcEncTop->getPPS()->setScalingListPresentFlag(false);
783
784#if SCALINGLIST_INFERRING
785    }
786#endif
787
788      m_pcEncTop->getTrQuant()->setScalingList(pcSlice->getScalingList());
789      m_pcEncTop->getTrQuant()->setUseScalingList(true);
790    }
791    else
792    {
793      printf("error : ScalingList == %d no support\n",m_pcEncTop->getUseScalingListId());
794      assert(0);
795    }
796
797    if(pcSlice->getSliceType()==B_SLICE&&m_pcCfg->getGOPEntry(iGOPid).m_sliceType=='P')
798    {
799      pcSlice->setSliceType(P_SLICE);
800    }
801    // Set the nal unit type
802    pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR));
803#if SVC_EXTENSION
804    if (m_layerId > 0)
805    {
806    Int interLayerPredLayerIdcTmp[MAX_VPS_LAYER_ID_PLUS1];
807    Int activeNumILRRefIdxTmp = 0;
808
809      for( Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
810      {
811        UInt refLayerIdc = pcSlice->getInterLayerPredLayerIdc(i);
812#if VPS_EXTN_DIRECT_REF_LAYERS
813        TComList<TComPic*> *cListPic = m_ppcTEncTop[m_layerId]->getRefLayerEnc(refLayerIdc)->getListPic();
814#else
815        TComList<TComPic*> *cListPic = m_ppcTEncTop[m_layerId-1]->getListPic();
816#endif
817        pcSlice->setBaseColPic( *cListPic, refLayerIdc );
818
819        // Apply temporal layer restriction to inter-layer prediction
820#if O0225_MAX_TID_FOR_REF_LAYERS
821        Int maxTidIlRefPicsPlus1 = m_pcEncTop->getVPS()->getMaxTidIlRefPicsPlus1(pcSlice->getBaseColPic(refLayerIdc)->getSlice(0)->getLayerId(),m_layerId);
822#else
823        Int maxTidIlRefPicsPlus1 = m_pcEncTop->getVPS()->getMaxTidIlRefPicsPlus1(pcSlice->getBaseColPic(refLayerIdc)->getSlice(0)->getLayerId());
824#endif
825        if( ((Int)(pcSlice->getBaseColPic(refLayerIdc)->getSlice(0)->getTLayer())<=maxTidIlRefPicsPlus1-1) || (maxTidIlRefPicsPlus1==0 && pcSlice->getBaseColPic(refLayerIdc)->getSlice(0)->getRapPicFlag()) )
826        {
827          interLayerPredLayerIdcTmp[activeNumILRRefIdxTmp++] = refLayerIdc; // add picture to the list of valid inter-layer pictures
828        }
829        else
830        {
831          continue; // ILP is not valid due to temporal layer restriction
832        }
833
834#if O0098_SCALED_REF_LAYER_ID
835        const Window &scalEL = m_pcEncTop->getScaledRefLayerWindowForLayer(pcSlice->getVPS()->getRefLayerId(m_layerId, refLayerIdc));
836#else
837        const Window &scalEL = m_pcEncTop->getScaledRefLayerWindow(refLayerIdc);
838#endif
839
840        Int widthBL   = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec()->getWidth();
841        Int heightBL  = pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec()->getHeight();
842
843        Int widthEL   = pcPic->getPicYuvRec()->getWidth()  - scalEL.getWindowLeftOffset() - scalEL.getWindowRightOffset();
844        Int heightEL  = pcPic->getPicYuvRec()->getHeight() - scalEL.getWindowTopOffset()  - scalEL.getWindowBottomOffset();
845
846        g_mvScalingFactor[refLayerIdc][0] = widthEL  == widthBL  ? 4096 : Clip3(-4096, 4095, ((widthEL  << 8) + (widthBL  >> 1)) / widthBL);
847        g_mvScalingFactor[refLayerIdc][1] = heightEL == heightBL ? 4096 : Clip3(-4096, 4095, ((heightEL << 8) + (heightBL >> 1)) / heightBL);
848
849        g_posScalingFactor[refLayerIdc][0] = ((widthBL  << 16) + (widthEL  >> 1)) / widthEL;
850        g_posScalingFactor[refLayerIdc][1] = ((heightBL << 16) + (heightEL >> 1)) / heightEL;
851
852#if SVC_UPSAMPLING
853        if( pcPic->isSpatialEnhLayer(refLayerIdc))
854        {
855/*#if O0098_SCALED_REF_LAYER_ID
856          Window scalEL = pcSlice->getSPS()->getScaledRefLayerWindowForLayer(pcSlice->getVPS()->getRefLayerId(m_layerId, refLayerIdc));
857#else
858          Window scalEL = pcSlice->getSPS()->getScaledRefLayerWindow(refLayerIdc);
859#endif*/
860#if O0215_PHASE_ALIGNMENT
861#if O0194_JOINT_US_BITSHIFT
862          m_pcPredSearch->upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL, pcSlice->getVPS()->getPhaseAlignFlag() );
863#else
864          m_pcPredSearch->upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL, pcSlice->getVPS()->getPhaseAlignFlag() );
865#endif
866#else
867#if O0194_JOINT_US_BITSHIFT
868          m_pcPredSearch->upsampleBasePic( pcSlice, refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL );
869#else
870          m_pcPredSearch->upsampleBasePic( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc), pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec(), pcPic->getPicYuvRec(), scalEL );
871#endif
872#endif
873        }
874        else
875        {
876          pcPic->setFullPelBaseRec( refLayerIdc, pcSlice->getBaseColPic(refLayerIdc)->getPicYuvRec() );
877        }
878        pcSlice->setFullPelBaseRec ( refLayerIdc, pcPic->getFullPelBaseRec(refLayerIdc) );
879#endif
880      }
881
882      // Update the list of active inter-layer pictures
883      for ( Int i = 0; i < activeNumILRRefIdxTmp; i++)
884      {
885        pcSlice->setInterLayerPredLayerIdc( interLayerPredLayerIdcTmp[i], i );
886      }
887
888#if !O0225_TID_BASED_IL_RPS_DERIV
889      pcSlice->setActiveNumILRRefIdx( activeNumILRRefIdxTmp );
890#endif
891      if ( pcSlice->getActiveNumILRRefIdx() == 0 )
892      {
893        // No valid inter-layer pictures -> disable inter-layer prediction
894        pcSlice->setInterLayerPredEnabledFlag(false);
895      }
896     
897      if( pocCurr % m_pcCfg->getIntraPeriod() == 0 )
898      {
899#if N0147_IRAP_ALIGN_FLAG
900        if(pcSlice->getVPS()->getCrossLayerIrapAlignFlag())
901        {
902          TComList<TComPic*> *cListPic = m_ppcTEncTop[m_layerId]->getRefLayerEnc(0)->getListPic();
903          TComPic* picLayer0 = pcSlice->getRefPic(*cListPic, pcSlice->getPOC() );
904          if(picLayer0)
905          {
906            pcSlice->setNalUnitType(picLayer0->getSlice(0)->getNalUnitType());
907          }
908          else
909          {
910            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_CRA);
911          }
912        }
913        else
914#endif
915        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_CRA);
916
917#if IDR_ALIGNMENT
918        TComList<TComPic*> *cListPic = m_ppcTEncTop[m_layerId]->getRefLayerEnc(0)->getListPic();
919        TComPic* picLayer0 = pcSlice->getRefPic(*cListPic, pcSlice->getPOC() );
920        if( picLayer0->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || picLayer0->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )
921        {
922          pcSlice->setNalUnitType(picLayer0->getSlice(0)->getNalUnitType());
923        }
924        else
925        {
926          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_CRA);
927        }
928#endif
929      }
930     
931      if( pcSlice->getActiveNumILRRefIdx() == 0 && pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA )
932      {
933        pcSlice->setSliceType(I_SLICE);
934      }
935      else if( !m_pcEncTop->getElRapSliceTypeB() )
936      {
937        if( (pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP) &&
938           (pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA) &&
939           pcSlice->getSliceType() == B_SLICE )
940        {
941          pcSlice->setSliceType(P_SLICE);
942        }
943      }
944    }
945#endif //#if SVC_EXTENSION
946    if(pcSlice->getTemporalLayerNonReferenceFlag())
947    {
948      if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_TRAIL_R &&
949          !(m_iGopSize == 1 && pcSlice->getSliceType() == I_SLICE))
950        // Add this condition to avoid POC issues with encoder_intra_main.cfg configuration (see #1127 in bug tracker)
951      {
952        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TRAIL_N);
953    }
954      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_RADL_R)
955      {
956        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_RADL_N);
957      }
958      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_RASL_R)
959      {
960        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_RASL_N);
961      }
962    }
963
964    // Do decoding refresh marking if any
965#if NO_CLRAS_OUTPUT_FLAG
966    pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic, m_pcEncTop->getNoClrasOutputFlag());
967#else
968    pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic);
969#endif
970    m_pcEncTop->selectReferencePictureSet(pcSlice, pocCurr, iGOPid);
971    pcSlice->getRPS()->setNumberOfLongtermPictures(0);
972
973    if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0) || (pcSlice->isIRAP()))
974    {
975      pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP());
976    }
977    pcSlice->applyReferencePictureSet(rcListPic, pcSlice->getRPS());
978
979    if(pcSlice->getTLayer() > 0)
980    {
981      if(pcSlice->isTemporalLayerSwitchingPoint(rcListPic) || pcSlice->getSPS()->getTemporalIdNestingFlag())
982      {
983#if ALIGN_TSA_STSA_PICS
984        if( pcSlice->getLayerId() > 0 )
985        {
986          Bool oneRefLayerTSA = false, oneRefLayerNotTSA = false;
987          for( Int i = 0; i < pcSlice->getLayerId(); i++)
988          {
989            TComList<TComPic *> *cListPic = m_ppcTEncTop[i]->getListPic();
990            TComPic *lowerLayerPic = pcSlice->getRefPic(*cListPic, pcSlice->getPOC());
991            if( lowerLayerPic && pcSlice->getVPS()->getDirectDependencyFlag(pcSlice->getLayerId(), i) )
992            {
993              if( ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N ) ||
994                  ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R ) 
995                )
996              {
997                if(pcSlice->getTemporalLayerNonReferenceFlag() )
998                {
999                  pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_N);
1000                }
1001                else
1002                {
1003                  pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R );
1004                }
1005                oneRefLayerTSA = true;
1006              }
1007              else
1008              {
1009                oneRefLayerNotTSA = true;
1010              }
1011            }
1012          }
1013          assert( !( oneRefLayerNotTSA && oneRefLayerTSA ) ); // Only one variable should be true - failure of this assert means
1014                                                                // that two independent reference layers that are not dependent on
1015                                                                // each other, but are reference for current layer have inconsistency
1016          if( oneRefLayerNotTSA /*&& !oneRefLayerTSA*/ )          // No reference layer is TSA - set current as TRAIL
1017          {
1018            if(pcSlice->getTemporalLayerNonReferenceFlag() )
1019            {
1020              pcSlice->setNalUnitType( NAL_UNIT_CODED_SLICE_TRAIL_N );
1021            }
1022            else
1023            {
1024              pcSlice->setNalUnitType( NAL_UNIT_CODED_SLICE_TRAIL_R );
1025            }
1026          }
1027          else  // This means there is no reference layer picture for current picture in this AU
1028          {
1029            if(pcSlice->getTemporalLayerNonReferenceFlag() )
1030            {
1031              pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_N);
1032            }
1033            else
1034            {
1035              pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R );
1036            }
1037          }
1038        }
1039#else
1040        if(pcSlice->getTemporalLayerNonReferenceFlag())
1041        {
1042          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_N);
1043        }
1044        else
1045        {
1046          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R);
1047        }
1048#endif
1049      }
1050      else if(pcSlice->isStepwiseTemporalLayerSwitchingPointCandidate(rcListPic))
1051      {
1052        Bool isSTSA=true;
1053        for(Int ii=iGOPid+1;(ii<m_pcCfg->getGOPSize() && isSTSA==true);ii++)
1054        {
1055          Int lTid= m_pcCfg->getGOPEntry(ii).m_temporalId;
1056          if(lTid==pcSlice->getTLayer()) 
1057          {
1058            TComReferencePictureSet* nRPS = pcSlice->getSPS()->getRPSList()->getReferencePictureSet(ii);
1059            for(Int jj=0;jj<nRPS->getNumberOfPictures();jj++)
1060            {
1061              if(nRPS->getUsed(jj)) 
1062              {
1063                Int tPoc=m_pcCfg->getGOPEntry(ii).m_POC+nRPS->getDeltaPOC(jj);
1064                Int kk=0;
1065                for(kk=0;kk<m_pcCfg->getGOPSize();kk++)
1066                {
1067                  if(m_pcCfg->getGOPEntry(kk).m_POC==tPoc)
1068                    break;
1069                }
1070                Int tTid=m_pcCfg->getGOPEntry(kk).m_temporalId;
1071                if(tTid >= pcSlice->getTLayer())
1072                {
1073                  isSTSA=false;
1074                  break;
1075                }
1076              }
1077            }
1078          }
1079        }
1080        if(isSTSA==true)
1081        {   
1082#if ALIGN_TSA_STSA_PICS
1083          if( pcSlice->getLayerId() > 0 )
1084          {
1085            Bool oneRefLayerSTSA = false, oneRefLayerNotSTSA = false;
1086            for( Int i = 0; i < pcSlice->getLayerId(); i++)
1087            {
1088              TComList<TComPic *> *cListPic = m_ppcTEncTop[i]->getListPic();
1089              TComPic *lowerLayerPic = pcSlice->getRefPic(*cListPic, pcSlice->getPOC());
1090              if( lowerLayerPic && pcSlice->getVPS()->getDirectDependencyFlag(pcSlice->getLayerId(), i) )
1091              {
1092                if( ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_STSA_N ) ||
1093                    ( lowerLayerPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_STSA_R ) 
1094                  )
1095                {
1096                  if(pcSlice->getTemporalLayerNonReferenceFlag() )
1097                  {
1098                    pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_N);
1099                  }
1100                  else
1101                  {
1102                    pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_R );
1103                  }
1104                  oneRefLayerSTSA = true;
1105                }
1106                else
1107                {
1108                  oneRefLayerNotSTSA = true;
1109                }
1110              }
1111            }
1112            assert( !( oneRefLayerNotSTSA && oneRefLayerSTSA ) ); // Only one variable should be true - failure of this assert means
1113                                                                  // that two independent reference layers that are not dependent on
1114                                                                  // each other, but are reference for current layer have inconsistency
1115            if( oneRefLayerNotSTSA /*&& !oneRefLayerSTSA*/ )          // No reference layer is STSA - set current as TRAIL
1116            {
1117              if(pcSlice->getTemporalLayerNonReferenceFlag() )
1118              {
1119                pcSlice->setNalUnitType( NAL_UNIT_CODED_SLICE_TRAIL_N );
1120              }
1121              else
1122              {
1123                pcSlice->setNalUnitType( NAL_UNIT_CODED_SLICE_TRAIL_R );
1124              }
1125            }
1126            else  // This means there is no reference layer picture for current picture in this AU
1127            {
1128              if(pcSlice->getTemporalLayerNonReferenceFlag() )
1129              {
1130                pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_N);
1131              }
1132              else
1133              {
1134                pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_R );
1135              }
1136            }
1137          }
1138#else
1139          if(pcSlice->getTemporalLayerNonReferenceFlag())
1140          {
1141            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_N);
1142          }
1143          else
1144          {
1145            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_R);
1146          }
1147#endif
1148        }
1149      }
1150    }
1151    arrangeLongtermPicturesInRPS(pcSlice, rcListPic);
1152    TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
1153    refPicListModification->setRefPicListModificationFlagL0(0);
1154    refPicListModification->setRefPicListModificationFlagL1(0);
1155    pcSlice->setNumRefIdx(REF_PIC_LIST_0,min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive,pcSlice->getRPS()->getNumberOfPictures()));
1156    pcSlice->setNumRefIdx(REF_PIC_LIST_1,min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive,pcSlice->getRPS()->getNumberOfPictures()));
1157
1158#if SVC_EXTENSION
1159    if( m_layerId > 0 && pcSlice->getActiveNumILRRefIdx() )
1160    {
1161#if RESTR_CHK
1162#if POC_RESET_FLAG
1163      if ( pocCurr > 0          && pcSlice->isRADL() && pcPic->getSlice(0)->getBaseColPic(pcPic->getSlice(0)->getInterLayerPredLayerIdc(0))->getSlice(0)->isRASL())
1164#else
1165      if (pcSlice->getPOC()>0  && pcSlice->isRADL() && pcPic->getSlice(0)->getBaseColPic(pcPic->getSlice(0)->getInterLayerPredLayerIdc(0))->getSlice(0)->isRASL())
1166#endif
1167      {
1168#if JCTVC_M0458_INTERLAYER_RPS_SIG
1169        pcSlice->setActiveNumILRRefIdx(0);
1170        pcSlice->setInterLayerPredEnabledFlag(0);
1171#else
1172        pcSlice->setNumILRRefIdx(0);
1173#endif
1174      }
1175#endif
1176#if JCTVC_M0458_INTERLAYER_RPS_SIG
1177      if( pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA )
1178      {
1179        pcSlice->setNumRefIdx(REF_PIC_LIST_0, pcSlice->getActiveNumILRRefIdx());
1180        pcSlice->setNumRefIdx(REF_PIC_LIST_1, pcSlice->getActiveNumILRRefIdx());
1181      }
1182      else
1183      {
1184        pcSlice->setNumRefIdx(REF_PIC_LIST_0, pcSlice->getNumRefIdx(REF_PIC_LIST_0)+pcSlice->getActiveNumILRRefIdx());
1185        pcSlice->setNumRefIdx(REF_PIC_LIST_1, pcSlice->getNumRefIdx(REF_PIC_LIST_1)+pcSlice->getActiveNumILRRefIdx());
1186      }
1187#else
1188      if( pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA )
1189      {
1190        pcSlice->setNumRefIdx(REF_PIC_LIST_0, pcSlice->getNumILRRefIdx());
1191        pcSlice->setNumRefIdx(REF_PIC_LIST_1, pcSlice->getNumILRRefIdx());
1192      }
1193      else
1194      {
1195        pcSlice->setNumRefIdx(REF_PIC_LIST_0, pcSlice->getNumRefIdx(REF_PIC_LIST_0)+pcSlice->getNumILRRefIdx());
1196        pcSlice->setNumRefIdx(REF_PIC_LIST_1, pcSlice->getNumRefIdx(REF_PIC_LIST_1)+pcSlice->getNumILRRefIdx());
1197      }
1198#endif
1199    }
1200#endif //SVC_EXTENSION
1201
1202#if ADAPTIVE_QP_SELECTION
1203    pcSlice->setTrQuant( m_pcEncTop->getTrQuant() );
1204#endif     
1205
1206#if SVC_EXTENSION
1207#if M0457_COL_PICTURE_SIGNALING && !REMOVE_COL_PICTURE_SIGNALING
1208    if ( pcSlice->getSliceType() == B_SLICE && !(pcSlice->getActiveNumILRRefIdx() > 0 && m_pcEncTop->getNumMotionPredRefLayers() > 0) )
1209#else
1210    if( pcSlice->getSliceType() == B_SLICE )
1211#endif
1212    {
1213      pcSlice->setColFromL0Flag(1-uiColDir);
1214    }
1215
1216    //  Set reference list
1217    if(m_layerId ==  0 || ( m_layerId > 0 && pcSlice->getActiveNumILRRefIdx() == 0 ) )
1218    {
1219      pcSlice->setRefPicList( rcListPic);
1220    }
1221
1222    if( m_layerId > 0 && pcSlice->getActiveNumILRRefIdx() )
1223    {
1224      pcSlice->setILRPic( m_pcEncTop->getIlpList() );
1225#if REF_IDX_MFM
1226#if M0457_COL_PICTURE_SIGNALING
1227      if( pcSlice->getMFMEnabledFlag() )
1228#else
1229      if( pcSlice->getSPS()->getMFMEnabledFlag() )
1230#endif
1231      {
1232        pcSlice->setRefPOCListILP(m_pcEncTop->getIlpList(), pcSlice->getBaseColPic());
1233#if M0457_COL_PICTURE_SIGNALING && !REMOVE_COL_PICTURE_SIGNALING
1234        pcSlice->setMotionPredIlp(getMotionPredIlp(pcSlice));
1235#endif
1236      }
1237#else
1238      //  Set reference list
1239      pcSlice->setRefPicList ( rcListPic );
1240#endif //SVC_EXTENSION
1241      pcSlice->setRefPicListModificationSvc();
1242      pcSlice->setRefPicList( rcListPic, false, m_pcEncTop->getIlpList());
1243
1244#if REF_IDX_MFM
1245#if M0457_COL_PICTURE_SIGNALING
1246#if REMOVE_COL_PICTURE_SIGNALING
1247      if( pcSlice->getMFMEnabledFlag() )
1248#else
1249      if( pcSlice->getMFMEnabledFlag() && !(pcSlice->getActiveNumILRRefIdx() > 0 && m_pcEncTop->getNumMotionPredRefLayers() > 0) )
1250#endif
1251#else
1252      if( pcSlice->getSPS()->getMFMEnabledFlag() )
1253#endif
1254      {
1255        Bool found         = false;
1256        UInt ColFromL0Flag = pcSlice->getColFromL0Flag();
1257        UInt ColRefIdx     = pcSlice->getColRefIdx();
1258
1259        for(Int colIdx = 0; colIdx < pcSlice->getNumRefIdx( RefPicList(1 - ColFromL0Flag) ); colIdx++) 
1260        { 
1261          if( pcSlice->getRefPic( RefPicList(1 - ColFromL0Flag), colIdx)->isILR(m_layerId) 
1262#if MFM_ENCCONSTRAINT
1263            && pcSlice->getBaseColPic( *m_ppcTEncTop[pcSlice->getRefPic( RefPicList(1 - ColFromL0Flag), colIdx)->getLayerId()]->getListPic() )->checkSameRefInfo() == true 
1264#endif
1265            ) 
1266          { 
1267            ColRefIdx = colIdx; 
1268            found = true;
1269            break; 
1270          }
1271        }
1272
1273        if( found == false )
1274        {
1275          ColFromL0Flag = 1 - ColFromL0Flag;
1276          for(Int colIdx = 0; colIdx < pcSlice->getNumRefIdx( RefPicList(1 - ColFromL0Flag) ); colIdx++) 
1277          { 
1278            if( pcSlice->getRefPic( RefPicList(1 - ColFromL0Flag), colIdx)->isILR(m_layerId) 
1279#if MFM_ENCCONSTRAINT
1280              && pcSlice->getBaseColPic( *m_ppcTEncTop[pcSlice->getRefPic( RefPicList(1 - ColFromL0Flag), colIdx)->getLayerId()]->getListPic() )->checkSameRefInfo() == true 
1281#endif
1282              ) 
1283            { 
1284              ColRefIdx = colIdx; 
1285              found = true; 
1286              break; 
1287            } 
1288          }
1289        }
1290
1291        if(found == true)
1292        {
1293          pcSlice->setColFromL0Flag(ColFromL0Flag);
1294          pcSlice->setColRefIdx(ColRefIdx);
1295        }
1296      }
1297#endif
1298    }
1299#else //SVC_EXTENSION
1300    //  Set reference list
1301    pcSlice->setRefPicList ( rcListPic );
1302#endif //#if SVC_EXTENSION
1303
1304    //  Slice info. refinement
1305    if ( (pcSlice->getSliceType() == B_SLICE) && (pcSlice->getNumRefIdx(REF_PIC_LIST_1) == 0) )
1306    {
1307      pcSlice->setSliceType ( P_SLICE );
1308    }
1309
1310#if M0457_IL_SAMPLE_PRED_ONLY_FLAG
1311    if (pcSlice->getSliceType() == B_SLICE && m_pcEncTop->getIlSampleOnlyPred() == 0)
1312#else
1313    if (pcSlice->getSliceType() == B_SLICE)
1314#endif
1315    {
1316#if !SVC_EXTENSION
1317      pcSlice->setColFromL0Flag(1-uiColDir);
1318#endif
1319      Bool bLowDelay = true;
1320      Int  iCurrPOC  = pcSlice->getPOC();
1321      Int iRefIdx = 0;
1322
1323      for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_0) && bLowDelay; iRefIdx++)
1324      {
1325        if ( pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx)->getPOC() > iCurrPOC )
1326        {
1327          bLowDelay = false;
1328        }
1329      }
1330      for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_1) && bLowDelay; iRefIdx++)
1331      {
1332        if ( pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx)->getPOC() > iCurrPOC )
1333        {
1334          bLowDelay = false;
1335        }
1336      }
1337
1338      pcSlice->setCheckLDC(bLowDelay); 
1339    }
1340    else
1341    {
1342      pcSlice->setCheckLDC(true); 
1343    }
1344
1345    uiColDir = 1-uiColDir;
1346
1347    //-------------------------------------------------------------
1348    pcSlice->setRefPOCList();
1349
1350    pcSlice->setList1IdxToList0Idx();
1351
1352    if (m_pcEncTop->getTMVPModeId() == 2)
1353    {
1354      if (iGOPid == 0) // first picture in SOP (i.e. forward B)
1355      {
1356        pcSlice->setEnableTMVPFlag(0);
1357      }
1358      else
1359      {
1360        // Note: pcSlice->getColFromL0Flag() is assumed to be always 0 and getcolRefIdx() is always 0.
1361        pcSlice->setEnableTMVPFlag(1);
1362      }
1363      pcSlice->getSPS()->setTMVPFlagsPresent(1);
1364    }
1365    else if (m_pcEncTop->getTMVPModeId() == 1)
1366    {
1367      pcSlice->getSPS()->setTMVPFlagsPresent(1);
1368#if SVC_EXTENSION
1369      if( pcSlice->getIdrPicFlag() )
1370      {
1371        pcSlice->setEnableTMVPFlag(0);
1372      }
1373      else
1374#endif
1375      pcSlice->setEnableTMVPFlag(1);
1376    }
1377    else
1378    {
1379      pcSlice->getSPS()->setTMVPFlagsPresent(0);
1380      pcSlice->setEnableTMVPFlag(0);
1381    }
1382    /////////////////////////////////////////////////////////////////////////////////////////////////// Compress a slice
1383    //  Slice compression
1384    if (m_pcCfg->getUseASR())
1385    {
1386      m_pcSliceEncoder->setSearchRange(pcSlice);
1387    }
1388
1389    Bool bGPBcheck=false;
1390    if ( pcSlice->getSliceType() == B_SLICE)
1391    {
1392      if ( pcSlice->getNumRefIdx(RefPicList( 0 ) ) == pcSlice->getNumRefIdx(RefPicList( 1 ) ) )
1393      {
1394        bGPBcheck=true;
1395        Int i;
1396        for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
1397        {
1398          if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) ) 
1399          {
1400            bGPBcheck=false;
1401            break;
1402          }
1403        }
1404      }
1405    }
1406    if(bGPBcheck)
1407    {
1408      pcSlice->setMvdL1ZeroFlag(true);
1409    }
1410    else
1411    {
1412      pcSlice->setMvdL1ZeroFlag(false);
1413    }
1414    pcPic->getSlice(pcSlice->getSliceIdx())->setMvdL1ZeroFlag(pcSlice->getMvdL1ZeroFlag());
1415
1416    Double lambda            = 0.0;
1417    Int actualHeadBits       = 0;
1418    Int actualTotalBits      = 0;
1419    Int estimatedBits        = 0;
1420    Int tmpBitsBeforeWriting = 0;
1421    if ( m_pcCfg->getUseRateCtrl() )
1422    {
1423      Int frameLevel = m_pcRateCtrl->getRCSeq()->getGOPID2Level( iGOPid );
1424      if ( pcPic->getSlice(0)->getSliceType() == I_SLICE )
1425      {
1426        frameLevel = 0;
1427      }
1428      m_pcRateCtrl->initRCPic( frameLevel );
1429      estimatedBits = m_pcRateCtrl->getRCPic()->getTargetBits();
1430
1431      Int sliceQP = m_pcCfg->getInitialQP();
1432#if POC_RESET_FLAG
1433      if ( ( pocCurr == 0 && m_pcCfg->getInitialQP() > 0 ) || ( frameLevel == 0 && m_pcCfg->getForceIntraQP() ) ) // QP is specified
1434#else
1435      if ( ( pcSlice->getPOC() == 0 && m_pcCfg->getInitialQP() > 0 ) || ( frameLevel == 0 && m_pcCfg->getForceIntraQP() ) ) // QP is specified
1436#endif
1437      {
1438        Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
1439        Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)NumberBFrames );
1440        Double dQPFactor     = 0.57*dLambda_scale;
1441        Int    SHIFT_QP      = 12;
1442        Int    bitdepth_luma_qp_scale = 0;
1443        Double qp_temp = (Double) sliceQP + bitdepth_luma_qp_scale - SHIFT_QP;
1444        lambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
1445      }
1446      else if ( frameLevel == 0 )   // intra case, but use the model
1447      {
1448        m_pcSliceEncoder->calCostSliceI(pcPic);
1449        if ( m_pcCfg->getIntraPeriod() != 1 )   // do not refine allocated bits for all intra case
1450        {
1451          Int bits = m_pcRateCtrl->getRCSeq()->getLeftAverageBits();
1452          bits = m_pcRateCtrl->getRCPic()->getRefineBitsForIntra( bits );
1453          if ( bits < 200 )
1454          {
1455            bits = 200;
1456          }
1457          m_pcRateCtrl->getRCPic()->setTargetBits( bits );
1458        }
1459
1460        list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
1461        m_pcRateCtrl->getRCPic()->getLCUInitTargetBits();
1462        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
1463        sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
1464      }
1465      else    // normal case
1466      {
1467        list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
1468        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
1469        sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
1470      }
1471
1472#if REPN_FORMAT_IN_VPS
1473      sliceQP = Clip3( -pcSlice->getQpBDOffsetY(), MAX_QP, sliceQP );
1474#else
1475      sliceQP = Clip3( -pcSlice->getSPS()->getQpBDOffsetY(), MAX_QP, sliceQP );
1476#endif
1477      m_pcRateCtrl->getRCPic()->setPicEstQP( sliceQP );
1478
1479      m_pcSliceEncoder->resetQP( pcPic, sliceQP, lambda );
1480    }
1481
1482    UInt uiNumSlices = 1;
1483
1484    UInt uiInternalAddress = pcPic->getNumPartInCU()-4;
1485    UInt uiExternalAddress = pcPic->getPicSym()->getNumberOfCUsInFrame()-1;
1486    UInt uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
1487    UInt uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
1488#if REPN_FORMAT_IN_VPS
1489    UInt uiWidth = pcSlice->getPicWidthInLumaSamples();
1490    UInt uiHeight = pcSlice->getPicHeightInLumaSamples();
1491#else
1492    UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
1493    UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
1494#endif
1495    while(uiPosX>=uiWidth||uiPosY>=uiHeight) 
1496    {
1497      uiInternalAddress--;
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    }
1501    uiInternalAddress++;
1502    if(uiInternalAddress==pcPic->getNumPartInCU()) 
1503    {
1504      uiInternalAddress = 0;
1505      uiExternalAddress++;
1506    }
1507    UInt uiRealEndAddress = uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress;
1508
1509    UInt uiCummulativeTileWidth;
1510    UInt uiCummulativeTileHeight;
1511    Int  p, j;
1512    UInt uiEncCUAddr;
1513
1514    //set NumColumnsMinus1 and NumRowsMinus1
1515    pcPic->getPicSym()->setNumColumnsMinus1( pcSlice->getPPS()->getNumColumnsMinus1() );
1516    pcPic->getPicSym()->setNumRowsMinus1( pcSlice->getPPS()->getNumRowsMinus1() );
1517
1518    //create the TComTileArray
1519    pcPic->getPicSym()->xCreateTComTileArray();
1520
1521    if( pcSlice->getPPS()->getUniformSpacingFlag() == 1 )
1522    {
1523      //set the width for each tile
1524      for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
1525      {
1526        for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1()+1; p++)
1527        {
1528          pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->
1529            setTileWidth( (p+1)*pcPic->getPicSym()->getFrameWidthInCU()/(pcPic->getPicSym()->getNumColumnsMinus1()+1) 
1530            - (p*pcPic->getPicSym()->getFrameWidthInCU())/(pcPic->getPicSym()->getNumColumnsMinus1()+1) );
1531        }
1532      }
1533
1534      //set the height for each tile
1535      for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
1536      {
1537        for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1()+1; p++)
1538        {
1539          pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->
1540            setTileHeight( (p+1)*pcPic->getPicSym()->getFrameHeightInCU()/(pcPic->getPicSym()->getNumRowsMinus1()+1) 
1541            - (p*pcPic->getPicSym()->getFrameHeightInCU())/(pcPic->getPicSym()->getNumRowsMinus1()+1) );   
1542        }
1543      }
1544    }
1545    else
1546    {
1547      //set the width for each tile
1548      for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
1549      {
1550        uiCummulativeTileWidth = 0;
1551        for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1(); p++)
1552        {
1553          pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->setTileWidth( pcSlice->getPPS()->getColumnWidth(p) );
1554          uiCummulativeTileWidth += pcSlice->getPPS()->getColumnWidth(p);
1555        }
1556        pcPic->getPicSym()->getTComTile(j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p)->setTileWidth( pcPic->getPicSym()->getFrameWidthInCU()-uiCummulativeTileWidth );
1557      }
1558
1559      //set the height for each tile
1560      for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
1561      {
1562        uiCummulativeTileHeight = 0;
1563        for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1(); p++)
1564        {
1565          pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->setTileHeight( pcSlice->getPPS()->getRowHeight(p) );
1566          uiCummulativeTileHeight += pcSlice->getPPS()->getRowHeight(p);
1567        }
1568        pcPic->getPicSym()->getTComTile(p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcPic->getPicSym()->getFrameHeightInCU()-uiCummulativeTileHeight );
1569      }
1570    }
1571    //intialize each tile of the current picture
1572    pcPic->getPicSym()->xInitTiles();
1573
1574#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
1575    if (m_pcCfg->getInterLayerConstrainedTileSetsSEIEnabled())
1576    {
1577      xBuildTileSetsMap(pcPic->getPicSym());
1578    }
1579#endif
1580
1581    // Allocate some coders, now we know how many tiles there are.
1582    Int iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
1583
1584    //generate the Coding Order Map and Inverse Coding Order Map
1585    for(p=0, uiEncCUAddr=0; p<pcPic->getPicSym()->getNumberOfCUsInFrame(); p++, uiEncCUAddr = pcPic->getPicSym()->xCalculateNxtCUAddr(uiEncCUAddr))
1586    {
1587      pcPic->getPicSym()->setCUOrderMap(p, uiEncCUAddr);
1588      pcPic->getPicSym()->setInverseCUOrderMap(uiEncCUAddr, p);
1589    }
1590    pcPic->getPicSym()->setCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());   
1591    pcPic->getPicSym()->setInverseCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());
1592
1593    // Allocate some coders, now we know how many tiles there are.
1594    m_pcEncTop->createWPPCoders(iNumSubstreams);
1595    pcSbacCoders = m_pcEncTop->getSbacCoders();
1596    pcSubstreamsOut = new TComOutputBitstream[iNumSubstreams];
1597
1598    UInt startCUAddrSliceIdx = 0; // used to index "m_uiStoredStartCUAddrForEncodingSlice" containing locations of slice boundaries
1599    UInt startCUAddrSlice    = 0; // used to keep track of current slice's starting CU addr.
1600    pcSlice->setSliceCurStartCUAddr( startCUAddrSlice ); // Setting "start CU addr" for current slice
1601    m_storedStartCUAddrForEncodingSlice.clear();
1602
1603    UInt startCUAddrSliceSegmentIdx = 0; // used to index "m_uiStoredStartCUAddrForEntropyEncodingSlice" containing locations of slice boundaries
1604    UInt startCUAddrSliceSegment    = 0; // used to keep track of current Dependent slice's starting CU addr.
1605    pcSlice->setSliceSegmentCurStartCUAddr( startCUAddrSliceSegment ); // Setting "start CU addr" for current Dependent slice
1606
1607    m_storedStartCUAddrForEncodingSliceSegment.clear();
1608    UInt nextCUAddr = 0;
1609    m_storedStartCUAddrForEncodingSlice.push_back (nextCUAddr);
1610    startCUAddrSliceIdx++;
1611    m_storedStartCUAddrForEncodingSliceSegment.push_back(nextCUAddr);
1612    startCUAddrSliceSegmentIdx++;
1613#if AVC_BASE
1614    if( m_layerId == 0 && m_pcEncTop->getVPS()->getAvcBaseLayerFlag() )
1615    {
1616      pcPic->getPicYuvOrg()->copyToPic( pcPic->getPicYuvRec() );
1617#if O0194_WEIGHTED_PREDICTION_CGS
1618      // Calculate for the base layer to be used in EL as Inter layer reference
1619      m_pcSliceEncoder->estimateILWpParam( pcSlice );
1620#endif
1621#if AVC_SYNTAX
1622      pcPic->readBLSyntax( m_ppcTEncTop[0]->getBLSyntaxFile(), SYNTAX_BYTES );
1623#endif
1624      return;
1625    }
1626#endif
1627
1628    while(nextCUAddr<uiRealEndAddress) // determine slice boundaries
1629    {
1630      pcSlice->setNextSlice       ( false );
1631      pcSlice->setNextSliceSegment( false );
1632      assert(pcPic->getNumAllocatedSlice() == startCUAddrSliceIdx);
1633      m_pcSliceEncoder->precompressSlice( pcPic );
1634      m_pcSliceEncoder->compressSlice   ( pcPic );
1635
1636      Bool bNoBinBitConstraintViolated = (!pcSlice->isNextSlice() && !pcSlice->isNextSliceSegment());
1637      if (pcSlice->isNextSlice() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_LCU))
1638      {
1639        startCUAddrSlice = pcSlice->getSliceCurEndCUAddr();
1640        // Reconstruction slice
1641        m_storedStartCUAddrForEncodingSlice.push_back(startCUAddrSlice);
1642        startCUAddrSliceIdx++;
1643        // Dependent slice
1644        if (startCUAddrSliceSegmentIdx>0 && m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx-1] != startCUAddrSlice)
1645        {
1646          m_storedStartCUAddrForEncodingSliceSegment.push_back(startCUAddrSlice);
1647          startCUAddrSliceSegmentIdx++;
1648        }
1649
1650        if (startCUAddrSlice < uiRealEndAddress)
1651        {
1652          pcPic->allocateNewSlice();         
1653          pcPic->setCurrSliceIdx                  ( startCUAddrSliceIdx-1 );
1654          m_pcSliceEncoder->setSliceIdx           ( startCUAddrSliceIdx-1 );
1655          pcSlice = pcPic->getSlice               ( startCUAddrSliceIdx-1 );
1656          pcSlice->copySliceInfo                  ( pcPic->getSlice(0)      );
1657          pcSlice->setSliceIdx                    ( startCUAddrSliceIdx-1 );
1658          pcSlice->setSliceCurStartCUAddr         ( startCUAddrSlice      );
1659          pcSlice->setSliceSegmentCurStartCUAddr  ( startCUAddrSlice      );
1660          pcSlice->setSliceBits(0);
1661#if SVC_EXTENSION
1662          // copy reference list modification info from the first slice, assuming that this information is the same across all slices in the picture
1663          memcpy( pcSlice->getRefPicListModification(), pcPic->getSlice(0)->getRefPicListModification(), sizeof(TComRefPicListModification) );
1664#endif
1665          uiNumSlices ++;
1666        }
1667      }
1668      else if (pcSlice->isNextSliceSegment() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_LCU))
1669      {
1670        startCUAddrSliceSegment                                                     = pcSlice->getSliceSegmentCurEndCUAddr();
1671        m_storedStartCUAddrForEncodingSliceSegment.push_back(startCUAddrSliceSegment);
1672        startCUAddrSliceSegmentIdx++;
1673        pcSlice->setSliceSegmentCurStartCUAddr( startCUAddrSliceSegment );
1674      }
1675      else
1676      {
1677        startCUAddrSlice                                                            = pcSlice->getSliceCurEndCUAddr();
1678        startCUAddrSliceSegment                                                     = pcSlice->getSliceSegmentCurEndCUAddr();
1679      }       
1680
1681      nextCUAddr = (startCUAddrSlice > startCUAddrSliceSegment) ? startCUAddrSlice : startCUAddrSliceSegment;
1682    }
1683    m_storedStartCUAddrForEncodingSlice.push_back( pcSlice->getSliceCurEndCUAddr());
1684    startCUAddrSliceIdx++;
1685    m_storedStartCUAddrForEncodingSliceSegment.push_back(pcSlice->getSliceCurEndCUAddr());
1686    startCUAddrSliceSegmentIdx++;
1687
1688    pcSlice = pcPic->getSlice(0);
1689
1690    // SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
1691#if HM_CLEANUP_SAO
1692    if( pcSlice->getSPS()->getUseSAO() && m_pcCfg->getSaoLcuBoundary() )
1693    {
1694      m_pcSAO->getPreDBFStatistics(pcPic);
1695    }
1696#else
1697    if( m_pcCfg->getSaoLcuBasedOptimization() && m_pcCfg->getSaoLcuBoundary() )
1698    {
1699      m_pcSAO->resetStats();
1700      m_pcSAO->calcSaoStatsCu_BeforeDblk( pcPic );
1701    }
1702#endif   
1703    //-- Loop filter
1704    Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
1705    m_pcLoopFilter->setCfg(bLFCrossTileBoundary);
1706    if ( m_pcCfg->getDeblockingFilterMetric() )
1707    {
1708      dblMetric(pcPic, uiNumSlices);
1709    }
1710    m_pcLoopFilter->loopFilterPic( pcPic );
1711
1712#if !HM_CLEANUP_SAO   
1713    pcSlice = pcPic->getSlice(0);
1714    if(pcSlice->getSPS()->getUseSAO())
1715    {
1716      std::vector<Bool> LFCrossSliceBoundaryFlag;
1717      for(Int s=0; s< uiNumSlices; s++)
1718      {
1719        LFCrossSliceBoundaryFlag.push_back(  ((uiNumSlices==1)?true:pcPic->getSlice(s)->getLFCrossSliceBoundaryFlag()) );
1720      }
1721      m_storedStartCUAddrForEncodingSlice.resize(uiNumSlices+1);
1722      pcPic->createNonDBFilterInfo(m_storedStartCUAddrForEncodingSlice, 0, &LFCrossSliceBoundaryFlag ,pcPic->getPicSym()->getNumTiles() ,bLFCrossTileBoundary);
1723    }
1724
1725
1726    pcSlice = pcPic->getSlice(0);
1727
1728    if(pcSlice->getSPS()->getUseSAO())
1729    {
1730      m_pcSAO->createPicSaoInfo(pcPic);
1731    }
1732#endif
1733    /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
1734    // Set entropy coder
1735    m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
1736
1737    /* write various header sets. */
1738    if ( m_bSeqFirst )
1739    {
1740#if SVC_EXTENSION
1741#if VPS_NUH_LAYER_ID
1742      OutputNALUnit nalu(NAL_UNIT_VPS, 0, 0        ); // The value of nuh_layer_id of VPS NAL unit shall be equal to 0.
1743#else
1744      OutputNALUnit nalu(NAL_UNIT_VPS, 0, m_layerId);
1745#endif
1746#if AVC_BASE
1747      if( ( m_layerId == 1 && m_pcEncTop->getVPS()->getAvcBaseLayerFlag() ) || ( m_layerId == 0 && !m_pcEncTop->getVPS()->getAvcBaseLayerFlag() ) )
1748#else
1749      if( m_layerId == 0 )
1750#endif
1751      {
1752#else
1753      OutputNALUnit nalu(NAL_UNIT_VPS);
1754#endif
1755#if VPS_EXTN_OFFSET_CALC
1756      OutputNALUnit tempNalu(NAL_UNIT_VPS, 0, 0        ); // The value of nuh_layer_id of VPS NAL unit shall be equal to 0.
1757      m_pcEntropyCoder->setBitstream(&tempNalu.m_Bitstream);
1758      m_pcEntropyCoder->encodeVPS(m_pcEncTop->getVPS());  // Use to calculate the VPS extension offset
1759#endif
1760      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1761      m_pcEntropyCoder->encodeVPS(m_pcEncTop->getVPS());
1762      writeRBSPTrailingBits(nalu.m_Bitstream);
1763      accessUnit.push_back(new NALUnitEBSP(nalu));
1764      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
1765#if SVC_EXTENSION
1766      }
1767#endif
1768
1769#if SVC_EXTENSION
1770      nalu = NALUnit(NAL_UNIT_SPS, 0, m_layerId);
1771#else
1772      nalu = NALUnit(NAL_UNIT_SPS);
1773#endif
1774      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1775      if (m_bSeqFirst)
1776      {
1777        pcSlice->getSPS()->setNumLongTermRefPicSPS(m_numLongTermRefPicSPS);
1778        for (Int k = 0; k < m_numLongTermRefPicSPS; k++)
1779        {
1780          pcSlice->getSPS()->setLtRefPicPocLsbSps(k, m_ltRefPicPocLsbSps[k]);
1781          pcSlice->getSPS()->setUsedByCurrPicLtSPSFlag(k, m_ltRefPicUsedByCurrPicFlag[k]);
1782        }
1783      }
1784      if( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() )
1785      {
1786        UInt maxCU = m_pcCfg->getSliceArgument() >> ( pcSlice->getSPS()->getMaxCUDepth() << 1);
1787        UInt numDU = ( m_pcCfg->getSliceMode() == 1 ) ? ( pcPic->getNumCUsInFrame() / maxCU ) : ( 0 );
1788        if( pcPic->getNumCUsInFrame() % maxCU != 0 || numDU == 0 )
1789        {
1790          numDU ++;
1791        }
1792        pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->setNumDU( numDU );
1793        pcSlice->getSPS()->setHrdParameters( m_pcCfg->getFrameRate(), numDU, m_pcCfg->getTargetBitrate(), ( m_pcCfg->getIntraPeriod() > 0 ) );
1794      }
1795      if( m_pcCfg->getBufferingPeriodSEIEnabled() || m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() )
1796      {
1797        pcSlice->getSPS()->getVuiParameters()->setHrdParametersPresentFlag( true );
1798      }
1799#if O0092_0094_DEPENDENCY_CONSTRAINT
1800      assert( pcSlice->getSPS()->getLayerId() == 0 || pcSlice->getSPS()->getLayerId() == m_layerId || m_pcEncTop->getVPS()->getRecursiveRefLayerFlag(m_layerId, pcSlice->getSPS()->getLayerId()) );
1801#endif
1802      m_pcEntropyCoder->encodeSPS(pcSlice->getSPS());
1803      writeRBSPTrailingBits(nalu.m_Bitstream);
1804      accessUnit.push_back(new NALUnitEBSP(nalu));
1805      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
1806
1807#if SVC_EXTENSION
1808      nalu = NALUnit(NAL_UNIT_PPS, 0, m_layerId);
1809#else
1810      nalu = NALUnit(NAL_UNIT_PPS);
1811#endif
1812      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1813#if O0092_0094_DEPENDENCY_CONSTRAINT
1814      assert( pcSlice->getPPS()->getPPSId() == 0 || pcSlice->getPPS()->getPPSId() == m_layerId || m_pcEncTop->getVPS()->getRecursiveRefLayerFlag(m_layerId, pcSlice->getPPS()->getPPSId()) );
1815#endif
1816      m_pcEntropyCoder->encodePPS(pcSlice->getPPS());
1817      writeRBSPTrailingBits(nalu.m_Bitstream);
1818      accessUnit.push_back(new NALUnitEBSP(nalu));
1819      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
1820
1821      xCreateLeadingSEIMessages(accessUnit, pcSlice->getSPS());
1822
1823      m_bSeqFirst = false;
1824    }
1825
1826    if (writeSOP) // write SOP description SEI (if enabled) at the beginning of GOP
1827    {
1828      Int SOPcurrPOC = pocCurr;
1829
1830      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
1831      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1832      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1833
1834      SEISOPDescription SOPDescriptionSEI;
1835      SOPDescriptionSEI.m_sopSeqParameterSetId = pcSlice->getSPS()->getSPSId();
1836
1837      UInt i = 0;
1838      UInt prevEntryId = iGOPid;
1839      for (j = iGOPid; j < m_iGopSize; j++)
1840      {
1841        Int deltaPOC = m_pcCfg->getGOPEntry(j).m_POC - m_pcCfg->getGOPEntry(prevEntryId).m_POC;
1842        if ((SOPcurrPOC + deltaPOC) < m_pcCfg->getFramesToBeEncoded())
1843        {
1844          SOPcurrPOC += deltaPOC;
1845          SOPDescriptionSEI.m_sopDescVclNaluType[i] = getNalUnitType(SOPcurrPOC, m_iLastIDR);
1846          SOPDescriptionSEI.m_sopDescTemporalId[i] = m_pcCfg->getGOPEntry(j).m_temporalId;
1847          SOPDescriptionSEI.m_sopDescStRpsIdx[i] = m_pcEncTop->getReferencePictureSetIdxForSOP(pcSlice, SOPcurrPOC, j);
1848          SOPDescriptionSEI.m_sopDescPocDelta[i] = deltaPOC;
1849
1850          prevEntryId = j;
1851          i++;
1852        }
1853      }
1854
1855      SOPDescriptionSEI.m_numPicsInSopMinus1 = i - 1;
1856
1857      m_seiWriter.writeSEImessage( nalu.m_Bitstream, SOPDescriptionSEI, pcSlice->getSPS());
1858      writeRBSPTrailingBits(nalu.m_Bitstream);
1859      accessUnit.push_back(new NALUnitEBSP(nalu));
1860
1861      writeSOP = false;
1862    }
1863
1864    if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
1865        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
1866        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
1867       || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
1868    {
1869      if( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() )
1870      {
1871        UInt numDU = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNumDU();
1872        pictureTimingSEI.m_numDecodingUnitsMinus1     = ( numDU - 1 );
1873        pictureTimingSEI.m_duCommonCpbRemovalDelayFlag = false;
1874
1875        if( pictureTimingSEI.m_numNalusInDuMinus1 == NULL )
1876        {
1877          pictureTimingSEI.m_numNalusInDuMinus1       = new UInt[ numDU ];
1878        }
1879        if( pictureTimingSEI.m_duCpbRemovalDelayMinus1  == NULL )
1880        {
1881          pictureTimingSEI.m_duCpbRemovalDelayMinus1  = new UInt[ numDU ];
1882        }
1883        if( accumBitsDU == NULL )
1884        {
1885          accumBitsDU                                  = new UInt[ numDU ];
1886        }
1887        if( accumNalsDU == NULL )
1888        {
1889          accumNalsDU                                  = new UInt[ numDU ];
1890        }
1891      }
1892      pictureTimingSEI.m_auCpbRemovalDelay = std::min<Int>(std::max<Int>(1, m_totalCoded - m_lastBPSEI), static_cast<Int>(pow(2, static_cast<double>(pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getCpbRemovalDelayLengthMinus1()+1)))); // Syntax element signalled as minus, hence the .
1893#if POC_RESET_FLAG
1894      pictureTimingSEI.m_picDpbOutputDelay = pcSlice->getSPS()->getNumReorderPics(0) + pocCurr - m_totalCoded;
1895#else
1896      pictureTimingSEI.m_picDpbOutputDelay = pcSlice->getSPS()->getNumReorderPics(0) + pcSlice->getPOC() - m_totalCoded;
1897#endif
1898      Int factor = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2;
1899      pictureTimingSEI.m_picDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
1900      if( m_pcCfg->getDecodingUnitInfoSEIEnabled() )
1901      {
1902        picSptDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
1903      }
1904    }
1905
1906    if( ( m_pcCfg->getBufferingPeriodSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) &&
1907        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) && 
1908        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
1909       || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
1910    {
1911      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
1912      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1913      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1914
1915      SEIBufferingPeriod sei_buffering_period;
1916     
1917      UInt uiInitialCpbRemovalDelay = (90000/2);                      // 0.5 sec
1918      sei_buffering_period.m_initialCpbRemovalDelay      [0][0]     = uiInitialCpbRemovalDelay;
1919      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][0]     = uiInitialCpbRemovalDelay;
1920      sei_buffering_period.m_initialCpbRemovalDelay      [0][1]     = uiInitialCpbRemovalDelay;
1921      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][1]     = uiInitialCpbRemovalDelay;
1922
1923      Double dTmp = (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getNumUnitsInTick() / (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getTimeScale();
1924
1925      UInt uiTmp = (UInt)( dTmp * 90000.0 ); 
1926      uiInitialCpbRemovalDelay -= uiTmp;
1927      uiInitialCpbRemovalDelay -= uiTmp / ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2 );
1928      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][0]  = uiInitialCpbRemovalDelay;
1929      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][0]  = uiInitialCpbRemovalDelay;
1930      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][1]  = uiInitialCpbRemovalDelay;
1931      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][1]  = uiInitialCpbRemovalDelay;
1932
1933      sei_buffering_period.m_rapCpbParamsPresentFlag              = 0;
1934      //for the concatenation, it can be set to one during splicing.
1935      sei_buffering_period.m_concatenationFlag = 0;
1936      //since the temporal layer HRD is not ready, we assumed it is fixed
1937      sei_buffering_period.m_auCpbRemovalDelayDelta = 1;
1938      sei_buffering_period.m_cpbDelayOffset = 0;
1939      sei_buffering_period.m_dpbDelayOffset = 0;
1940
1941      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_buffering_period, pcSlice->getSPS());
1942      writeRBSPTrailingBits(nalu.m_Bitstream);
1943      {
1944      UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
1945      UInt offsetPosition = m_activeParameterSetSEIPresentInAU;   // Insert BP SEI after APS SEI
1946      AccessUnit::iterator it;
1947      for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
1948      {
1949        it++;
1950      }
1951      accessUnit.insert(it, new NALUnitEBSP(nalu));
1952      m_bufferingPeriodSEIPresentInAU = true;
1953      }
1954
1955      if (m_pcCfg->getScalableNestingSEIEnabled())
1956      {
1957        OutputNALUnit naluTmp(NAL_UNIT_PREFIX_SEI);
1958        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1959        m_pcEntropyCoder->setBitstream(&naluTmp.m_Bitstream);
1960        scalableNestingSEI.m_nestedSEIs.clear();
1961        scalableNestingSEI.m_nestedSEIs.push_back(&sei_buffering_period);
1962        m_seiWriter.writeSEImessage( naluTmp.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
1963        writeRBSPTrailingBits(naluTmp.m_Bitstream);
1964        UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
1965        UInt offsetPosition = m_activeParameterSetSEIPresentInAU + m_bufferingPeriodSEIPresentInAU + m_pictureTimingSEIPresentInAU;   // Insert BP SEI after non-nested APS, BP and PT SEIs
1966        AccessUnit::iterator it;
1967        for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
1968        {
1969          it++;
1970        }
1971        accessUnit.insert(it, new NALUnitEBSP(naluTmp));
1972        m_nestedBufferingPeriodSEIPresentInAU = true;
1973      }
1974
1975      m_lastBPSEI = m_totalCoded;
1976      m_cpbRemovalDelay = 0;
1977    }
1978    m_cpbRemovalDelay ++;
1979    if( ( m_pcEncTop->getRecoveryPointSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) )
1980    {
1981      if( m_pcEncTop->getGradualDecodingRefreshInfoEnabled() && !pcSlice->getRapPicFlag() )
1982      {
1983        // Gradual decoding refresh SEI
1984        OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
1985        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1986        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1987
1988        SEIGradualDecodingRefreshInfo seiGradualDecodingRefreshInfo;
1989        seiGradualDecodingRefreshInfo.m_gdrForegroundFlag = true; // Indicating all "foreground"
1990
1991        m_seiWriter.writeSEImessage( nalu.m_Bitstream, seiGradualDecodingRefreshInfo, pcSlice->getSPS() );
1992        writeRBSPTrailingBits(nalu.m_Bitstream);
1993        accessUnit.push_back(new NALUnitEBSP(nalu));
1994      }
1995    // Recovery point SEI
1996      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
1997      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1998      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1999
2000      SEIRecoveryPoint sei_recovery_point;
2001      sei_recovery_point.m_recoveryPocCnt    = 0;
2002#if POC_RESET_FLAG
2003      sei_recovery_point.m_exactMatchingFlag = ( pocCurr == 0 ) ? (true) : (false);
2004#else
2005      sei_recovery_point.m_exactMatchingFlag = ( pcSlice->getPOC() == 0 ) ? (true) : (false);
2006#endif
2007      sei_recovery_point.m_brokenLinkFlag    = false;
2008
2009      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_recovery_point, pcSlice->getSPS() );
2010      writeRBSPTrailingBits(nalu.m_Bitstream);
2011      accessUnit.push_back(new NALUnitEBSP(nalu));
2012    }
2013
2014    /* use the main bitstream buffer for storing the marshalled picture */
2015    m_pcEntropyCoder->setBitstream(NULL);
2016
2017    startCUAddrSliceIdx = 0;
2018    startCUAddrSlice    = 0; 
2019
2020    startCUAddrSliceSegmentIdx = 0;
2021    startCUAddrSliceSegment    = 0; 
2022    nextCUAddr                 = 0;
2023    pcSlice = pcPic->getSlice(startCUAddrSliceIdx);
2024
2025    Int processingState = (pcSlice->getSPS()->getUseSAO())?(EXECUTE_INLOOPFILTER):(ENCODE_SLICE);
2026    Bool skippedSlice=false;
2027    while (nextCUAddr < uiRealEndAddress) // Iterate over all slices
2028    {
2029      switch(processingState)
2030      {
2031      case ENCODE_SLICE:
2032        {
2033          pcSlice->setNextSlice       ( false );
2034          pcSlice->setNextSliceSegment( false );
2035          if (nextCUAddr == m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx])
2036          {
2037            pcSlice = pcPic->getSlice(startCUAddrSliceIdx);
2038            if(startCUAddrSliceIdx > 0 && pcSlice->getSliceType()!= I_SLICE)
2039            {
2040              pcSlice->checkColRefIdx(startCUAddrSliceIdx, pcPic);
2041            }
2042            pcPic->setCurrSliceIdx(startCUAddrSliceIdx);
2043            m_pcSliceEncoder->setSliceIdx(startCUAddrSliceIdx);
2044            assert(startCUAddrSliceIdx == pcSlice->getSliceIdx());
2045            // Reconstruction slice
2046            pcSlice->setSliceCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
2047            pcSlice->setSliceCurEndCUAddr  ( m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx+1 ] );
2048            // Dependent slice
2049            pcSlice->setSliceSegmentCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
2050            pcSlice->setSliceSegmentCurEndCUAddr  ( m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx+1 ] );
2051
2052            pcSlice->setNextSlice       ( true );
2053
2054            startCUAddrSliceIdx++;
2055            startCUAddrSliceSegmentIdx++;
2056          } 
2057          else if (nextCUAddr == m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx])
2058          {
2059            // Dependent slice
2060            pcSlice->setSliceSegmentCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
2061            pcSlice->setSliceSegmentCurEndCUAddr  ( m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx+1 ] );
2062
2063            pcSlice->setNextSliceSegment( true );
2064
2065            startCUAddrSliceSegmentIdx++;
2066          }
2067#if SVC_EXTENSION && M0457_COL_PICTURE_SIGNALING
2068          pcSlice->setNumMotionPredRefLayers(m_pcEncTop->getNumMotionPredRefLayers());
2069#endif
2070          pcSlice->setRPS(pcPic->getSlice(0)->getRPS());
2071          pcSlice->setRPSidx(pcPic->getSlice(0)->getRPSidx());
2072          UInt uiDummyStartCUAddr;
2073          UInt uiDummyBoundingCUAddr;
2074          m_pcSliceEncoder->xDetermineStartAndBoundingCUAddr(uiDummyStartCUAddr,uiDummyBoundingCUAddr,pcPic,true);
2075
2076          uiInternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) % pcPic->getNumPartInCU();
2077          uiExternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) / pcPic->getNumPartInCU();
2078          uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
2079          uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
2080
2081#if REPN_FORMAT_IN_VPS
2082          uiWidth = pcSlice->getPicWidthInLumaSamples();
2083          uiHeight = pcSlice->getPicHeightInLumaSamples();
2084#else
2085          uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
2086          uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
2087#endif
2088          while(uiPosX>=uiWidth||uiPosY>=uiHeight)
2089          {
2090            uiInternalAddress--;
2091            uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
2092            uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
2093          }
2094          uiInternalAddress++;
2095          if(uiInternalAddress==pcPic->getNumPartInCU())
2096          {
2097            uiInternalAddress = 0;
2098            uiExternalAddress = pcPic->getPicSym()->getCUOrderMap(pcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
2099          }
2100          UInt endAddress = pcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress);
2101          if(endAddress<=pcSlice->getSliceSegmentCurStartCUAddr()) 
2102          {
2103            UInt boundingAddrSlice, boundingAddrSliceSegment;
2104            boundingAddrSlice          = m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx];         
2105            boundingAddrSliceSegment = m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx];         
2106            nextCUAddr               = min(boundingAddrSlice, boundingAddrSliceSegment);
2107            if(pcSlice->isNextSlice())
2108            {
2109              skippedSlice=true;
2110            }
2111            continue;
2112          }
2113          if(skippedSlice) 
2114          {
2115            pcSlice->setNextSlice       ( true );
2116            pcSlice->setNextSliceSegment( false );
2117          }
2118          skippedSlice=false;
2119          pcSlice->allocSubstreamSizes( iNumSubstreams );
2120          for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
2121          {
2122            pcSubstreamsOut[ui].clear();
2123          }
2124
2125          m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
2126          m_pcEntropyCoder->resetEntropy      ();
2127          /* start slice NALunit */
2128#if SVC_EXTENSION
2129          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer(), m_layerId );
2130#else
2131          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer() );
2132#endif
2133          Bool sliceSegment = (!pcSlice->isNextSlice());
2134          if (!sliceSegment)
2135          {
2136            uiOneBitstreamPerSliceLength = 0; // start of a new slice
2137          }
2138          m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
2139          tmpBitsBeforeWriting = m_pcEntropyCoder->getNumberOfWrittenBits();
2140          m_pcEntropyCoder->encodeSliceHeader(pcSlice);
2141          actualHeadBits += ( m_pcEntropyCoder->getNumberOfWrittenBits() - tmpBitsBeforeWriting );
2142
2143          // is it needed?
2144          {
2145            if (!sliceSegment)
2146            {
2147              pcBitstreamRedirect->writeAlignOne();
2148            }
2149            else
2150            {
2151              // We've not completed our slice header info yet, do the alignment later.
2152            }
2153            m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
2154            m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
2155            m_pcEntropyCoder->resetEntropy    ();
2156            for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams() ; ui++ )
2157            {
2158              m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[ui], pcSlice );
2159              m_pcEntropyCoder->resetEntropy    ();
2160            }
2161          }
2162
2163          if(pcSlice->isNextSlice())
2164          {
2165            // set entropy coder for writing
2166            m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
2167            {
2168              for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams() ; ui++ )
2169              {
2170                m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[ui], pcSlice );
2171                m_pcEntropyCoder->resetEntropy    ();
2172              }
2173              pcSbacCoders[0].load(m_pcSbacCoder);
2174              m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[0], pcSlice );  //ALF is written in substream #0 with CABAC coder #0 (see ALF param encoding below)
2175            }
2176            m_pcEntropyCoder->resetEntropy    ();
2177            // File writing
2178            if (!sliceSegment)
2179            {
2180              m_pcEntropyCoder->setBitstream(pcBitstreamRedirect);
2181            }
2182            else
2183            {
2184              m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
2185            }
2186            // for now, override the TILES_DECODER setting in order to write substreams.
2187            m_pcEntropyCoder->setBitstream    ( &pcSubstreamsOut[0] );
2188
2189          }
2190          pcSlice->setFinalized(true);
2191
2192          m_pcSbacCoder->load( &pcSbacCoders[0] );
2193
2194          pcSlice->setTileOffstForMultES( uiOneBitstreamPerSliceLength );
2195            pcSlice->setTileLocationCount ( 0 );
2196          m_pcSliceEncoder->encodeSlice(pcPic, pcSubstreamsOut);
2197
2198          {
2199            // Construct the final bitstream by flushing and concatenating substreams.
2200            // The final bitstream is either nalu.m_Bitstream or pcBitstreamRedirect;
2201            UInt* puiSubstreamSizes = pcSlice->getSubstreamSizes();
2202            UInt uiTotalCodedSize = 0; // for padding calcs.
2203            UInt uiNumSubstreamsPerTile = iNumSubstreams;
2204            if (iNumSubstreams > 1)
2205            {
2206              uiNumSubstreamsPerTile /= pcPic->getPicSym()->getNumTiles();
2207            }
2208            for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
2209            {
2210              // Flush all substreams -- this includes empty ones.
2211              // Terminating bit and flush.
2212              m_pcEntropyCoder->setEntropyCoder   ( &pcSbacCoders[ui], pcSlice );
2213              m_pcEntropyCoder->setBitstream      (  &pcSubstreamsOut[ui] );
2214              m_pcEntropyCoder->encodeTerminatingBit( 1 );
2215              m_pcEntropyCoder->encodeSliceFinish();
2216
2217              pcSubstreamsOut[ui].writeByteAlignment();   // Byte-alignment in slice_data() at end of sub-stream
2218              // Byte alignment is necessary between tiles when tiles are independent.
2219              uiTotalCodedSize += pcSubstreamsOut[ui].getNumberOfWrittenBits();
2220
2221              Bool bNextSubstreamInNewTile = ((ui+1) < iNumSubstreams)&& ((ui+1)%uiNumSubstreamsPerTile == 0);
2222              if (bNextSubstreamInNewTile)
2223              {
2224                pcSlice->setTileLocation(ui/uiNumSubstreamsPerTile, pcSlice->getTileOffstForMultES()+(uiTotalCodedSize>>3));
2225              }
2226              if (ui+1 < pcSlice->getPPS()->getNumSubstreams())
2227              {
2228                puiSubstreamSizes[ui] = pcSubstreamsOut[ui].getNumberOfWrittenBits() + (pcSubstreamsOut[ui].countStartCodeEmulations()<<3);
2229              }
2230            }
2231
2232            // Complete the slice header info.
2233            m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
2234            m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
2235            m_pcEntropyCoder->encodeTilesWPPEntryPoint( pcSlice );
2236
2237            // Substreams...
2238            TComOutputBitstream *pcOut = pcBitstreamRedirect;
2239          Int offs = 0;
2240          Int nss = pcSlice->getPPS()->getNumSubstreams();
2241          if (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
2242          {
2243            // 1st line present for WPP.
2244            offs = pcSlice->getSliceSegmentCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU()/pcSlice->getPic()->getFrameWidthInCU();
2245            nss  = pcSlice->getNumEntryPointOffsets()+1;
2246          }
2247          for ( UInt ui = 0 ; ui < nss; ui++ )
2248          {
2249            pcOut->addSubstream(&pcSubstreamsOut[ui+offs]);
2250            }
2251          }
2252
2253          UInt boundingAddrSlice, boundingAddrSliceSegment;
2254          boundingAddrSlice        = m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx];         
2255          boundingAddrSliceSegment = m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx];         
2256          nextCUAddr               = min(boundingAddrSlice, boundingAddrSliceSegment);
2257          // If current NALU is the first NALU of slice (containing slice header) and more NALUs exist (due to multiple dependent slices) then buffer it.
2258          // 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.
2259          Bool bNALUAlignedWrittenToList    = false; // used to ensure current NALU is not written more than once to the NALU list.
2260          xAttachSliceDataToNalUnit(nalu, pcBitstreamRedirect);
2261          accessUnit.push_back(new NALUnitEBSP(nalu));
2262          actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
2263          bNALUAlignedWrittenToList = true; 
2264          uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits(); // length of bitstream after byte-alignment
2265
2266          if (!bNALUAlignedWrittenToList)
2267          {
2268            {
2269              nalu.m_Bitstream.writeAlignZero();
2270            }
2271            accessUnit.push_back(new NALUnitEBSP(nalu));
2272            uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits() + 24; // length of bitstream after byte-alignment + 3 byte startcode 0x000001
2273          }
2274
2275          if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
2276              ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
2277              ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
2278             || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) &&
2279              ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() ) )
2280          {
2281              UInt numNalus = 0;
2282            UInt numRBSPBytes = 0;
2283            for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
2284            {
2285              UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
2286              if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
2287              {
2288                numRBSPBytes += numRBSPBytes_nal;
2289                numNalus ++;
2290              }
2291            }
2292            accumBitsDU[ pcSlice->getSliceIdx() ] = ( numRBSPBytes << 3 );
2293            accumNalsDU[ pcSlice->getSliceIdx() ] = numNalus;   // SEI not counted for bit count; hence shouldn't be counted for # of NALUs - only for consistency
2294          }
2295          processingState = ENCODE_SLICE;
2296          }
2297          break;
2298        case EXECUTE_INLOOPFILTER:
2299          {
2300            // set entropy coder for RD
2301            m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
2302#if HIGHER_LAYER_IRAP_SKIP_FLAG
2303            if ( pcSlice->getSPS()->getUseSAO() && !( m_pcEncTop->getSkipPictureAtArcSwitch() && m_pcEncTop->getAdaptiveResolutionChange() > 0 && pcSlice->getLayerId() == 1 && pcSlice->getPOC() == m_pcEncTop->getAdaptiveResolutionChange()) )
2304#else
2305            if ( pcSlice->getSPS()->getUseSAO() )
2306#endif
2307            {
2308              m_pcEntropyCoder->resetEntropy();
2309              m_pcEntropyCoder->setBitstream( m_pcBitCounter );
2310#if HM_CLEANUP_SAO
2311              Bool sliceEnabled[NUM_SAO_COMPONENTS];
2312              m_pcSAO->initRDOCabacCoder(m_pcEncTop->getRDGoOnSbacCoder(), pcSlice);
2313              m_pcSAO->SAOProcess(pcPic
2314                , sliceEnabled
2315                , pcPic->getSlice(0)->getLambdas()
2316#if SAO_ENCODE_ALLOW_USE_PREDEBLOCK
2317                , m_pcCfg->getSaoLcuBoundary()
2318#endif
2319              );
2320              m_pcSAO->PCMLFDisableProcess(pcPic);   
2321
2322              //assign SAO slice header
2323              for(Int s=0; s< uiNumSlices; s++)
2324              {
2325                pcPic->getSlice(s)->setSaoEnabledFlag(sliceEnabled[SAO_Y]);
2326                assert(sliceEnabled[SAO_Cb] == sliceEnabled[SAO_Cr]);
2327                pcPic->getSlice(s)->setSaoEnabledFlagChroma(sliceEnabled[SAO_Cb]);
2328              }
2329#else
2330              m_pcSAO->startSaoEnc(pcPic, m_pcEntropyCoder, m_pcEncTop->getRDSbacCoder(), m_pcEncTop->getRDGoOnSbacCoder());
2331              SAOParam& cSaoParam = *pcSlice->getPic()->getPicSym()->getSaoParam();
2332
2333#if SAO_ENCODING_CHOICE
2334              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma(), pcPic->getSlice(0)->getDepth());
2335#else
2336              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma());
2337#endif
2338              m_pcSAO->endSaoEnc();
2339              m_pcSAO->PCMLFDisableProcess(pcPic);
2340#endif
2341            }
2342#if !HM_CLEANUP_SAO         
2343#if SAO_RDO
2344            m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
2345#endif
2346#endif
2347            processingState = ENCODE_SLICE;
2348#if !HM_CLEANUP_SAO
2349#if HIGHER_LAYER_IRAP_SKIP_FLAG
2350            if ( ( m_pcEncTop->getSkipPictureAtArcSwitch() && m_pcEncTop->getAdaptiveResolutionChange() > 0 && pcSlice->getLayerId() == 1 && pcSlice->getPOC() == m_pcEncTop->getAdaptiveResolutionChange()) )
2351            {
2352              pcSlice->getPic()->getPicSym()->getSaoParam()->bSaoFlag[0]=0;
2353              pcSlice->getPic()->getPicSym()->getSaoParam()->bSaoFlag[1]=0;
2354            }
2355#endif
2356            for(Int s=0; s< uiNumSlices; s++)
2357            {
2358              if (pcSlice->getSPS()->getUseSAO())
2359              {
2360                pcPic->getSlice(s)->setSaoEnabledFlag((pcSlice->getPic()->getPicSym()->getSaoParam()->bSaoFlag[0]==1)?true:false);
2361              }
2362            }
2363#endif
2364          }
2365          break;
2366        default:
2367          {
2368            printf("Not a supported encoding state\n");
2369            assert(0);
2370            exit(-1);
2371          }
2372        }
2373      } // end iteration over slices
2374#if !HM_CLEANUP_SAO   
2375      if(pcSlice->getSPS()->getUseSAO())
2376      {
2377        if(pcSlice->getSPS()->getUseSAO())
2378        {
2379          m_pcSAO->destroyPicSaoInfo();
2380        }
2381        pcPic->destroyNonDBFilterInfo();
2382      }
2383#endif
2384      pcPic->compressMotion(); 
2385     
2386      //-- For time output for each slice
2387      Double dEncTime = (Double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
2388
2389      const Char* digestStr = NULL;
2390      if (m_pcCfg->getDecodedPictureHashSEIEnabled())
2391      {
2392        /* calculate MD5sum for entire reconstructed picture */
2393        SEIDecodedPictureHash sei_recon_picture_digest;
2394        if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
2395        {
2396          sei_recon_picture_digest.method = SEIDecodedPictureHash::MD5;
2397          calcMD5(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
2398          digestStr = digestToString(sei_recon_picture_digest.digest, 16);
2399        }
2400        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
2401        {
2402          sei_recon_picture_digest.method = SEIDecodedPictureHash::CRC;
2403          calcCRC(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
2404          digestStr = digestToString(sei_recon_picture_digest.digest, 2);
2405        }
2406        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
2407        {
2408          sei_recon_picture_digest.method = SEIDecodedPictureHash::CHECKSUM;
2409          calcChecksum(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
2410          digestStr = digestToString(sei_recon_picture_digest.digest, 4);
2411        }
2412#if SVC_EXTENSION
2413        OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer(), m_layerId);
2414#else
2415        OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer());
2416#endif
2417
2418        /* write the SEI messages */
2419        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
2420        m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_recon_picture_digest, pcSlice->getSPS());
2421        writeRBSPTrailingBits(nalu.m_Bitstream);
2422
2423        accessUnit.insert(accessUnit.end(), new NALUnitEBSP(nalu));
2424      }
2425      if (m_pcCfg->getTemporalLevel0IndexSEIEnabled())
2426      {
2427        SEITemporalLevel0Index sei_temporal_level0_index;
2428        if (pcSlice->getRapPicFlag())
2429        {
2430          m_tl0Idx = 0;
2431          m_rapIdx = (m_rapIdx + 1) & 0xFF;
2432        }
2433        else
2434        {
2435          m_tl0Idx = (m_tl0Idx + (pcSlice->getTLayer() ? 0 : 1)) & 0xFF;
2436        }
2437        sei_temporal_level0_index.tl0Idx = m_tl0Idx;
2438        sei_temporal_level0_index.rapIdx = m_rapIdx;
2439
2440        OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI); 
2441
2442        /* write the SEI messages */
2443        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
2444        m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_temporal_level0_index, pcSlice->getSPS());
2445        writeRBSPTrailingBits(nalu.m_Bitstream);
2446
2447        /* insert the SEI message NALUnit before any Slice NALUnits */
2448        AccessUnit::iterator it = find_if(accessUnit.begin(), accessUnit.end(), mem_fun(&NALUnit::isSlice));
2449        accessUnit.insert(it, new NALUnitEBSP(nalu));
2450      }
2451
2452      xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime );
2453
2454      //In case of field coding, compute the interlaced PSNR for both fields
2455      if (isField && ((!pcPic->isTopField() && isTff) || (pcPic->isTopField() && !isTff)))
2456      {
2457        //get complementary top field
2458        TComPic* pcPicTop;
2459        TComList<TComPic*>::iterator   iterPic = rcListPic.begin();
2460        while ((*iterPic)->getPOC() != pcPic->getPOC()-1)
2461        {
2462          iterPic ++;
2463        }
2464        pcPicTop = *(iterPic);
2465        xCalculateInterlacedAddPSNR(pcPicTop, pcPic, pcPicTop->getPicYuvRec(), pcPic->getPicYuvRec(), accessUnit, dEncTime );
2466      }
2467
2468      if (digestStr)
2469      {
2470        if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
2471        {
2472          printf(" [MD5:%s]", digestStr);
2473        }
2474        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
2475        {
2476          printf(" [CRC:%s]", digestStr);
2477        }
2478        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
2479        {
2480          printf(" [Checksum:%s]", digestStr);
2481        }
2482      }
2483      if ( m_pcCfg->getUseRateCtrl() )
2484      {
2485        Double avgQP     = m_pcRateCtrl->getRCPic()->calAverageQP();
2486        Double avgLambda = m_pcRateCtrl->getRCPic()->calAverageLambda();
2487        if ( avgLambda < 0.0 )
2488        {
2489          avgLambda = lambda;
2490        }
2491        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, pcSlice->getSliceType());
2492        m_pcRateCtrl->getRCPic()->addToPictureLsit( m_pcRateCtrl->getPicList() );
2493
2494        m_pcRateCtrl->getRCSeq()->updateAfterPic( actualTotalBits );
2495        if ( pcSlice->getSliceType() != I_SLICE )
2496        {
2497          m_pcRateCtrl->getRCGOP()->updateAfterPicture( actualTotalBits );
2498        }
2499        else    // for intra picture, the estimated bits are used to update the current status in the GOP
2500        {
2501          m_pcRateCtrl->getRCGOP()->updateAfterPicture( estimatedBits );
2502        }
2503      }
2504
2505      if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
2506          ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
2507          ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
2508         || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
2509      {
2510        TComVUI *vui = pcSlice->getSPS()->getVuiParameters();
2511        TComHRD *hrd = vui->getHrdParameters();
2512
2513        if( hrd->getSubPicCpbParamsPresentFlag() )
2514        {
2515          Int i;
2516          UInt64 ui64Tmp;
2517          UInt uiPrev = 0;
2518          UInt numDU = ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 );
2519          UInt *pCRD = &pictureTimingSEI.m_duCpbRemovalDelayMinus1[0];
2520          UInt maxDiff = ( hrd->getTickDivisorMinus2() + 2 ) - 1;
2521
2522          for( i = 0; i < numDU; i ++ )
2523          {
2524            pictureTimingSEI.m_numNalusInDuMinus1[ i ]       = ( i == 0 ) ? ( accumNalsDU[ i ] - 1 ) : ( accumNalsDU[ i ] - accumNalsDU[ i - 1] - 1 );
2525          }
2526
2527          if( numDU == 1 )
2528          {
2529            pCRD[ 0 ] = 0; /* don't care */
2530          }
2531          else
2532          {
2533            pCRD[ numDU - 1 ] = 0;/* by definition */
2534            UInt tmp = 0;
2535            UInt accum = 0;
2536
2537            for( i = ( numDU - 2 ); i >= 0; i -- )
2538            {
2539              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
2540              if( (UInt)ui64Tmp > maxDiff )
2541              {
2542                tmp ++;
2543              }
2544            }
2545            uiPrev = 0;
2546
2547            UInt flag = 0;
2548            for( i = ( numDU - 2 ); i >= 0; i -- )
2549            {
2550              flag = 0;
2551              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
2552
2553              if( (UInt)ui64Tmp > maxDiff )
2554              {
2555                if(uiPrev >= maxDiff - tmp)
2556                {
2557                  ui64Tmp = uiPrev + 1;
2558                  flag = 1;
2559                }
2560                else                            ui64Tmp = maxDiff - tmp + 1;
2561              }
2562              pCRD[ i ] = (UInt)ui64Tmp - uiPrev - 1;
2563              if( (Int)pCRD[ i ] < 0 )
2564              {
2565                pCRD[ i ] = 0;
2566              }
2567              else if (tmp > 0 && flag == 1) 
2568              {
2569                tmp --;
2570              }
2571              accum += pCRD[ i ] + 1;
2572              uiPrev = accum;
2573            }
2574          }
2575        }
2576        if( m_pcCfg->getPictureTimingSEIEnabled() )
2577        {
2578          {
2579            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
2580          m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
2581          pictureTimingSEI.m_picStruct = (isField && pcSlice->getPic()->isTopField())? 1 : isField? 2 : 0;
2582          m_seiWriter.writeSEImessage(nalu.m_Bitstream, pictureTimingSEI, pcSlice->getSPS());
2583          writeRBSPTrailingBits(nalu.m_Bitstream);
2584          UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
2585          UInt offsetPosition = m_activeParameterSetSEIPresentInAU
2586                                    + m_bufferingPeriodSEIPresentInAU;    // Insert PT SEI after APS and BP SEI
2587          AccessUnit::iterator it;
2588          for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
2589          {
2590            it++;
2591          }
2592          accessUnit.insert(it, new NALUnitEBSP(nalu));
2593          m_pictureTimingSEIPresentInAU = true;
2594        }
2595          if ( m_pcCfg->getScalableNestingSEIEnabled() ) // put picture timing SEI into scalable nesting SEI
2596          {
2597            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
2598            m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
2599            scalableNestingSEI.m_nestedSEIs.clear();
2600            scalableNestingSEI.m_nestedSEIs.push_back(&pictureTimingSEI);
2601            m_seiWriter.writeSEImessage(nalu.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
2602            writeRBSPTrailingBits(nalu.m_Bitstream);
2603            UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
2604            UInt offsetPosition = m_activeParameterSetSEIPresentInAU
2605              + m_bufferingPeriodSEIPresentInAU + m_pictureTimingSEIPresentInAU + m_nestedBufferingPeriodSEIPresentInAU;    // Insert PT SEI after APS and BP SEI
2606            AccessUnit::iterator it;
2607            for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
2608            {
2609              it++;
2610            }
2611            accessUnit.insert(it, new NALUnitEBSP(nalu));
2612            m_nestedPictureTimingSEIPresentInAU = true;
2613          }
2614        }
2615        if( m_pcCfg->getDecodingUnitInfoSEIEnabled() && hrd->getSubPicCpbParamsPresentFlag() )
2616        {             
2617          m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
2618          for( Int i = 0; i < ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 ); i ++ )
2619          {
2620            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
2621
2622            SEIDecodingUnitInfo tempSEI;
2623            tempSEI.m_decodingUnitIdx = i;
2624            tempSEI.m_duSptCpbRemovalDelay = pictureTimingSEI.m_duCpbRemovalDelayMinus1[i] + 1;
2625            tempSEI.m_dpbOutputDuDelayPresentFlag = false;
2626            tempSEI.m_picSptDpbOutputDuDelay = picSptDpbOutputDuDelay;
2627
2628            AccessUnit::iterator it;
2629            // Insert the first one in the right location, before the first slice
2630            if(i == 0)
2631            {
2632              // Insert before the first slice.
2633              m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, pcSlice->getSPS());
2634              writeRBSPTrailingBits(nalu.m_Bitstream);
2635
2636              UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
2637              UInt offsetPosition = m_activeParameterSetSEIPresentInAU
2638                                    + m_bufferingPeriodSEIPresentInAU
2639                                    + m_pictureTimingSEIPresentInAU;  // Insert DU info SEI after APS, BP and PT SEI
2640              for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
2641              {
2642                it++;
2643              }
2644              accessUnit.insert(it, new NALUnitEBSP(nalu));
2645            }
2646            else
2647            {
2648              Int ctr;
2649              // For the second decoding unit onwards we know how many NALUs are present
2650              for (ctr = 0, it = accessUnit.begin(); it != accessUnit.end(); it++)
2651              {           
2652                if(ctr == accumNalsDU[ i - 1 ])
2653                {
2654                  // Insert before the first slice.
2655                  m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, pcSlice->getSPS());
2656                  writeRBSPTrailingBits(nalu.m_Bitstream);
2657
2658                  accessUnit.insert(it, new NALUnitEBSP(nalu));
2659                  break;
2660                }
2661                if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
2662                {
2663                  ctr++;
2664                }
2665              }
2666            }           
2667          }
2668        }
2669      }
2670      xResetNonNestedSEIPresentFlags();
2671      xResetNestedSEIPresentFlags();
2672      pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
2673
2674#if M0040_ADAPTIVE_RESOLUTION_CHANGE
2675      pcPicYuvRecOut->setReconstructed(true);
2676#endif
2677
2678      pcPic->setReconMark   ( true );
2679      m_bFirst = false;
2680      m_iNumPicCoded++;
2681      m_totalCoded ++;
2682      /* logging: insert a newline at end of picture period */
2683      printf("\n");
2684      fflush(stdout);
2685
2686      delete[] pcSubstreamsOut;
2687  }
2688  delete pcBitstreamRedirect;
2689
2690  if( accumBitsDU != NULL) delete accumBitsDU;
2691  if( accumNalsDU != NULL) delete accumNalsDU;
2692
2693#if SVC_EXTENSION
2694  assert ( m_iNumPicCoded <= 1 || (isField && iPOCLast == 1) );
2695#else
2696  assert ( (m_iNumPicCoded == iNumPicRcvd) || (isField && iPOCLast == 1) );
2697#endif
2698}
2699
2700#if !SVC_EXTENSION
2701Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded, Bool isField)
2702{
2703  assert (uiNumAllPicCoded == m_gcAnalyzeAll.getNumPic());
2704 
2705   
2706  //--CFG_KDY
2707  if(isField)
2708  {
2709    m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() * 2);
2710    m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() * 2);
2711    m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() * 2);
2712    m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() * 2);
2713  }
2714   else
2715  {
2716    m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() );
2717    m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() );
2718    m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() );
2719    m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() );
2720  }
2721 
2722  //-- all
2723  printf( "\n\nSUMMARY --------------------------------------------------------\n" );
2724  m_gcAnalyzeAll.printOut('a');
2725 
2726  printf( "\n\nI Slices--------------------------------------------------------\n" );
2727  m_gcAnalyzeI.printOut('i');
2728 
2729  printf( "\n\nP Slices--------------------------------------------------------\n" );
2730  m_gcAnalyzeP.printOut('p');
2731 
2732  printf( "\n\nB Slices--------------------------------------------------------\n" );
2733  m_gcAnalyzeB.printOut('b');
2734 
2735#if _SUMMARY_OUT_
2736  m_gcAnalyzeAll.printSummaryOut();
2737#endif
2738#if _SUMMARY_PIC_
2739  m_gcAnalyzeI.printSummary('I');
2740  m_gcAnalyzeP.printSummary('P');
2741  m_gcAnalyzeB.printSummary('B');
2742#endif
2743
2744  if(isField)
2745  {
2746    //-- interlaced summary
2747    m_gcAnalyzeAll_in.setFrmRate( m_pcCfg->getFrameRate());
2748    printf( "\n\nSUMMARY INTERLACED ---------------------------------------------\n" );
2749    m_gcAnalyzeAll_in.printOutInterlaced('a',  m_gcAnalyzeAll.getBits());
2750   
2751#if _SUMMARY_OUT_
2752    m_gcAnalyzeAll_in.printSummaryOutInterlaced();
2753#endif
2754  }
2755
2756  printf("\nRVM: %.3lf\n" , xCalculateRVM());
2757}
2758#endif
2759
2760Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits )
2761{
2762  TComSlice* pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
2763  Bool bCalcDist = false;
2764  m_pcLoopFilter->setCfg(m_pcCfg->getLFCrossTileBoundaryFlag());
2765  m_pcLoopFilter->loopFilterPic( pcPic );
2766 
2767  m_pcEntropyCoder->setEntropyCoder ( m_pcEncTop->getRDGoOnSbacCoder(), pcSlice );
2768  m_pcEntropyCoder->resetEntropy    ();
2769  m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
2770#if !HM_CLEANUP_SAO
2771  pcSlice = pcPic->getSlice(0);
2772  if(pcSlice->getSPS()->getUseSAO())
2773  {
2774    std::vector<Bool> LFCrossSliceBoundaryFlag(1, true);
2775    std::vector<Int>  sliceStartAddress;
2776    sliceStartAddress.push_back(0);
2777    sliceStartAddress.push_back(pcPic->getNumCUsInFrame()* pcPic->getNumPartInCU());
2778    pcPic->createNonDBFilterInfo(sliceStartAddress, 0, &LFCrossSliceBoundaryFlag);
2779  }
2780 
2781  if( pcSlice->getSPS()->getUseSAO())
2782  {
2783    pcPic->destroyNonDBFilterInfo();
2784  }
2785#endif
2786  m_pcEntropyCoder->resetEntropy    ();
2787  ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
2788 
2789  if (!bCalcDist)
2790    ruiDist = xFindDistortionFrame(pcPic->getPicYuvOrg(), pcPic->getPicYuvRec());
2791}
2792
2793// ====================================================================================================================
2794// Protected member functions
2795// ====================================================================================================================
2796
2797
2798Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Bool isField )
2799{
2800  assert( iNumPicRcvd > 0 );
2801  //  Exception for the first frames
2802  if ( ( isField && (iPOCLast == 0 || iPOCLast == 1) ) || (!isField  && (iPOCLast == 0))  )
2803  {
2804    m_iGopSize    = 1;
2805  }
2806  else
2807  {
2808    m_iGopSize    = m_pcCfg->getGOPSize();
2809  }
2810  assert (m_iGopSize > 0);
2811 
2812  return;
2813}
2814
2815Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut )
2816{
2817  assert( iNumPicRcvd > 0 );
2818  //  Exception for the first frame
2819  if ( iPOCLast == 0 )
2820  {
2821    m_iGopSize    = 1;
2822  }
2823  else
2824    m_iGopSize    = m_pcCfg->getGOPSize();
2825 
2826  assert (m_iGopSize > 0); 
2827
2828  return;
2829}
2830
2831Void TEncGOP::xGetBuffer( TComList<TComPic*>&      rcListPic,
2832                         TComList<TComPicYuv*>&    rcListPicYuvRecOut,
2833                         Int                       iNumPicRcvd,
2834                         Int                       iTimeOffset,
2835                         TComPic*&                 rpcPic,
2836                         TComPicYuv*&              rpcPicYuvRecOut,
2837                         Int                       pocCurr,
2838                         Bool                      isField)
2839{
2840  Int i;
2841  //  Rec. output
2842  TComList<TComPicYuv*>::iterator     iterPicYuvRec = rcListPicYuvRecOut.end();
2843
2844  if (isField)
2845  {
2846    for ( i = 0; i < ( (pocCurr == 0 ) || (pocCurr == 1 ) ? (iNumPicRcvd - iTimeOffset + 1) : (iNumPicRcvd - iTimeOffset + 2) ); i++ )
2847    {
2848      iterPicYuvRec--;
2849    }
2850  }
2851  else
2852  {
2853    for ( i = 0; i < (iNumPicRcvd - iTimeOffset + 1); i++ )
2854    {
2855      iterPicYuvRec--;
2856    }
2857   
2858  }
2859 
2860  if (isField)
2861  {
2862    if(pocCurr == 1)
2863    {
2864      iterPicYuvRec++;
2865    }
2866  }
2867  rpcPicYuvRecOut = *(iterPicYuvRec);
2868 
2869  //  Current pic.
2870  TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
2871  while (iterPic != rcListPic.end())
2872  {
2873    rpcPic = *(iterPic);
2874    rpcPic->setCurrSliceIdx(0);
2875    if (rpcPic->getPOC() == pocCurr)
2876    {
2877      break;
2878    }
2879    iterPic++;
2880  }
2881 
2882  assert( rpcPic != NULL );
2883  assert( rpcPic->getPOC() == pocCurr );
2884 
2885  return;
2886}
2887
2888UInt64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1)
2889{
2890  Int     x, y;
2891  Pel*  pSrc0   = pcPic0 ->getLumaAddr();
2892  Pel*  pSrc1   = pcPic1 ->getLumaAddr();
2893  UInt  uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthY-8);
2894  Int   iTemp;
2895 
2896  Int   iStride = pcPic0->getStride();
2897  Int   iWidth  = pcPic0->getWidth();
2898  Int   iHeight = pcPic0->getHeight();
2899 
2900  UInt64  uiTotalDiff = 0;
2901 
2902  for( y = 0; y < iHeight; y++ )
2903  {
2904    for( x = 0; x < iWidth; x++ )
2905    {
2906      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
2907    }
2908    pSrc0 += iStride;
2909    pSrc1 += iStride;
2910  }
2911 
2912  uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthC-8);
2913  iHeight >>= 1;
2914  iWidth  >>= 1;
2915  iStride >>= 1;
2916 
2917  pSrc0  = pcPic0->getCbAddr();
2918  pSrc1  = pcPic1->getCbAddr();
2919 
2920  for( y = 0; y < iHeight; y++ )
2921  {
2922    for( x = 0; x < iWidth; x++ )
2923    {
2924      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
2925    }
2926    pSrc0 += iStride;
2927    pSrc1 += iStride;
2928  }
2929 
2930  pSrc0  = pcPic0->getCrAddr();
2931  pSrc1  = pcPic1->getCrAddr();
2932 
2933  for( y = 0; y < iHeight; y++ )
2934  {
2935    for( x = 0; x < iWidth; x++ )
2936    {
2937      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
2938    }
2939    pSrc0 += iStride;
2940    pSrc1 += iStride;
2941  }
2942 
2943  return uiTotalDiff;
2944}
2945
2946#if VERBOSE_RATE
2947static const Char* nalUnitTypeToString(NalUnitType type)
2948{
2949  switch (type)
2950  {
2951    case NAL_UNIT_CODED_SLICE_TRAIL_R:    return "TRAIL_R";
2952    case NAL_UNIT_CODED_SLICE_TRAIL_N:    return "TRAIL_N";
2953    case NAL_UNIT_CODED_SLICE_TSA_R:      return "TSA_R";
2954    case NAL_UNIT_CODED_SLICE_TSA_N:      return "TSA_N";
2955    case NAL_UNIT_CODED_SLICE_STSA_R:     return "STSA_R";
2956    case NAL_UNIT_CODED_SLICE_STSA_N:     return "STSA_N";
2957    case NAL_UNIT_CODED_SLICE_BLA_W_LP:   return "BLA_W_LP";
2958    case NAL_UNIT_CODED_SLICE_BLA_W_RADL: return "BLA_W_RADL";
2959    case NAL_UNIT_CODED_SLICE_BLA_N_LP:   return "BLA_N_LP";
2960    case NAL_UNIT_CODED_SLICE_IDR_W_RADL: return "IDR_W_RADL";
2961    case NAL_UNIT_CODED_SLICE_IDR_N_LP:   return "IDR_N_LP";
2962    case NAL_UNIT_CODED_SLICE_CRA:        return "CRA";
2963    case NAL_UNIT_CODED_SLICE_RADL_R:     return "RADL_R";
2964    case NAL_UNIT_CODED_SLICE_RASL_R:     return "RASL_R";
2965    case NAL_UNIT_VPS:                    return "VPS";
2966    case NAL_UNIT_SPS:                    return "SPS";
2967    case NAL_UNIT_PPS:                    return "PPS";
2968    case NAL_UNIT_ACCESS_UNIT_DELIMITER:  return "AUD";
2969    case NAL_UNIT_EOS:                    return "EOS";
2970    case NAL_UNIT_EOB:                    return "EOB";
2971    case NAL_UNIT_FILLER_DATA:            return "FILLER";
2972    case NAL_UNIT_PREFIX_SEI:             return "SEI";
2973    case NAL_UNIT_SUFFIX_SEI:             return "SEI";
2974    default:                              return "UNK";
2975  }
2976}
2977#endif
2978
2979Void TEncGOP::xCalculateAddPSNR( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit& accessUnit, Double dEncTime )
2980{
2981  Int     x, y;
2982  UInt64 uiSSDY  = 0;
2983  UInt64 uiSSDU  = 0;
2984  UInt64 uiSSDV  = 0;
2985 
2986  Double  dYPSNR  = 0.0;
2987  Double  dUPSNR  = 0.0;
2988  Double  dVPSNR  = 0.0;
2989 
2990  //===== calculate PSNR =====
2991  Pel*  pOrg    = pcPic ->getPicYuvOrg()->getLumaAddr();
2992  Pel*  pRec    = pcPicD->getLumaAddr();
2993  Int   iStride = pcPicD->getStride();
2994 
2995  Int   iWidth;
2996  Int   iHeight;
2997 
2998  iWidth  = pcPicD->getWidth () - m_pcEncTop->getPad(0);
2999  iHeight = pcPicD->getHeight() - m_pcEncTop->getPad(1);
3000 
3001  Int   iSize   = iWidth*iHeight;
3002 
3003  for( y = 0; y < iHeight; y++ )
3004  {
3005    for( x = 0; x < iWidth; x++ )
3006    {
3007      Int iDiff = (Int)( pOrg[x] - pRec[x] );
3008      uiSSDY   += iDiff * iDiff;
3009    }
3010    pOrg += iStride;
3011    pRec += iStride;
3012  }
3013 
3014  iHeight >>= 1;
3015  iWidth  >>= 1;
3016  iStride >>= 1;
3017  pOrg  = pcPic ->getPicYuvOrg()->getCbAddr();
3018  pRec  = pcPicD->getCbAddr();
3019 
3020  for( y = 0; y < iHeight; y++ )
3021  {
3022    for( x = 0; x < iWidth; x++ )
3023    {
3024      Int iDiff = (Int)( pOrg[x] - pRec[x] );
3025      uiSSDU   += iDiff * iDiff;
3026    }
3027    pOrg += iStride;
3028    pRec += iStride;
3029  }
3030 
3031  pOrg  = pcPic ->getPicYuvOrg()->getCrAddr();
3032  pRec  = pcPicD->getCrAddr();
3033 
3034  for( y = 0; y < iHeight; y++ )
3035  {
3036    for( x = 0; x < iWidth; x++ )
3037    {
3038      Int iDiff = (Int)( pOrg[x] - pRec[x] );
3039      uiSSDV   += iDiff * iDiff;
3040    }
3041    pOrg += iStride;
3042    pRec += iStride;
3043  }
3044 
3045  Int maxvalY = 255 << (g_bitDepthY-8);
3046  Int maxvalC = 255 << (g_bitDepthC-8);
3047  Double fRefValueY = (Double) maxvalY * maxvalY * iSize;
3048  Double fRefValueC = (Double) maxvalC * maxvalC * iSize / 4.0;
3049  dYPSNR            = ( uiSSDY ? 10.0 * log10( fRefValueY / (Double)uiSSDY ) : 99.99 );
3050  dUPSNR            = ( uiSSDU ? 10.0 * log10( fRefValueC / (Double)uiSSDU ) : 99.99 );
3051  dVPSNR            = ( uiSSDV ? 10.0 * log10( fRefValueC / (Double)uiSSDV ) : 99.99 );
3052
3053  /* calculate the size of the access unit, excluding:
3054   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
3055   *  - SEI NAL units
3056   */
3057  UInt numRBSPBytes = 0;
3058  for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
3059  {
3060    UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
3061#if VERBOSE_RATE
3062    printf("*** %6s numBytesInNALunit: %u\n", nalUnitTypeToString((*it)->m_nalUnitType), numRBSPBytes_nal);
3063#endif
3064    if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
3065    {
3066      numRBSPBytes += numRBSPBytes_nal;
3067    }
3068  }
3069
3070  UInt uibits = numRBSPBytes * 8;
3071  m_vRVM_RP.push_back( uibits );
3072
3073  //===== add PSNR =====
3074#if SVC_EXTENSION
3075  m_gcAnalyzeAll[m_layerId].addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
3076  TComSlice*  pcSlice = pcPic->getSlice(0);
3077  if (pcSlice->isIntra())
3078  {
3079    m_gcAnalyzeI[m_layerId].addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
3080  }
3081  if (pcSlice->isInterP())
3082  {
3083    m_gcAnalyzeP[m_layerId].addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
3084  }
3085  if (pcSlice->isInterB())
3086  {
3087    m_gcAnalyzeB[m_layerId].addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
3088  }
3089#else
3090  m_gcAnalyzeAll.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
3091  TComSlice*  pcSlice = pcPic->getSlice(0);
3092  if (pcSlice->isIntra())
3093  {
3094    m_gcAnalyzeI.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
3095  }
3096  if (pcSlice->isInterP())
3097  {
3098    m_gcAnalyzeP.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
3099  }
3100  if (pcSlice->isInterB())
3101  {
3102    m_gcAnalyzeB.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
3103  }
3104#endif
3105
3106  Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
3107  if (!pcSlice->isReferenced()) c += 32;
3108
3109#if SVC_EXTENSION
3110#if ADAPTIVE_QP_SELECTION
3111  printf("POC %4d LId: %1d TId: %1d ( %c-SLICE, nQP %d QP %d ) %10d bits",
3112         pcSlice->getPOC(),
3113         pcSlice->getLayerId(),
3114         pcSlice->getTLayer(),
3115         c,
3116         pcSlice->getSliceQpBase(),
3117         pcSlice->getSliceQp(),
3118         uibits );
3119#else
3120  printf("POC %4d LId: %1d TId: %1d ( %c-SLICE, QP %d ) %10d bits",
3121         pcSlice->getPOC()-pcSlice->getLastIDR(),
3122         pcSlice->getLayerId(),
3123         pcSlice->getTLayer(),
3124         c,
3125         pcSlice->getSliceQp(),
3126         uibits );
3127#endif
3128#else
3129#if ADAPTIVE_QP_SELECTION
3130  printf("POC %4d TId: %1d ( %c-SLICE, nQP %d QP %d ) %10d bits",
3131         pcSlice->getPOC(),
3132         pcSlice->getTLayer(),
3133         c,
3134         pcSlice->getSliceQpBase(),
3135         pcSlice->getSliceQp(),
3136         uibits );
3137#else
3138  printf("POC %4d TId: %1d ( %c-SLICE, QP %d ) %10d bits",
3139         pcSlice->getPOC()-pcSlice->getLastIDR(),
3140         pcSlice->getTLayer(),
3141         c,
3142         pcSlice->getSliceQp(),
3143         uibits );
3144#endif
3145#endif
3146
3147  printf(" [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", dYPSNR, dUPSNR, dVPSNR );
3148  printf(" [ET %5.0f ]", dEncTime );
3149 
3150  for (Int iRefList = 0; iRefList < 2; iRefList++)
3151  {
3152    printf(" [L%d ", iRefList);
3153    for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(RefPicList(iRefList)); iRefIndex++)
3154    {
3155#if SVC_EXTENSION
3156#if VPS_EXTN_DIRECT_REF_LAYERS
3157      if( pcSlice->getRefPic(RefPicList(iRefList), iRefIndex)->isILR(m_layerId) )
3158      {
3159        printf( "%d(%d)", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)-pcSlice->getLastIDR(), pcSlice->getRefPic(RefPicList(iRefList), iRefIndex)->getLayerId() );
3160      }
3161      else
3162      {
3163        printf ("%d", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)-pcSlice->getLastIDR());
3164      }
3165#endif
3166      if( pcSlice->getEnableTMVPFlag() && iRefList == 1 - pcSlice->getColFromL0Flag() && iRefIndex == pcSlice->getColRefIdx() )
3167      {
3168        printf( "c" );
3169      }
3170
3171      printf( " " );
3172#else
3173      printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)-pcSlice->getLastIDR());
3174#endif
3175    }
3176    printf("]");
3177  }
3178}
3179
3180
3181Void reinterlace(Pel* top, Pel* bottom, Pel* dst, UInt stride, UInt width, UInt height, Bool isTff)
3182{
3183 
3184  for (Int y = 0; y < height; y++)
3185  {
3186    for (Int x = 0; x < width; x++)
3187    {
3188      dst[x] = isTff ? top[x] : bottom[x];
3189      dst[stride+x] = isTff ? bottom[x] : top[x];
3190    }
3191    top += stride;
3192    bottom += stride;
3193    dst += stride*2;
3194  }
3195}
3196
3197Void TEncGOP::xCalculateInterlacedAddPSNR( TComPic* pcPicOrgTop, TComPic* pcPicOrgBottom, TComPicYuv* pcPicRecTop, TComPicYuv* pcPicRecBottom, const AccessUnit& accessUnit, Double dEncTime )
3198{
3199  Int     x, y;
3200 
3201  UInt64 uiSSDY_in  = 0;
3202  UInt64 uiSSDU_in  = 0;
3203  UInt64 uiSSDV_in  = 0;
3204 
3205  Double  dYPSNR_in  = 0.0;
3206  Double  dUPSNR_in  = 0.0;
3207  Double  dVPSNR_in  = 0.0;
3208 
3209  /*------ INTERLACED PSNR -----------*/
3210 
3211  /* Luma */
3212 
3213  Pel*  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getLumaAddr();
3214  Pel*  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getLumaAddr();
3215  Pel*  pRecTop = pcPicRecTop->getLumaAddr();
3216  Pel*  pRecBottom = pcPicRecBottom->getLumaAddr();
3217 
3218  Int   iWidth;
3219  Int   iHeight;
3220  Int iStride;
3221 
3222  iWidth  = pcPicOrgTop->getPicYuvOrg()->getWidth () - m_pcEncTop->getPad(0);
3223  iHeight = pcPicOrgTop->getPicYuvOrg()->getHeight() - m_pcEncTop->getPad(1);
3224  iStride = pcPicOrgTop->getPicYuvOrg()->getStride();
3225  Int   iSize   = iWidth*iHeight;
3226  bool isTff = pcPicOrgTop->isTopField();
3227 
3228  TComPicYuv* pcOrgInterlaced = new TComPicYuv;
3229#if AUXILIARY_PICTURES
3230  pcOrgInterlaced->create( iWidth, iHeight << 1, pcPicOrgTop->getChromaFormat(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
3231#else
3232  pcOrgInterlaced->create( iWidth, iHeight << 1, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
3233#endif
3234 
3235  TComPicYuv* pcRecInterlaced = new TComPicYuv;
3236#if AUXILIARY_PICTURES
3237  pcRecInterlaced->create( iWidth, iHeight << 1, pcPicOrgTop->getChromaFormat(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
3238#else
3239  pcRecInterlaced->create( iWidth, iHeight << 1, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
3240#endif
3241 
3242  Pel* pOrgInterlaced = pcOrgInterlaced->getLumaAddr();
3243  Pel* pRecInterlaced = pcRecInterlaced->getLumaAddr();
3244 
3245  //=== Interlace fields ====
3246  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
3247  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
3248 
3249  //===== calculate PSNR =====
3250  for( y = 0; y < iHeight << 1; y++ )
3251  {
3252    for( x = 0; x < iWidth; x++ )
3253    {
3254      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
3255      uiSSDY_in   += iDiff * iDiff;
3256    }
3257    pOrgInterlaced += iStride;
3258    pRecInterlaced += iStride;
3259  }
3260 
3261  /*Chroma*/
3262 
3263  iHeight >>= 1;
3264  iWidth  >>= 1;
3265  iStride >>= 1;
3266 
3267  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getCbAddr();
3268  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getCbAddr();
3269  pRecTop = pcPicRecTop->getCbAddr();
3270  pRecBottom = pcPicRecBottom->getCbAddr();
3271  pOrgInterlaced = pcOrgInterlaced->getCbAddr();
3272  pRecInterlaced = pcRecInterlaced->getCbAddr();
3273 
3274  //=== Interlace fields ====
3275  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
3276  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
3277 
3278  //===== calculate PSNR =====
3279  for( y = 0; y < iHeight << 1; y++ )
3280  {
3281    for( x = 0; x < iWidth; x++ )
3282    {
3283      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
3284      uiSSDU_in   += iDiff * iDiff;
3285    }
3286    pOrgInterlaced += iStride;
3287    pRecInterlaced += iStride;
3288  }
3289 
3290  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getCrAddr();
3291  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getCrAddr();
3292  pRecTop = pcPicRecTop->getCrAddr();
3293  pRecBottom = pcPicRecBottom->getCrAddr();
3294  pOrgInterlaced = pcOrgInterlaced->getCrAddr();
3295  pRecInterlaced = pcRecInterlaced->getCrAddr();
3296 
3297  //=== Interlace fields ====
3298  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
3299  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
3300 
3301  //===== calculate PSNR =====
3302  for( y = 0; y < iHeight << 1; y++ )
3303  {
3304    for( x = 0; x < iWidth; x++ )
3305    {
3306      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
3307      uiSSDV_in   += iDiff * iDiff;
3308    }
3309    pOrgInterlaced += iStride;
3310    pRecInterlaced += iStride;
3311  }
3312 
3313  Int maxvalY = 255 << (g_bitDepthY-8);
3314  Int maxvalC = 255 << (g_bitDepthC-8);
3315  Double fRefValueY = (Double) maxvalY * maxvalY * iSize*2;
3316  Double fRefValueC = (Double) maxvalC * maxvalC * iSize*2 / 4.0;
3317  dYPSNR_in            = ( uiSSDY_in ? 10.0 * log10( fRefValueY / (Double)uiSSDY_in ) : 99.99 );
3318  dUPSNR_in            = ( uiSSDU_in ? 10.0 * log10( fRefValueC / (Double)uiSSDU_in ) : 99.99 );
3319  dVPSNR_in            = ( uiSSDV_in ? 10.0 * log10( fRefValueC / (Double)uiSSDV_in ) : 99.99 );
3320 
3321  /* calculate the size of the access unit, excluding:
3322   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
3323   *  - SEI NAL units
3324   */
3325  UInt numRBSPBytes = 0;
3326  for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
3327  {
3328    UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
3329   
3330    if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
3331      numRBSPBytes += numRBSPBytes_nal;
3332  }
3333 
3334  UInt uibits = numRBSPBytes * 8 ;
3335 
3336  //===== add PSNR =====
3337  m_gcAnalyzeAll_in.addResult (dYPSNR_in, dUPSNR_in, dVPSNR_in, (Double)uibits);
3338 
3339  printf("\n                                      Interlaced frame %d: [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", pcPicOrgBottom->getPOC()/2 , dYPSNR_in, dUPSNR_in, dVPSNR_in );
3340 
3341  pcOrgInterlaced->destroy();
3342  delete pcOrgInterlaced;
3343  pcRecInterlaced->destroy();
3344  delete pcRecInterlaced;
3345}
3346
3347
3348
3349/** Function for deciding the nal_unit_type.
3350 * \param pocCurr POC of the current picture
3351 * \returns the nal unit type of the picture
3352 * This function checks the configuration and returns the appropriate nal_unit_type for the picture.
3353 */
3354NalUnitType TEncGOP::getNalUnitType(Int pocCurr, Int lastIDR)
3355{
3356  if (pocCurr == 0)
3357  {
3358    return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
3359  }
3360  if (pocCurr % m_pcCfg->getIntraPeriod() == 0)
3361  {
3362    if (m_pcCfg->getDecodingRefreshType() == 1)
3363    {
3364      return NAL_UNIT_CODED_SLICE_CRA;
3365    }
3366    else if (m_pcCfg->getDecodingRefreshType() == 2)
3367    {
3368      return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
3369    }
3370  }
3371  if(m_pocCRA>0)
3372  {
3373    if(pocCurr<m_pocCRA)
3374    {
3375      // All leading pictures are being marked as TFD pictures here since current encoder uses all
3376      // reference pictures while encoding leading pictures. An encoder can ensure that a leading
3377      // picture can be still decodable when random accessing to a CRA/CRANT/BLA/BLANT picture by
3378      // controlling the reference pictures used for encoding that leading picture. Such a leading
3379      // picture need not be marked as a TFD picture.
3380      return NAL_UNIT_CODED_SLICE_RASL_R;
3381    }
3382  }
3383  if (lastIDR>0)
3384  {
3385    if (pocCurr < lastIDR)
3386    {
3387      return NAL_UNIT_CODED_SLICE_RADL_R;
3388    }
3389  }
3390  return NAL_UNIT_CODED_SLICE_TRAIL_R;
3391}
3392
3393Double TEncGOP::xCalculateRVM()
3394{
3395  Double dRVM = 0;
3396 
3397  if( m_pcCfg->getGOPSize() == 1 && m_pcCfg->getIntraPeriod() != 1 && m_pcCfg->getFramesToBeEncoded() > RVM_VCEGAM10_M * 2 )
3398  {
3399    // calculate RVM only for lowdelay configurations
3400    std::vector<Double> vRL , vB;
3401    size_t N = m_vRVM_RP.size();
3402    vRL.resize( N );
3403    vB.resize( N );
3404   
3405    Int i;
3406    Double dRavg = 0 , dBavg = 0;
3407    vB[RVM_VCEGAM10_M] = 0;
3408    for( i = RVM_VCEGAM10_M + 1 ; i < N - RVM_VCEGAM10_M + 1 ; i++ )
3409    {
3410      vRL[i] = 0;
3411      for( Int j = i - RVM_VCEGAM10_M ; j <= i + RVM_VCEGAM10_M - 1 ; j++ )
3412        vRL[i] += m_vRVM_RP[j];
3413      vRL[i] /= ( 2 * RVM_VCEGAM10_M );
3414      vB[i] = vB[i-1] + m_vRVM_RP[i] - vRL[i];
3415      dRavg += m_vRVM_RP[i];
3416      dBavg += vB[i];
3417    }
3418   
3419    dRavg /= ( N - 2 * RVM_VCEGAM10_M );
3420    dBavg /= ( N - 2 * RVM_VCEGAM10_M );
3421   
3422    Double dSigamB = 0;
3423    for( i = RVM_VCEGAM10_M + 1 ; i < N - RVM_VCEGAM10_M + 1 ; i++ )
3424    {
3425      Double tmp = vB[i] - dBavg;
3426      dSigamB += tmp * tmp;
3427    }
3428    dSigamB = sqrt( dSigamB / ( N - 2 * RVM_VCEGAM10_M ) );
3429   
3430    Double f = sqrt( 12.0 * ( RVM_VCEGAM10_M - 1 ) / ( RVM_VCEGAM10_M + 1 ) );
3431   
3432    dRVM = dSigamB / dRavg * f;
3433  }
3434 
3435  return( dRVM );
3436}
3437
3438/** Attaches the input bitstream to the stream in the output NAL unit
3439    Updates rNalu to contain concatenated bitstream. rpcBitstreamRedirect is cleared at the end of this function call.
3440 *  \param codedSliceData contains the coded slice data (bitstream) to be concatenated to rNalu
3441 *  \param rNalu          target NAL unit
3442 */
3443Void TEncGOP::xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream*& codedSliceData)
3444{
3445  // Byte-align
3446  rNalu.m_Bitstream.writeByteAlignment();   // Slice header byte-alignment
3447
3448  // Perform bitstream concatenation
3449  if (codedSliceData->getNumberOfWrittenBits() > 0)
3450    {
3451    rNalu.m_Bitstream.addSubstream(codedSliceData);
3452  }
3453
3454  m_pcEntropyCoder->setBitstream(&rNalu.m_Bitstream);
3455
3456  codedSliceData->clear();
3457}
3458
3459// Function will arrange the long-term pictures in the decreasing order of poc_lsb_lt,
3460// and among the pictures with the same lsb, it arranges them in increasing delta_poc_msb_cycle_lt value
3461Void TEncGOP::arrangeLongtermPicturesInRPS(TComSlice *pcSlice, TComList<TComPic*>& rcListPic)
3462{
3463  TComReferencePictureSet *rps = pcSlice->getRPS();
3464  if(!rps->getNumberOfLongtermPictures())
3465  {
3466    return;
3467  }
3468
3469  // Arrange long-term reference pictures in the correct order of LSB and MSB,
3470  // and assign values for pocLSBLT and MSB present flag
3471  Int longtermPicsPoc[MAX_NUM_REF_PICS], longtermPicsLSB[MAX_NUM_REF_PICS], indices[MAX_NUM_REF_PICS];
3472  Int longtermPicsMSB[MAX_NUM_REF_PICS];
3473  Bool mSBPresentFlag[MAX_NUM_REF_PICS];
3474  ::memset(longtermPicsPoc, 0, sizeof(longtermPicsPoc));    // Store POC values of LTRP
3475  ::memset(longtermPicsLSB, 0, sizeof(longtermPicsLSB));    // Store POC LSB values of LTRP
3476  ::memset(longtermPicsMSB, 0, sizeof(longtermPicsMSB));    // Store POC LSB values of LTRP
3477  ::memset(indices        , 0, sizeof(indices));            // Indices to aid in tracking sorted LTRPs
3478  ::memset(mSBPresentFlag , 0, sizeof(mSBPresentFlag));     // Indicate if MSB needs to be present
3479
3480  // Get the long-term reference pictures
3481  Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
3482  Int i, ctr = 0;
3483  Int maxPicOrderCntLSB = 1 << pcSlice->getSPS()->getBitsForPOC();
3484  for(i = rps->getNumberOfPictures() - 1; i >= offset; i--, ctr++)
3485  {
3486    longtermPicsPoc[ctr] = rps->getPOC(i);                                  // LTRP POC
3487    longtermPicsLSB[ctr] = getLSB(longtermPicsPoc[ctr], maxPicOrderCntLSB); // LTRP POC LSB
3488    indices[ctr]      = i; 
3489    longtermPicsMSB[ctr] = longtermPicsPoc[ctr] - longtermPicsLSB[ctr];
3490  }
3491  Int numLongPics = rps->getNumberOfLongtermPictures();
3492  assert(ctr == numLongPics);
3493
3494  // Arrange pictures in decreasing order of MSB;
3495  for(i = 0; i < numLongPics; i++)
3496  {
3497    for(Int j = 0; j < numLongPics - 1; j++)
3498    {
3499      if(longtermPicsMSB[j] < longtermPicsMSB[j+1])
3500      {
3501        std::swap(longtermPicsPoc[j], longtermPicsPoc[j+1]);
3502        std::swap(longtermPicsLSB[j], longtermPicsLSB[j+1]);
3503        std::swap(longtermPicsMSB[j], longtermPicsMSB[j+1]);
3504        std::swap(indices[j]        , indices[j+1]        );
3505      }
3506    }
3507  }
3508
3509  for(i = 0; i < numLongPics; i++)
3510  {
3511    // Check if MSB present flag should be enabled.
3512    // Check if the buffer contains any pictures that have the same LSB.
3513    TComList<TComPic*>::iterator  iterPic = rcListPic.begin(); 
3514    TComPic*                      pcPic;
3515    while ( iterPic != rcListPic.end() )
3516    {
3517      pcPic = *iterPic;
3518      if( (getLSB(pcPic->getPOC(), maxPicOrderCntLSB) == longtermPicsLSB[i])   &&     // Same LSB
3519                                      (pcPic->getSlice(0)->isReferenced())     &&    // Reference picture
3520                                        (pcPic->getPOC() != longtermPicsPoc[i])    )  // Not the LTRP itself
3521      {
3522        mSBPresentFlag[i] = true;
3523        break;
3524      }
3525      iterPic++;     
3526    }
3527  }
3528
3529  // tempArray for usedByCurr flag
3530  Bool tempArray[MAX_NUM_REF_PICS]; ::memset(tempArray, 0, sizeof(tempArray));
3531  for(i = 0; i < numLongPics; i++)
3532  {
3533    tempArray[i] = rps->getUsed(indices[i]);
3534  }
3535  // Now write the final values;
3536  ctr = 0;
3537  Int currMSB = 0, currLSB = 0;
3538  // currPicPoc = currMSB + currLSB
3539  currLSB = getLSB(pcSlice->getPOC(), maxPicOrderCntLSB); 
3540  currMSB = pcSlice->getPOC() - currLSB;
3541
3542  for(i = rps->getNumberOfPictures() - 1; i >= offset; i--, ctr++)
3543  {
3544    rps->setPOC                   (i, longtermPicsPoc[ctr]);
3545    rps->setDeltaPOC              (i, - pcSlice->getPOC() + longtermPicsPoc[ctr]);
3546    rps->setUsed                  (i, tempArray[ctr]);
3547    rps->setPocLSBLT              (i, longtermPicsLSB[ctr]);
3548    rps->setDeltaPocMSBCycleLT    (i, (currMSB - (longtermPicsPoc[ctr] - longtermPicsLSB[ctr])) / maxPicOrderCntLSB);
3549    rps->setDeltaPocMSBPresentFlag(i, mSBPresentFlag[ctr]);     
3550
3551    assert(rps->getDeltaPocMSBCycleLT(i) >= 0);   // Non-negative value
3552  }
3553  for(i = rps->getNumberOfPictures() - 1, ctr = 1; i >= offset; i--, ctr++)
3554  {
3555    for(Int j = rps->getNumberOfPictures() - 1 - ctr; j >= offset; j--)
3556    {
3557      // Here at the encoder we know that we have set the full POC value for the LTRPs, hence we
3558      // don't have to check the MSB present flag values for this constraint.
3559      assert( rps->getPOC(i) != rps->getPOC(j) ); // If assert fails, LTRP entry repeated in RPS!!!
3560    }
3561  }
3562}
3563
3564/** Function for finding the position to insert the first of APS and non-nested BP, PT, DU info SEI messages.
3565 * \param accessUnit Access Unit of the current picture
3566 * This function finds the position to insert the first of APS and non-nested BP, PT, DU info SEI messages.
3567 */
3568Int TEncGOP::xGetFirstSeiLocation(AccessUnit &accessUnit)
3569{
3570  // Find the location of the first SEI message
3571  AccessUnit::iterator it;
3572  Int seiStartPos = 0;
3573  for(it = accessUnit.begin(); it != accessUnit.end(); it++, seiStartPos++)
3574  {
3575     if ((*it)->isSei() || (*it)->isVcl())
3576     {
3577       break;
3578     }               
3579  }
3580//  assert(it != accessUnit.end());  // Triggers with some legit configurations
3581  return seiStartPos;
3582}
3583
3584#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
3585Void TEncGOP::xBuildTileSetsMap(TComPicSym* picSym)
3586{
3587  Int numCUs = picSym->getFrameWidthInCU() * picSym->getFrameHeightInCU();
3588
3589  for (Int i = 0; i < numCUs; i++)
3590  {
3591    picSym->setTileSetIdxMap(i, -1, 0, false);
3592  }
3593
3594  for (Int i = 0; i < m_pcCfg->getIlNumSetsInMessage(); i++)
3595  {
3596    TComTile* topLeftTile     = picSym->getTComTile(m_pcCfg->getTopLeftTileIndex(i));
3597    TComTile* bottomRightTile = picSym->getTComTile(m_pcCfg->getBottomRightTileIndex(i));
3598    Int tileSetLeftEdgePosInCU = topLeftTile->getRightEdgePosInCU() - topLeftTile->getTileWidth() + 1;
3599    Int tileSetRightEdgePosInCU = bottomRightTile->getRightEdgePosInCU();
3600    Int tileSetTopEdgePosInCU = topLeftTile->getBottomEdgePosInCU() - topLeftTile->getTileHeight() + 1;
3601    Int tileSetBottomEdgePosInCU = bottomRightTile->getBottomEdgePosInCU();
3602    assert(tileSetLeftEdgePosInCU < tileSetRightEdgePosInCU && tileSetTopEdgePosInCU < tileSetBottomEdgePosInCU);
3603    for (Int j = tileSetTopEdgePosInCU; j <= tileSetBottomEdgePosInCU; j++)
3604    {
3605      for (Int k = tileSetLeftEdgePosInCU; k <= tileSetRightEdgePosInCU; k++)
3606      {
3607        picSym->setTileSetIdxMap(j * picSym->getFrameWidthInCU() + k, i, m_pcCfg->getIlcIdc(i), false);
3608      }
3609    }
3610  }
3611 
3612  if (m_pcCfg->getSkippedTileSetPresentFlag())
3613  {
3614    Int skippedTileSetIdx = m_pcCfg->getIlNumSetsInMessage();
3615    for (Int i = 0; i < numCUs; i++)
3616    {
3617      if (picSym->getTileSetIdxMap(i) < 0)
3618      {
3619        picSym->setTileSetIdxMap(i, skippedTileSetIdx, 0, true);
3620      }
3621    }
3622  }
3623}
3624#endif
3625
3626Void TEncGOP::dblMetric( TComPic* pcPic, UInt uiNumSlices )
3627{
3628  TComPicYuv* pcPicYuvRec = pcPic->getPicYuvRec();
3629  Pel* Rec    = pcPicYuvRec->getLumaAddr( 0 );
3630  Pel* tempRec = Rec;
3631  Int  stride = pcPicYuvRec->getStride();
3632  UInt log2maxTB = pcPic->getSlice(0)->getSPS()->getQuadtreeTULog2MaxSize();
3633  UInt maxTBsize = (1<<log2maxTB);
3634  const UInt minBlockArtSize = 8;
3635  const UInt picWidth = pcPicYuvRec->getWidth();
3636  const UInt picHeight = pcPicYuvRec->getHeight();
3637  const UInt noCol = (picWidth>>log2maxTB);
3638  const UInt noRows = (picHeight>>log2maxTB);
3639  assert(noCol > 1);
3640  assert(noRows > 1);
3641  UInt64 *colSAD = (UInt64*)malloc(noCol*sizeof(UInt64));
3642  UInt64 *rowSAD = (UInt64*)malloc(noRows*sizeof(UInt64));
3643  UInt colIdx = 0;
3644  UInt rowIdx = 0;
3645  Pel p0, p1, p2, q0, q1, q2;
3646 
3647  Int qp = pcPic->getSlice(0)->getSliceQp();
3648  Int bitdepthScale = 1 << (g_bitDepthY-8);
3649  Int beta = TComLoopFilter::getBeta( qp ) * bitdepthScale;
3650  const Int thr2 = (beta>>2);
3651  const Int thr1 = 2*bitdepthScale;
3652  UInt a = 0;
3653 
3654  memset(colSAD, 0, noCol*sizeof(UInt64));
3655  memset(rowSAD, 0, noRows*sizeof(UInt64));
3656 
3657  if (maxTBsize > minBlockArtSize)
3658  {
3659    // Analyze vertical artifact edges
3660    for(Int c = maxTBsize; c < picWidth; c += maxTBsize)
3661    {
3662      for(Int r = 0; r < picHeight; r++)
3663      {
3664        p2 = Rec[c-3];
3665        p1 = Rec[c-2];
3666        p0 = Rec[c-1];
3667        q0 = Rec[c];
3668        q1 = Rec[c+1];
3669        q2 = Rec[c+2];
3670        a = ((abs(p2-(p1<<1)+p0)+abs(q0-(q1<<1)+q2))<<1);
3671        if ( thr1 < a && a < thr2)
3672        {
3673          colSAD[colIdx] += abs(p0 - q0);
3674        }
3675        Rec += stride;
3676      }
3677      colIdx++;
3678      Rec = tempRec;
3679    }
3680   
3681    // Analyze horizontal artifact edges
3682    for(Int r = maxTBsize; r < picHeight; r += maxTBsize)
3683    {
3684      for(Int c = 0; c < picWidth; c++)
3685      {
3686        p2 = Rec[c + (r-3)*stride];
3687        p1 = Rec[c + (r-2)*stride];
3688        p0 = Rec[c + (r-1)*stride];
3689        q0 = Rec[c + r*stride];
3690        q1 = Rec[c + (r+1)*stride];
3691        q2 = Rec[c + (r+2)*stride];
3692        a = ((abs(p2-(p1<<1)+p0)+abs(q0-(q1<<1)+q2))<<1);
3693        if (thr1 < a && a < thr2)
3694        {
3695          rowSAD[rowIdx] += abs(p0 - q0);
3696        }
3697      }
3698      rowIdx++;
3699    }
3700  }
3701 
3702  UInt64 colSADsum = 0;
3703  UInt64 rowSADsum = 0;
3704  for(Int c = 0; c < noCol-1; c++)
3705  {
3706    colSADsum += colSAD[c];
3707  }
3708  for(Int r = 0; r < noRows-1; r++)
3709  {
3710    rowSADsum += rowSAD[r];
3711  }
3712 
3713  colSADsum <<= 10;
3714  rowSADsum <<= 10;
3715  colSADsum /= (noCol-1);
3716  colSADsum /= picHeight;
3717  rowSADsum /= (noRows-1);
3718  rowSADsum /= picWidth;
3719 
3720  UInt64 avgSAD = ((colSADsum + rowSADsum)>>1);
3721  avgSAD >>= (g_bitDepthY-8);
3722 
3723  if ( avgSAD > 2048 )
3724  {
3725    avgSAD >>= 9;
3726    Int offset = Clip3(2,6,(Int)avgSAD);
3727    for (Int i=0; i<uiNumSlices; i++)
3728    {
3729      pcPic->getSlice(i)->setDeblockingFilterOverrideFlag(true);
3730      pcPic->getSlice(i)->setDeblockingFilterDisable(false);
3731      pcPic->getSlice(i)->setDeblockingFilterBetaOffsetDiv2( offset );
3732      pcPic->getSlice(i)->setDeblockingFilterTcOffsetDiv2( offset );
3733    }
3734  }
3735  else
3736  {
3737    for (Int i=0; i<uiNumSlices; i++)
3738    {
3739      pcPic->getSlice(i)->setDeblockingFilterOverrideFlag(false);
3740      pcPic->getSlice(i)->setDeblockingFilterDisable(        pcPic->getSlice(i)->getPPS()->getPicDisableDeblockingFilterFlag() );
3741      pcPic->getSlice(i)->setDeblockingFilterBetaOffsetDiv2( pcPic->getSlice(i)->getPPS()->getDeblockingFilterBetaOffsetDiv2() );
3742      pcPic->getSlice(i)->setDeblockingFilterTcOffsetDiv2(   pcPic->getSlice(i)->getPPS()->getDeblockingFilterTcOffsetDiv2()   );
3743    }
3744  }
3745 
3746  free(colSAD);
3747  free(rowSAD);
3748}
3749
3750#if M0457_COL_PICTURE_SIGNALING && !REMOVE_COL_PICTURE_SIGNALING
3751TComPic* TEncGOP::getMotionPredIlp(TComSlice* pcSlice)
3752{
3753  TComPic* ilpPic = NULL;
3754  Int activeMotionPredReflayerIdx = 0;
3755
3756  for( Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ )
3757  {
3758    UInt refLayerIdc = pcSlice->getInterLayerPredLayerIdc(i);
3759    if( m_pcEncTop->getMotionPredEnabledFlag( pcSlice->getVPS()->getRefLayerId( m_layerId, refLayerIdc ) ) )
3760    {
3761      if (activeMotionPredReflayerIdx == pcSlice->getColRefLayerIdx())
3762      {
3763        ilpPic = m_pcEncTop->getIlpList()[refLayerIdc];
3764        break;
3765      }
3766      else
3767      {
3768        activeMotionPredReflayerIdx++;
3769      }
3770    }
3771  }
3772
3773  assert(ilpPic != NULL);
3774
3775  return ilpPic;
3776}
3777#endif
3778
3779//! \}
Note: See TracBrowser for help on using the repository browser.