source: 3DVCSoftware/branches/HTM-9.2-dev0/source/Lib/TLibEncoder/TEncGOP.cpp @ 762

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

remove multiple PPS for depth views

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