source: 3DVCSoftware/branches/HTM-12.2-dev1-Mediatek/source/Lib/TLibEncoder/TEncGOP.cpp @ 1096

Last change on this file since 1096 was 1090, checked in by mediatek-htm, 11 years ago

Integration of JCT3V-J0060. The MACRO is "MTK_SINGLE_DEPTH_VPS_FLAG_J0060".

By YiWen Chen (yiwen.chen@…)

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