source: 3DVCSoftware/branches/HTM-10.0-dev0/source/Lib/TLibEncoder/TEncGOP.cpp @ 862

Last change on this file since 862 was 862, checked in by qualcomm, 10 years ago

JCTVC-P0204: Sub-bitstream property SEI message (Macro: H_MV_HLS_7_SEI_P0204_26)

Includes signaling, and option to input parameters of the SEI message in the configuration file.

From: Adarsh K. Ramasubramonian <aramasub@…>

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