source: 3DVCSoftware/branches/HTM-11.2-dev3-MediaTek/source/Lib/TLibEncoder/TEncGOP.cpp @ 983

Last change on this file since 983 was 983, checked in by mediatek-htm, 10 years ago

Integration of Single Depth Mode proposed in JCT3V-I0095.
The MACRO is "MTK_SINGLE_DEPTH_MODE_I0095".

By Yi-Wen Chen (yiwen.chen@…)

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