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

Last change on this file since 765 was 765, checked in by tech, 11 years ago

Cleanup part 2

  • Property svn:eol-style set to native
File size: 122.8 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    pcSlice->setARPStepNum(m_ivPicLists);
748    if(pcSlice->getARPStepNum() > 1)
749    {
750      for(Int iLayerId = 0; iLayerId < getLayerId(); iLayerId ++ )
751      {
752        Int  iViewIdx =   pcSlice->getVPS()->getViewIndex(iLayerId);
753        Bool bIsDepth = ( pcSlice->getVPS()->getDepthId  ( iLayerId ) == 1 );
754        if( iViewIdx<getViewIndex() && !bIsDepth )
755        {
756          pcSlice->setBaseViewRefPicList( m_ivPicLists->getPicList( iLayerId ), iViewIdx );
757        }
758      }
759    }
760#endif
761#if H_3D
762    pcSlice->setIvPicLists( m_ivPicLists );         
763#if H_3D_IV_MERGE   
764    assert( !m_pcEncTop->getIsDepth() || ( pcSlice->getTexturePic() != 0 ) );
765#endif   
766#endif
767    //  Slice info. refinement
768#if H_MV
769    if ( pcSlice->getSliceType() == B_SLICE )
770    {
771      if( m_pcCfg->getGOPEntry( ( pcSlice->getRapPicFlag() == true && getLayerId() > 0 ) ? MAX_GOP : iGOPid ).m_sliceType == 'P' ) 
772      { 
773        pcSlice->setSliceType( P_SLICE ); 
774      }
775    }
776#else
777    if ( (pcSlice->getSliceType() == B_SLICE) && (pcSlice->getNumRefIdx(REF_PIC_LIST_1) == 0) )
778    {
779      pcSlice->setSliceType ( P_SLICE );
780    }
781#endif
782    if (pcSlice->getSliceType() == B_SLICE)
783    {
784      pcSlice->setColFromL0Flag(1-uiColDir);
785      Bool bLowDelay = true;
786      Int  iCurrPOC  = pcSlice->getPOC();
787      Int iRefIdx = 0;
788
789      for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_0) && bLowDelay; iRefIdx++)
790      {
791        if ( pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx)->getPOC() > iCurrPOC )
792        {
793          bLowDelay = false;
794        }
795      }
796      for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_1) && bLowDelay; iRefIdx++)
797      {
798        if ( pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx)->getPOC() > iCurrPOC )
799        {
800          bLowDelay = false;
801        }
802      }
803
804      pcSlice->setCheckLDC(bLowDelay); 
805    }
806    else
807    {
808      pcSlice->setCheckLDC(true); 
809    }
810
811    uiColDir = 1-uiColDir;
812
813    //-------------------------------------------------------------
814    pcSlice->setRefPOCList();
815
816    pcSlice->setList1IdxToList0Idx();
817#if H_3D_TMVP
818    if(pcSlice->getLayerId())
819      pcSlice->generateAlterRefforTMVP();
820#endif
821    if (m_pcEncTop->getTMVPModeId() == 2)
822    {
823      if (iGOPid == 0) // first picture in SOP (i.e. forward B)
824      {
825        pcSlice->setEnableTMVPFlag(0);
826      }
827      else
828      {
829        // Note: pcSlice->getColFromL0Flag() is assumed to be always 0 and getcolRefIdx() is always 0.
830        pcSlice->setEnableTMVPFlag(1);
831      }
832      pcSlice->getSPS()->setTMVPFlagsPresent(1);
833    }
834    else if (m_pcEncTop->getTMVPModeId() == 1)
835    {
836      pcSlice->getSPS()->setTMVPFlagsPresent(1);
837      pcSlice->setEnableTMVPFlag(1);
838    }
839    else
840    {
841      pcSlice->getSPS()->setTMVPFlagsPresent(0);
842      pcSlice->setEnableTMVPFlag(0);
843    }
844#if H_MV
845    if( pcSlice->getIdrPicFlag() )
846    {
847      pcSlice->setEnableTMVPFlag(0);
848    }
849#endif
850
851#if H_3D_VSO
852  // Should be moved to TEncTop !!!
853  Bool bUseVSO = m_pcEncTop->getUseVSO();
854 
855  TComRdCost* pcRdCost = m_pcEncTop->getRdCost();   
856
857  pcRdCost->setUseVSO( bUseVSO );
858
859  // SAIT_VSO_EST_A0033
860  pcRdCost->setUseEstimatedVSD( m_pcEncTop->getUseEstimatedVSD() );
861
862  if ( bUseVSO )
863  {
864    Int iVSOMode = m_pcEncTop->getVSOMode();
865    pcRdCost->setVSOMode( iVSOMode  );
866    pcRdCost->setAllowNegDist( m_pcEncTop->getAllowNegDist() );
867
868    // SAIT_VSO_EST_A0033
869#if H_3D_FCO
870    Bool flagRec;
871    flagRec =  ((m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), false, pcSlice->getPOC(), true) == NULL) ? false: true);
872    pcRdCost->setVideoRecPicYuv( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), false, pcSlice->getPOC(), flagRec ) );
873    pcRdCost->setDepthPicYuv   ( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), true, pcSlice->getPOC(), false ) );
874#else
875    pcRdCost->setVideoRecPicYuv( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), false , pcSlice->getPOC(), true ) );
876    pcRdCost->setDepthPicYuv   ( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), true  , pcSlice->getPOC(), false ) );
877#endif
878
879    // LGE_WVSO_A0119
880    Bool bUseWVSO  = m_pcEncTop->getUseWVSO();
881    pcRdCost->setUseWVSO( bUseWVSO );
882
883  }
884#endif
885    /////////////////////////////////////////////////////////////////////////////////////////////////// Compress a slice
886    //  Slice compression
887    if (m_pcCfg->getUseASR())
888    {
889      m_pcSliceEncoder->setSearchRange(pcSlice);
890    }
891
892    Bool bGPBcheck=false;
893    if ( pcSlice->getSliceType() == B_SLICE)
894    {
895      if ( pcSlice->getNumRefIdx(RefPicList( 0 ) ) == pcSlice->getNumRefIdx(RefPicList( 1 ) ) )
896      {
897        bGPBcheck=true;
898        Int i;
899        for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
900        {
901          if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) ) 
902          {
903            bGPBcheck=false;
904            break;
905          }
906        }
907      }
908    }
909    if(bGPBcheck)
910    {
911      pcSlice->setMvdL1ZeroFlag(true);
912    }
913    else
914    {
915      pcSlice->setMvdL1ZeroFlag(false);
916    }
917    pcPic->getSlice(pcSlice->getSliceIdx())->setMvdL1ZeroFlag(pcSlice->getMvdL1ZeroFlag());
918
919#if RATE_CONTROL_LAMBDA_DOMAIN
920    Double lambda            = 0.0;
921    Int actualHeadBits       = 0;
922    Int actualTotalBits      = 0;
923    Int estimatedBits        = 0;
924    Int tmpBitsBeforeWriting = 0;
925    if ( m_pcCfg->getUseRateCtrl() )
926    {
927      Int frameLevel = m_pcRateCtrl->getRCSeq()->getGOPID2Level( iGOPid );
928      if ( pcPic->getSlice(0)->getSliceType() == I_SLICE )
929      {
930        frameLevel = 0;
931      }
932      m_pcRateCtrl->initRCPic( frameLevel );
933
934#if KWU_RC_MADPRED_E0227
935      if(m_pcCfg->getLayerId() != 0)
936      {
937        m_pcRateCtrl->getRCPic()->setIVPic( m_pcEncTop->getEncTop()->getTEncTop(0)->getRateCtrl()->getRCPic() );
938      }
939#endif
940
941      estimatedBits = m_pcRateCtrl->getRCPic()->getTargetBits();
942
943      Int sliceQP = m_pcCfg->getInitialQP();
944      if ( ( pcSlice->getPOC() == 0 && m_pcCfg->getInitialQP() > 0 ) || ( frameLevel == 0 && m_pcCfg->getForceIntraQP() ) ) // QP is specified
945      {
946        Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
947        Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)NumberBFrames );
948        Double dQPFactor     = 0.57*dLambda_scale;
949        Int    SHIFT_QP      = 12;
950        Int    bitdepth_luma_qp_scale = 0;
951        Double qp_temp = (Double) sliceQP + bitdepth_luma_qp_scale - SHIFT_QP;
952        lambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
953      }
954      else if ( frameLevel == 0 )   // intra case, but use the model
955      {
956#if RATE_CONTROL_INTRA
957        m_pcSliceEncoder->calCostSliceI(pcPic);
958#endif
959        if ( m_pcCfg->getIntraPeriod() != 1 )   // do not refine allocated bits for all intra case
960        {
961          Int bits = m_pcRateCtrl->getRCSeq()->getLeftAverageBits();
962#if RATE_CONTROL_INTRA
963          bits = m_pcRateCtrl->getRCPic()->getRefineBitsForIntra( bits );
964#else
965          bits = m_pcRateCtrl->getRCSeq()->getRefineBitsForIntra( bits );
966#endif
967          if ( bits < 200 )
968          {
969            bits = 200;
970          }
971          m_pcRateCtrl->getRCPic()->setTargetBits( bits );
972        }
973
974        list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
975#if RATE_CONTROL_INTRA
976        m_pcRateCtrl->getRCPic()->getLCUInitTargetBits();
977        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
978#else
979        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture );
980#endif
981        sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
982      }
983      else    // normal case
984      {
985#if KWU_RC_MADPRED_E0227
986        if(m_pcRateCtrl->getLayerID() != 0)
987        {
988          list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
989          lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambdaIV( listPreviousPicture, pcSlice->getPOC() );
990          sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
991        }
992        else
993        {
994#endif
995        list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
996#if RATE_CONTROL_INTRA
997        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture, pcSlice->getSliceType());
998#else
999        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture );
1000#endif
1001        sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
1002#if KWU_RC_MADPRED_E0227
1003        }
1004#endif
1005      }
1006
1007      sliceQP = Clip3( -pcSlice->getSPS()->getQpBDOffsetY(), MAX_QP, sliceQP );
1008      m_pcRateCtrl->getRCPic()->setPicEstQP( sliceQP );
1009
1010      m_pcSliceEncoder->resetQP( pcPic, sliceQP, lambda );
1011    }
1012#endif
1013
1014    UInt uiNumSlices = 1;
1015
1016    UInt uiInternalAddress = pcPic->getNumPartInCU()-4;
1017    UInt uiExternalAddress = pcPic->getPicSym()->getNumberOfCUsInFrame()-1;
1018    UInt uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
1019    UInt uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
1020    UInt uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
1021    UInt uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
1022    while(uiPosX>=uiWidth||uiPosY>=uiHeight) 
1023    {
1024      uiInternalAddress--;
1025      uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
1026      uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
1027    }
1028    uiInternalAddress++;
1029    if(uiInternalAddress==pcPic->getNumPartInCU()) 
1030    {
1031      uiInternalAddress = 0;
1032      uiExternalAddress++;
1033    }
1034    UInt uiRealEndAddress = uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress;
1035
1036    UInt uiCummulativeTileWidth;
1037    UInt uiCummulativeTileHeight;
1038    Int  p, j;
1039    UInt uiEncCUAddr;
1040
1041    //set NumColumnsMinus1 and NumRowsMinus1
1042    pcPic->getPicSym()->setNumColumnsMinus1( pcSlice->getPPS()->getNumColumnsMinus1() );
1043    pcPic->getPicSym()->setNumRowsMinus1( pcSlice->getPPS()->getNumRowsMinus1() );
1044
1045    //create the TComTileArray
1046    pcPic->getPicSym()->xCreateTComTileArray();
1047
1048    if( pcSlice->getPPS()->getUniformSpacingFlag() == 1 )
1049    {
1050      //set the width for each tile
1051      for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
1052      {
1053        for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1()+1; p++)
1054        {
1055          pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->
1056            setTileWidth( (p+1)*pcPic->getPicSym()->getFrameWidthInCU()/(pcPic->getPicSym()->getNumColumnsMinus1()+1) 
1057            - (p*pcPic->getPicSym()->getFrameWidthInCU())/(pcPic->getPicSym()->getNumColumnsMinus1()+1) );
1058        }
1059      }
1060
1061      //set the height for each tile
1062      for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
1063      {
1064        for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1()+1; p++)
1065        {
1066          pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->
1067            setTileHeight( (p+1)*pcPic->getPicSym()->getFrameHeightInCU()/(pcPic->getPicSym()->getNumRowsMinus1()+1) 
1068            - (p*pcPic->getPicSym()->getFrameHeightInCU())/(pcPic->getPicSym()->getNumRowsMinus1()+1) );   
1069        }
1070      }
1071    }
1072    else
1073    {
1074      //set the width for each tile
1075      for(j=0; j < pcPic->getPicSym()->getNumRowsMinus1()+1; j++)
1076      {
1077        uiCummulativeTileWidth = 0;
1078        for(p=0; p < pcPic->getPicSym()->getNumColumnsMinus1(); p++)
1079        {
1080          pcPic->getPicSym()->getTComTile( j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p )->setTileWidth( pcSlice->getPPS()->getColumnWidth(p) );
1081          uiCummulativeTileWidth += pcSlice->getPPS()->getColumnWidth(p);
1082        }
1083        pcPic->getPicSym()->getTComTile(j * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + p)->setTileWidth( pcPic->getPicSym()->getFrameWidthInCU()-uiCummulativeTileWidth );
1084      }
1085
1086      //set the height for each tile
1087      for(j=0; j < pcPic->getPicSym()->getNumColumnsMinus1()+1; j++)
1088      {
1089        uiCummulativeTileHeight = 0;
1090        for(p=0; p < pcPic->getPicSym()->getNumRowsMinus1(); p++)
1091        {
1092          pcPic->getPicSym()->getTComTile( p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j )->setTileHeight( pcSlice->getPPS()->getRowHeight(p) );
1093          uiCummulativeTileHeight += pcSlice->getPPS()->getRowHeight(p);
1094        }
1095        pcPic->getPicSym()->getTComTile(p * (pcPic->getPicSym()->getNumColumnsMinus1()+1) + j)->setTileHeight( pcPic->getPicSym()->getFrameHeightInCU()-uiCummulativeTileHeight );
1096      }
1097    }
1098    //intialize each tile of the current picture
1099    pcPic->getPicSym()->xInitTiles();
1100
1101    // Allocate some coders, now we know how many tiles there are.
1102    Int iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
1103
1104    //generate the Coding Order Map and Inverse Coding Order Map
1105    for(p=0, uiEncCUAddr=0; p<pcPic->getPicSym()->getNumberOfCUsInFrame(); p++, uiEncCUAddr = pcPic->getPicSym()->xCalculateNxtCUAddr(uiEncCUAddr))
1106    {
1107      pcPic->getPicSym()->setCUOrderMap(p, uiEncCUAddr);
1108      pcPic->getPicSym()->setInverseCUOrderMap(uiEncCUAddr, p);
1109    }
1110    pcPic->getPicSym()->setCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());   
1111    pcPic->getPicSym()->setInverseCUOrderMap(pcPic->getPicSym()->getNumberOfCUsInFrame(), pcPic->getPicSym()->getNumberOfCUsInFrame());
1112
1113    // Allocate some coders, now we know how many tiles there are.
1114    m_pcEncTop->createWPPCoders(iNumSubstreams);
1115    pcSbacCoders = m_pcEncTop->getSbacCoders();
1116    pcSubstreamsOut = new TComOutputBitstream[iNumSubstreams];
1117
1118    UInt startCUAddrSliceIdx = 0; // used to index "m_uiStoredStartCUAddrForEncodingSlice" containing locations of slice boundaries
1119    UInt startCUAddrSlice    = 0; // used to keep track of current slice's starting CU addr.
1120    pcSlice->setSliceCurStartCUAddr( startCUAddrSlice ); // Setting "start CU addr" for current slice
1121    m_storedStartCUAddrForEncodingSlice.clear();
1122
1123    UInt startCUAddrSliceSegmentIdx = 0; // used to index "m_uiStoredStartCUAddrForEntropyEncodingSlice" containing locations of slice boundaries
1124    UInt startCUAddrSliceSegment    = 0; // used to keep track of current Dependent slice's starting CU addr.
1125    pcSlice->setSliceSegmentCurStartCUAddr( startCUAddrSliceSegment ); // Setting "start CU addr" for current Dependent slice
1126
1127    m_storedStartCUAddrForEncodingSliceSegment.clear();
1128    UInt nextCUAddr = 0;
1129    m_storedStartCUAddrForEncodingSlice.push_back (nextCUAddr);
1130    startCUAddrSliceIdx++;
1131    m_storedStartCUAddrForEncodingSliceSegment.push_back(nextCUAddr);
1132    startCUAddrSliceSegmentIdx++;
1133#if H_3D_NBDV
1134      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.
1135      {
1136        Int iColPoc = pcSlice->getRefPOC(RefPicList(1-pcSlice->getColFromL0Flag()), pcSlice->getColRefIdx());
1137        pcPic->setNumDdvCandPics(pcPic->getDisCandRefPictures(iColPoc));
1138      }
1139#endif
1140#if H_3D
1141      pcSlice->setDepthToDisparityLUTs(); 
1142
1143#endif
1144
1145#if H_3D_NBDV
1146      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.
1147      {
1148        pcPic->checkTemporalIVRef();
1149      }
1150
1151      if(pcSlice->getIsDepth())
1152      {
1153        pcPic->checkTextureRef();
1154      }
1155#endif
1156    while(nextCUAddr<uiRealEndAddress) // determine slice boundaries
1157    {
1158      pcSlice->setNextSlice       ( false );
1159      pcSlice->setNextSliceSegment( false );
1160      assert(pcPic->getNumAllocatedSlice() == startCUAddrSliceIdx);
1161      m_pcSliceEncoder->precompressSlice( pcPic );
1162      m_pcSliceEncoder->compressSlice   ( pcPic );
1163
1164      Bool bNoBinBitConstraintViolated = (!pcSlice->isNextSlice() && !pcSlice->isNextSliceSegment());
1165      if (pcSlice->isNextSlice() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_LCU))
1166      {
1167        startCUAddrSlice = pcSlice->getSliceCurEndCUAddr();
1168        // Reconstruction slice
1169        m_storedStartCUAddrForEncodingSlice.push_back(startCUAddrSlice);
1170        startCUAddrSliceIdx++;
1171        // Dependent slice
1172        if (startCUAddrSliceSegmentIdx>0 && m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx-1] != startCUAddrSlice)
1173        {
1174          m_storedStartCUAddrForEncodingSliceSegment.push_back(startCUAddrSlice);
1175          startCUAddrSliceSegmentIdx++;
1176        }
1177
1178        if (startCUAddrSlice < uiRealEndAddress)
1179        {
1180          pcPic->allocateNewSlice();         
1181          pcPic->setCurrSliceIdx                  ( startCUAddrSliceIdx-1 );
1182          m_pcSliceEncoder->setSliceIdx           ( startCUAddrSliceIdx-1 );
1183          pcSlice = pcPic->getSlice               ( startCUAddrSliceIdx-1 );
1184          pcSlice->copySliceInfo                  ( pcPic->getSlice(0)      );
1185          pcSlice->setSliceIdx                    ( startCUAddrSliceIdx-1 );
1186          pcSlice->setSliceCurStartCUAddr         ( startCUAddrSlice      );
1187          pcSlice->setSliceSegmentCurStartCUAddr  ( startCUAddrSlice      );
1188          pcSlice->setSliceBits(0);
1189          uiNumSlices ++;
1190        }
1191      }
1192      else if (pcSlice->isNextSliceSegment() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_LCU))
1193      {
1194        startCUAddrSliceSegment                                                     = pcSlice->getSliceSegmentCurEndCUAddr();
1195        m_storedStartCUAddrForEncodingSliceSegment.push_back(startCUAddrSliceSegment);
1196        startCUAddrSliceSegmentIdx++;
1197        pcSlice->setSliceSegmentCurStartCUAddr( startCUAddrSliceSegment );
1198      }
1199      else
1200      {
1201        startCUAddrSlice                                                            = pcSlice->getSliceCurEndCUAddr();
1202        startCUAddrSliceSegment                                                     = pcSlice->getSliceSegmentCurEndCUAddr();
1203      }       
1204
1205      nextCUAddr = (startCUAddrSlice > startCUAddrSliceSegment) ? startCUAddrSlice : startCUAddrSliceSegment;
1206    }
1207    m_storedStartCUAddrForEncodingSlice.push_back( pcSlice->getSliceCurEndCUAddr());
1208    startCUAddrSliceIdx++;
1209    m_storedStartCUAddrForEncodingSliceSegment.push_back(pcSlice->getSliceCurEndCUAddr());
1210    startCUAddrSliceSegmentIdx++;
1211
1212    pcSlice = pcPic->getSlice(0);
1213
1214    // SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
1215    if( m_pcCfg->getSaoLcuBasedOptimization() && m_pcCfg->getSaoLcuBoundary() )
1216    {
1217      m_pcSAO->resetStats();
1218      m_pcSAO->calcSaoStatsCu_BeforeDblk( pcPic );
1219    }
1220
1221    //-- Loop filter
1222    Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
1223    m_pcLoopFilter->setCfg(bLFCrossTileBoundary);
1224    if ( m_pcCfg->getDeblockingFilterMetric() )
1225    {
1226      dblMetric(pcPic, uiNumSlices);
1227    }
1228    m_pcLoopFilter->loopFilterPic( pcPic );
1229
1230    pcSlice = pcPic->getSlice(0);
1231    if(pcSlice->getSPS()->getUseSAO())
1232    {
1233      std::vector<Bool> LFCrossSliceBoundaryFlag;
1234      for(Int s=0; s< uiNumSlices; s++)
1235      {
1236        LFCrossSliceBoundaryFlag.push_back(  ((uiNumSlices==1)?true:pcPic->getSlice(s)->getLFCrossSliceBoundaryFlag()) );
1237      }
1238      m_storedStartCUAddrForEncodingSlice.resize(uiNumSlices+1);
1239      pcPic->createNonDBFilterInfo(m_storedStartCUAddrForEncodingSlice, 0, &LFCrossSliceBoundaryFlag ,pcPic->getPicSym()->getNumTiles() ,bLFCrossTileBoundary);
1240    }
1241
1242
1243    pcSlice = pcPic->getSlice(0);
1244
1245    if(pcSlice->getSPS()->getUseSAO())
1246    {
1247      m_pcSAO->createPicSaoInfo(pcPic);
1248    }
1249
1250    /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
1251    // Set entropy coder
1252    m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
1253
1254    /* write various header sets. */
1255    if ( m_bSeqFirst )
1256    {
1257      OutputNALUnit nalu(NAL_UNIT_VPS);
1258#if H_MV
1259      if( getLayerId() == 0 )
1260      {
1261#endif
1262      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1263      m_pcEntropyCoder->encodeVPS(m_pcEncTop->getVPS());
1264      writeRBSPTrailingBits(nalu.m_Bitstream);
1265      accessUnit.push_back(new NALUnitEBSP(nalu));
1266#if RATE_CONTROL_LAMBDA_DOMAIN
1267      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
1268#endif
1269
1270#if H_MV
1271      }
1272      nalu = NALUnit(NAL_UNIT_SPS, 0, getLayerId());
1273#else
1274      nalu = NALUnit(NAL_UNIT_SPS);
1275#endif
1276      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1277      if (m_bSeqFirst)
1278      {
1279        pcSlice->getSPS()->setNumLongTermRefPicSPS(m_numLongTermRefPicSPS);
1280        for (Int k = 0; k < m_numLongTermRefPicSPS; k++)
1281        {
1282          pcSlice->getSPS()->setLtRefPicPocLsbSps(k, m_ltRefPicPocLsbSps[k]);
1283          pcSlice->getSPS()->setUsedByCurrPicLtSPSFlag(k, m_ltRefPicUsedByCurrPicFlag[k]);
1284        }
1285      }
1286      if( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() )
1287      {
1288        UInt maxCU = m_pcCfg->getSliceArgument() >> ( pcSlice->getSPS()->getMaxCUDepth() << 1);
1289        UInt numDU = ( m_pcCfg->getSliceMode() == 1 ) ? ( pcPic->getNumCUsInFrame() / maxCU ) : ( 0 );
1290        if( pcPic->getNumCUsInFrame() % maxCU != 0 || numDU == 0 )
1291        {
1292          numDU ++;
1293        }
1294        pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->setNumDU( numDU );
1295        pcSlice->getSPS()->setHrdParameters( m_pcCfg->getFrameRate(), numDU, m_pcCfg->getTargetBitrate(), ( m_pcCfg->getIntraPeriod() > 0 ) );
1296      }
1297      if( m_pcCfg->getBufferingPeriodSEIEnabled() || m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() )
1298      {
1299        pcSlice->getSPS()->getVuiParameters()->setHrdParametersPresentFlag( true );
1300      }
1301#if !H_3D
1302      m_pcEntropyCoder->encodeSPS(pcSlice->getSPS());
1303#else
1304      m_pcEntropyCoder->encodeSPS(pcSlice->getSPS(), pcSlice->getViewIndex(), pcSlice->getIsDepth() );
1305#endif
1306      writeRBSPTrailingBits(nalu.m_Bitstream);
1307      accessUnit.push_back(new NALUnitEBSP(nalu));
1308#if RATE_CONTROL_LAMBDA_DOMAIN
1309      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
1310#endif
1311
1312#if H_MV
1313      nalu = NALUnit(NAL_UNIT_PPS, 0, getLayerId());
1314#else
1315      nalu = NALUnit(NAL_UNIT_PPS);
1316#endif
1317#if PPS_FIX_DEPTH
1318      if(!pcSlice->getIsDepth() || !pcSlice->getViewIndex() )
1319      {
1320#endif
1321      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1322      m_pcEntropyCoder->encodePPS(pcSlice->getPPS());
1323      writeRBSPTrailingBits(nalu.m_Bitstream);
1324      accessUnit.push_back(new NALUnitEBSP(nalu));
1325#if RATE_CONTROL_LAMBDA_DOMAIN
1326      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
1327#endif
1328#if PPS_FIX_DEPTH
1329      }
1330#endif
1331      xCreateLeadingSEIMessages(accessUnit, pcSlice->getSPS());
1332
1333      m_bSeqFirst = false;
1334    }
1335
1336    if (writeSOP) // write SOP description SEI (if enabled) at the beginning of GOP
1337    {
1338      Int SOPcurrPOC = pocCurr;
1339
1340      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
1341      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1342      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1343
1344      SEISOPDescription SOPDescriptionSEI;
1345      SOPDescriptionSEI.m_sopSeqParameterSetId = pcSlice->getSPS()->getSPSId();
1346
1347      UInt i = 0;
1348      UInt prevEntryId = iGOPid;
1349      for (j = iGOPid; j < m_iGopSize; j++)
1350      {
1351        Int deltaPOC = m_pcCfg->getGOPEntry(j).m_POC - m_pcCfg->getGOPEntry(prevEntryId).m_POC;
1352        if ((SOPcurrPOC + deltaPOC) < m_pcCfg->getFramesToBeEncoded())
1353        {
1354          SOPcurrPOC += deltaPOC;
1355          SOPDescriptionSEI.m_sopDescVclNaluType[i] = getNalUnitType(SOPcurrPOC, m_iLastIDR);
1356          SOPDescriptionSEI.m_sopDescTemporalId[i] = m_pcCfg->getGOPEntry(j).m_temporalId;
1357          SOPDescriptionSEI.m_sopDescStRpsIdx[i] = m_pcEncTop->getReferencePictureSetIdxForSOP(pcSlice, SOPcurrPOC, j);
1358          SOPDescriptionSEI.m_sopDescPocDelta[i] = deltaPOC;
1359
1360          prevEntryId = j;
1361          i++;
1362        }
1363      }
1364
1365      SOPDescriptionSEI.m_numPicsInSopMinus1 = i - 1;
1366
1367      m_seiWriter.writeSEImessage( nalu.m_Bitstream, SOPDescriptionSEI, pcSlice->getSPS());
1368      writeRBSPTrailingBits(nalu.m_Bitstream);
1369      accessUnit.push_back(new NALUnitEBSP(nalu));
1370
1371      writeSOP = false;
1372    }
1373
1374    if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
1375        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
1376        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
1377       || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
1378    {
1379      if( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() )
1380      {
1381        UInt numDU = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNumDU();
1382        pictureTimingSEI.m_numDecodingUnitsMinus1     = ( numDU - 1 );
1383        pictureTimingSEI.m_duCommonCpbRemovalDelayFlag = false;
1384
1385        if( pictureTimingSEI.m_numNalusInDuMinus1 == NULL )
1386        {
1387          pictureTimingSEI.m_numNalusInDuMinus1       = new UInt[ numDU ];
1388        }
1389        if( pictureTimingSEI.m_duCpbRemovalDelayMinus1  == NULL )
1390        {
1391          pictureTimingSEI.m_duCpbRemovalDelayMinus1  = new UInt[ numDU ];
1392        }
1393        if( accumBitsDU == NULL )
1394        {
1395          accumBitsDU                                  = new UInt[ numDU ];
1396        }
1397        if( accumNalsDU == NULL )
1398        {
1399          accumNalsDU                                  = new UInt[ numDU ];
1400        }
1401      }
1402      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 .
1403      pictureTimingSEI.m_picDpbOutputDelay = pcSlice->getSPS()->getNumReorderPics(0) + pcSlice->getPOC() - m_totalCoded;
1404      Int factor = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2;
1405      pictureTimingSEI.m_picDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
1406      if( m_pcCfg->getDecodingUnitInfoSEIEnabled() )
1407      {
1408        picSptDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
1409      }
1410    }
1411
1412    if( ( m_pcCfg->getBufferingPeriodSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) &&
1413        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) && 
1414        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
1415       || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
1416    {
1417      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
1418      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1419      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1420
1421      SEIBufferingPeriod sei_buffering_period;
1422     
1423      UInt uiInitialCpbRemovalDelay = (90000/2);                      // 0.5 sec
1424      sei_buffering_period.m_initialCpbRemovalDelay      [0][0]     = uiInitialCpbRemovalDelay;
1425      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][0]     = uiInitialCpbRemovalDelay;
1426      sei_buffering_period.m_initialCpbRemovalDelay      [0][1]     = uiInitialCpbRemovalDelay;
1427      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][1]     = uiInitialCpbRemovalDelay;
1428
1429      Double dTmp = (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getNumUnitsInTick() / (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getTimeScale();
1430
1431      UInt uiTmp = (UInt)( dTmp * 90000.0 ); 
1432      uiInitialCpbRemovalDelay -= uiTmp;
1433      uiInitialCpbRemovalDelay -= uiTmp / ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2 );
1434      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][0]  = uiInitialCpbRemovalDelay;
1435      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][0]  = uiInitialCpbRemovalDelay;
1436      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][1]  = uiInitialCpbRemovalDelay;
1437      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][1]  = uiInitialCpbRemovalDelay;
1438
1439      sei_buffering_period.m_rapCpbParamsPresentFlag              = 0;
1440      //for the concatenation, it can be set to one during splicing.
1441      sei_buffering_period.m_concatenationFlag = 0;
1442      //since the temporal layer HRD is not ready, we assumed it is fixed
1443      sei_buffering_period.m_auCpbRemovalDelayDelta = 1;
1444      sei_buffering_period.m_cpbDelayOffset = 0;
1445      sei_buffering_period.m_dpbDelayOffset = 0;
1446
1447      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_buffering_period, pcSlice->getSPS());
1448      writeRBSPTrailingBits(nalu.m_Bitstream);
1449      {
1450      UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
1451      UInt offsetPosition = m_activeParameterSetSEIPresentInAU;   // Insert BP SEI after APS SEI
1452      AccessUnit::iterator it;
1453      for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
1454      {
1455        it++;
1456      }
1457      accessUnit.insert(it, new NALUnitEBSP(nalu));
1458      m_bufferingPeriodSEIPresentInAU = true;
1459      }
1460
1461      if (m_pcCfg->getScalableNestingSEIEnabled())
1462      {
1463        OutputNALUnit naluTmp(NAL_UNIT_PREFIX_SEI);
1464        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1465        m_pcEntropyCoder->setBitstream(&naluTmp.m_Bitstream);
1466        scalableNestingSEI.m_nestedSEIs.clear();
1467        scalableNestingSEI.m_nestedSEIs.push_back(&sei_buffering_period);
1468        m_seiWriter.writeSEImessage( naluTmp.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
1469        writeRBSPTrailingBits(naluTmp.m_Bitstream);
1470        UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
1471        UInt offsetPosition = m_activeParameterSetSEIPresentInAU + m_bufferingPeriodSEIPresentInAU + m_pictureTimingSEIPresentInAU;   // Insert BP SEI after non-nested APS, BP and PT SEIs
1472        AccessUnit::iterator it;
1473        for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
1474        {
1475          it++;
1476        }
1477        accessUnit.insert(it, new NALUnitEBSP(naluTmp));
1478        m_nestedBufferingPeriodSEIPresentInAU = true;
1479      }
1480
1481      m_lastBPSEI = m_totalCoded;
1482      m_cpbRemovalDelay = 0;
1483    }
1484    m_cpbRemovalDelay ++;
1485    if( ( m_pcEncTop->getRecoveryPointSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) )
1486    {
1487      if( m_pcEncTop->getGradualDecodingRefreshInfoEnabled() && !pcSlice->getRapPicFlag() )
1488      {
1489        // Gradual decoding refresh SEI
1490        OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
1491        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1492        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1493
1494        SEIGradualDecodingRefreshInfo seiGradualDecodingRefreshInfo;
1495        seiGradualDecodingRefreshInfo.m_gdrForegroundFlag = true; // Indicating all "foreground"
1496
1497        m_seiWriter.writeSEImessage( nalu.m_Bitstream, seiGradualDecodingRefreshInfo, pcSlice->getSPS() );
1498        writeRBSPTrailingBits(nalu.m_Bitstream);
1499        accessUnit.push_back(new NALUnitEBSP(nalu));
1500      }
1501    // Recovery point SEI
1502      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
1503      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1504      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1505
1506      SEIRecoveryPoint sei_recovery_point;
1507      sei_recovery_point.m_recoveryPocCnt    = 0;
1508      sei_recovery_point.m_exactMatchingFlag = ( pcSlice->getPOC() == 0 ) ? (true) : (false);
1509      sei_recovery_point.m_brokenLinkFlag    = false;
1510
1511      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_recovery_point, pcSlice->getSPS() );
1512      writeRBSPTrailingBits(nalu.m_Bitstream);
1513      accessUnit.push_back(new NALUnitEBSP(nalu));
1514    }
1515
1516    /* use the main bitstream buffer for storing the marshalled picture */
1517    m_pcEntropyCoder->setBitstream(NULL);
1518
1519    startCUAddrSliceIdx = 0;
1520    startCUAddrSlice    = 0; 
1521
1522    startCUAddrSliceSegmentIdx = 0;
1523    startCUAddrSliceSegment    = 0; 
1524    nextCUAddr                 = 0;
1525    pcSlice = pcPic->getSlice(startCUAddrSliceIdx);
1526
1527    Int processingState = (pcSlice->getSPS()->getUseSAO())?(EXECUTE_INLOOPFILTER):(ENCODE_SLICE);
1528    Bool skippedSlice=false;
1529    while (nextCUAddr < uiRealEndAddress) // Iterate over all slices
1530    {
1531      switch(processingState)
1532      {
1533      case ENCODE_SLICE:
1534        {
1535          pcSlice->setNextSlice       ( false );
1536          pcSlice->setNextSliceSegment( false );
1537          if (nextCUAddr == m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx])
1538          {
1539            pcSlice = pcPic->getSlice(startCUAddrSliceIdx);
1540            if(startCUAddrSliceIdx > 0 && pcSlice->getSliceType()!= I_SLICE)
1541            {
1542              pcSlice->checkColRefIdx(startCUAddrSliceIdx, pcPic);
1543            }
1544            pcPic->setCurrSliceIdx(startCUAddrSliceIdx);
1545            m_pcSliceEncoder->setSliceIdx(startCUAddrSliceIdx);
1546            assert(startCUAddrSliceIdx == pcSlice->getSliceIdx());
1547            // Reconstruction slice
1548            pcSlice->setSliceCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
1549            pcSlice->setSliceCurEndCUAddr  ( m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx+1 ] );
1550            // Dependent slice
1551            pcSlice->setSliceSegmentCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
1552            pcSlice->setSliceSegmentCurEndCUAddr  ( m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx+1 ] );
1553
1554            pcSlice->setNextSlice       ( true );
1555
1556            startCUAddrSliceIdx++;
1557            startCUAddrSliceSegmentIdx++;
1558          } 
1559          else if (nextCUAddr == m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx])
1560          {
1561            // Dependent slice
1562            pcSlice->setSliceSegmentCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
1563            pcSlice->setSliceSegmentCurEndCUAddr  ( m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx+1 ] );
1564
1565            pcSlice->setNextSliceSegment( true );
1566
1567            startCUAddrSliceSegmentIdx++;
1568          }
1569
1570          pcSlice->setRPS(pcPic->getSlice(0)->getRPS());
1571          pcSlice->setRPSidx(pcPic->getSlice(0)->getRPSidx());
1572          UInt uiDummyStartCUAddr;
1573          UInt uiDummyBoundingCUAddr;
1574          m_pcSliceEncoder->xDetermineStartAndBoundingCUAddr(uiDummyStartCUAddr,uiDummyBoundingCUAddr,pcPic,true);
1575
1576          uiInternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) % pcPic->getNumPartInCU();
1577          uiExternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) / pcPic->getNumPartInCU();
1578          uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
1579          uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
1580          uiWidth = pcSlice->getSPS()->getPicWidthInLumaSamples();
1581          uiHeight = pcSlice->getSPS()->getPicHeightInLumaSamples();
1582          while(uiPosX>=uiWidth||uiPosY>=uiHeight)
1583          {
1584            uiInternalAddress--;
1585            uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
1586            uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
1587          }
1588          uiInternalAddress++;
1589          if(uiInternalAddress==pcPic->getNumPartInCU())
1590          {
1591            uiInternalAddress = 0;
1592            uiExternalAddress = pcPic->getPicSym()->getCUOrderMap(pcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
1593          }
1594          UInt endAddress = pcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress);
1595          if(endAddress<=pcSlice->getSliceSegmentCurStartCUAddr()) 
1596          {
1597            UInt boundingAddrSlice, boundingAddrSliceSegment;
1598            boundingAddrSlice          = m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx];         
1599            boundingAddrSliceSegment = m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx];         
1600            nextCUAddr               = min(boundingAddrSlice, boundingAddrSliceSegment);
1601            if(pcSlice->isNextSlice())
1602            {
1603              skippedSlice=true;
1604            }
1605            continue;
1606          }
1607          if(skippedSlice) 
1608          {
1609            pcSlice->setNextSlice       ( true );
1610            pcSlice->setNextSliceSegment( false );
1611          }
1612          skippedSlice=false;
1613          pcSlice->allocSubstreamSizes( iNumSubstreams );
1614          for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
1615          {
1616            pcSubstreamsOut[ui].clear();
1617          }
1618
1619          m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
1620          m_pcEntropyCoder->resetEntropy      ();
1621          /* start slice NALunit */
1622#if H_MV
1623          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer(), getLayerId() );
1624#else
1625          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer() );
1626#endif
1627          Bool sliceSegment = (!pcSlice->isNextSlice());
1628          if (!sliceSegment)
1629          {
1630            uiOneBitstreamPerSliceLength = 0; // start of a new slice
1631          }
1632          m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1633#if RATE_CONTROL_LAMBDA_DOMAIN
1634          tmpBitsBeforeWriting = m_pcEntropyCoder->getNumberOfWrittenBits();
1635#endif
1636          m_pcEntropyCoder->encodeSliceHeader(pcSlice);
1637#if RATE_CONTROL_LAMBDA_DOMAIN
1638          actualHeadBits += ( m_pcEntropyCoder->getNumberOfWrittenBits() - tmpBitsBeforeWriting );
1639#endif
1640
1641          // is it needed?
1642          {
1643            if (!sliceSegment)
1644            {
1645              pcBitstreamRedirect->writeAlignOne();
1646            }
1647            else
1648            {
1649              // We've not completed our slice header info yet, do the alignment later.
1650            }
1651            m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
1652            m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
1653            m_pcEntropyCoder->resetEntropy    ();
1654            for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams() ; ui++ )
1655            {
1656              m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[ui], pcSlice );
1657              m_pcEntropyCoder->resetEntropy    ();
1658            }
1659          }
1660
1661          if(pcSlice->isNextSlice())
1662          {
1663            // set entropy coder for writing
1664            m_pcSbacCoder->init( (TEncBinIf*)m_pcBinCABAC );
1665            {
1666              for ( UInt ui = 0 ; ui < pcSlice->getPPS()->getNumSubstreams() ; ui++ )
1667              {
1668                m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[ui], pcSlice );
1669                m_pcEntropyCoder->resetEntropy    ();
1670              }
1671              pcSbacCoders[0].load(m_pcSbacCoder);
1672              m_pcEntropyCoder->setEntropyCoder ( &pcSbacCoders[0], pcSlice );  //ALF is written in substream #0 with CABAC coder #0 (see ALF param encoding below)
1673            }
1674            m_pcEntropyCoder->resetEntropy    ();
1675            // File writing
1676            if (!sliceSegment)
1677            {
1678              m_pcEntropyCoder->setBitstream(pcBitstreamRedirect);
1679            }
1680            else
1681            {
1682              m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1683            }
1684            // for now, override the TILES_DECODER setting in order to write substreams.
1685            m_pcEntropyCoder->setBitstream    ( &pcSubstreamsOut[0] );
1686
1687          }
1688          pcSlice->setFinalized(true);
1689
1690          m_pcSbacCoder->load( &pcSbacCoders[0] );
1691
1692          pcSlice->setTileOffstForMultES( uiOneBitstreamPerSliceLength );
1693            pcSlice->setTileLocationCount ( 0 );
1694          m_pcSliceEncoder->encodeSlice(pcPic, pcSubstreamsOut);
1695
1696          {
1697            // Construct the final bitstream by flushing and concatenating substreams.
1698            // The final bitstream is either nalu.m_Bitstream or pcBitstreamRedirect;
1699            UInt* puiSubstreamSizes = pcSlice->getSubstreamSizes();
1700            UInt uiTotalCodedSize = 0; // for padding calcs.
1701            UInt uiNumSubstreamsPerTile = iNumSubstreams;
1702            if (iNumSubstreams > 1)
1703            {
1704              uiNumSubstreamsPerTile /= pcPic->getPicSym()->getNumTiles();
1705            }
1706            for ( UInt ui = 0 ; ui < iNumSubstreams; ui++ )
1707            {
1708              // Flush all substreams -- this includes empty ones.
1709              // Terminating bit and flush.
1710              m_pcEntropyCoder->setEntropyCoder   ( &pcSbacCoders[ui], pcSlice );
1711              m_pcEntropyCoder->setBitstream      (  &pcSubstreamsOut[ui] );
1712              m_pcEntropyCoder->encodeTerminatingBit( 1 );
1713              m_pcEntropyCoder->encodeSliceFinish();
1714
1715              pcSubstreamsOut[ui].writeByteAlignment();   // Byte-alignment in slice_data() at end of sub-stream
1716              // Byte alignment is necessary between tiles when tiles are independent.
1717              uiTotalCodedSize += pcSubstreamsOut[ui].getNumberOfWrittenBits();
1718
1719              Bool bNextSubstreamInNewTile = ((ui+1) < iNumSubstreams)&& ((ui+1)%uiNumSubstreamsPerTile == 0);
1720              if (bNextSubstreamInNewTile)
1721              {
1722                pcSlice->setTileLocation(ui/uiNumSubstreamsPerTile, pcSlice->getTileOffstForMultES()+(uiTotalCodedSize>>3));
1723              }
1724              if (ui+1 < pcSlice->getPPS()->getNumSubstreams())
1725              {
1726                puiSubstreamSizes[ui] = pcSubstreamsOut[ui].getNumberOfWrittenBits() + (pcSubstreamsOut[ui].countStartCodeEmulations()<<3);
1727              }
1728            }
1729
1730            // Complete the slice header info.
1731            m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice );
1732            m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
1733            m_pcEntropyCoder->encodeTilesWPPEntryPoint( pcSlice );
1734
1735            // Substreams...
1736            TComOutputBitstream *pcOut = pcBitstreamRedirect;
1737          Int offs = 0;
1738          Int nss = pcSlice->getPPS()->getNumSubstreams();
1739          if (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
1740          {
1741            // 1st line present for WPP.
1742            offs = pcSlice->getSliceSegmentCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU()/pcSlice->getPic()->getFrameWidthInCU();
1743            nss  = pcSlice->getNumEntryPointOffsets()+1;
1744          }
1745          for ( UInt ui = 0 ; ui < nss; ui++ )
1746          {
1747            pcOut->addSubstream(&pcSubstreamsOut[ui+offs]);
1748            }
1749          }
1750
1751          UInt boundingAddrSlice, boundingAddrSliceSegment;
1752          boundingAddrSlice        = m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx];         
1753          boundingAddrSliceSegment = m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx];         
1754          nextCUAddr               = min(boundingAddrSlice, boundingAddrSliceSegment);
1755          // If current NALU is the first NALU of slice (containing slice header) and more NALUs exist (due to multiple dependent slices) then buffer it.
1756          // 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.
1757          Bool bNALUAlignedWrittenToList    = false; // used to ensure current NALU is not written more than once to the NALU list.
1758          xAttachSliceDataToNalUnit(nalu, pcBitstreamRedirect);
1759          accessUnit.push_back(new NALUnitEBSP(nalu));
1760#if RATE_CONTROL_LAMBDA_DOMAIN
1761          actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
1762#endif
1763          bNALUAlignedWrittenToList = true; 
1764          uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits(); // length of bitstream after byte-alignment
1765
1766          if (!bNALUAlignedWrittenToList)
1767          {
1768            {
1769              nalu.m_Bitstream.writeAlignZero();
1770            }
1771            accessUnit.push_back(new NALUnitEBSP(nalu));
1772            uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits() + 24; // length of bitstream after byte-alignment + 3 byte startcode 0x000001
1773          }
1774
1775          if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
1776              ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
1777              ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
1778             || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) &&
1779              ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() ) )
1780          {
1781              UInt numNalus = 0;
1782            UInt numRBSPBytes = 0;
1783            for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
1784            {
1785              UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
1786              if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
1787              {
1788                numRBSPBytes += numRBSPBytes_nal;
1789                numNalus ++;
1790              }
1791            }
1792            accumBitsDU[ pcSlice->getSliceIdx() ] = ( numRBSPBytes << 3 );
1793            accumNalsDU[ pcSlice->getSliceIdx() ] = numNalus;   // SEI not counted for bit count; hence shouldn't be counted for # of NALUs - only for consistency
1794          }
1795          processingState = ENCODE_SLICE;
1796          }
1797          break;
1798        case EXECUTE_INLOOPFILTER:
1799          {
1800            // set entropy coder for RD
1801            m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
1802            if ( pcSlice->getSPS()->getUseSAO() )
1803            {
1804              m_pcEntropyCoder->resetEntropy();
1805              m_pcEntropyCoder->setBitstream( m_pcBitCounter );
1806              m_pcSAO->startSaoEnc(pcPic, m_pcEntropyCoder, m_pcEncTop->getRDSbacCoder(), m_pcEncTop->getRDGoOnSbacCoder());
1807              SAOParam& cSaoParam = *pcSlice->getPic()->getPicSym()->getSaoParam();
1808
1809#if SAO_CHROMA_LAMBDA
1810#if SAO_ENCODING_CHOICE
1811              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma(), pcPic->getSlice(0)->getDepth());
1812#else
1813              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma());
1814#endif
1815#else
1816              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambda());
1817#endif
1818              m_pcSAO->endSaoEnc();
1819              m_pcSAO->PCMLFDisableProcess(pcPic);
1820            }
1821#if SAO_RDO
1822            m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
1823#endif
1824            processingState = ENCODE_SLICE;
1825
1826            for(Int s=0; s< uiNumSlices; s++)
1827            {
1828              if (pcSlice->getSPS()->getUseSAO())
1829              {
1830                pcPic->getSlice(s)->setSaoEnabledFlag((pcSlice->getPic()->getPicSym()->getSaoParam()->bSaoFlag[0]==1)?true:false);
1831              }
1832            }
1833          }
1834          break;
1835        default:
1836          {
1837            printf("Not a supported encoding state\n");
1838            assert(0);
1839            exit(-1);
1840          }
1841        }
1842      } // end iteration over slices
1843
1844      if(pcSlice->getSPS()->getUseSAO())
1845      {
1846        if(pcSlice->getSPS()->getUseSAO())
1847        {
1848          m_pcSAO->destroyPicSaoInfo();
1849        }
1850        pcPic->destroyNonDBFilterInfo();
1851      }
1852#if H_3D
1853      pcPic->compressMotion(2); 
1854#endif
1855#if !H_3D
1856      pcPic->compressMotion(); 
1857#endif
1858#if H_MV
1859      m_pocLastCoded = pcPic->getPOC();
1860#endif
1861
1862      //-- For time output for each slice
1863      Double dEncTime = (Double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
1864
1865      const Char* digestStr = NULL;
1866      if (m_pcCfg->getDecodedPictureHashSEIEnabled())
1867      {
1868        /* calculate MD5sum for entire reconstructed picture */
1869        SEIDecodedPictureHash sei_recon_picture_digest;
1870        if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
1871        {
1872          sei_recon_picture_digest.method = SEIDecodedPictureHash::MD5;
1873          calcMD5(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
1874          digestStr = digestToString(sei_recon_picture_digest.digest, 16);
1875        }
1876        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
1877        {
1878          sei_recon_picture_digest.method = SEIDecodedPictureHash::CRC;
1879          calcCRC(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
1880          digestStr = digestToString(sei_recon_picture_digest.digest, 2);
1881        }
1882        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
1883        {
1884          sei_recon_picture_digest.method = SEIDecodedPictureHash::CHECKSUM;
1885          calcChecksum(*pcPic->getPicYuvRec(), sei_recon_picture_digest.digest);
1886          digestStr = digestToString(sei_recon_picture_digest.digest, 4);
1887        }
1888#if H_MV
1889        OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer(), getLayerId() );
1890#else
1891        OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer());
1892#endif
1893
1894        /* write the SEI messages */
1895        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1896        m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_recon_picture_digest, pcSlice->getSPS());
1897        writeRBSPTrailingBits(nalu.m_Bitstream);
1898
1899        accessUnit.insert(accessUnit.end(), new NALUnitEBSP(nalu));
1900      }
1901      if (m_pcCfg->getTemporalLevel0IndexSEIEnabled())
1902      {
1903        SEITemporalLevel0Index sei_temporal_level0_index;
1904        if (pcSlice->getRapPicFlag())
1905        {
1906          m_tl0Idx = 0;
1907          m_rapIdx = (m_rapIdx + 1) & 0xFF;
1908        }
1909        else
1910        {
1911          m_tl0Idx = (m_tl0Idx + (pcSlice->getTLayer() ? 0 : 1)) & 0xFF;
1912        }
1913        sei_temporal_level0_index.tl0Idx = m_tl0Idx;
1914        sei_temporal_level0_index.rapIdx = m_rapIdx;
1915
1916        OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI); 
1917
1918        /* write the SEI messages */
1919        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
1920        m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_temporal_level0_index, pcSlice->getSPS());
1921        writeRBSPTrailingBits(nalu.m_Bitstream);
1922
1923        /* insert the SEI message NALUnit before any Slice NALUnits */
1924        AccessUnit::iterator it = find_if(accessUnit.begin(), accessUnit.end(), mem_fun(&NALUnit::isSlice));
1925        accessUnit.insert(it, new NALUnitEBSP(nalu));
1926      }
1927
1928      xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime );
1929
1930    //In case of field coding, compute the interlaced PSNR for both fields
1931    if (isField && ((!pcPic->isTopField() && isTff) || (pcPic->isTopField() && !isTff)))
1932    {
1933      //get complementary top field
1934      TComPic* pcPicTop;
1935      TComList<TComPic*>::iterator   iterPic = rcListPic.begin();
1936      while ((*iterPic)->getPOC() != pcPic->getPOC()-1)
1937      {
1938        iterPic ++;
1939      }
1940      pcPicTop = *(iterPic);
1941      xCalculateInterlacedAddPSNR(pcPicTop, pcPic, pcPicTop->getPicYuvRec(), pcPic->getPicYuvRec(), accessUnit, dEncTime );
1942    }
1943   
1944      if (digestStr)
1945      {
1946        if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
1947        {
1948          printf(" [MD5:%s]", digestStr);
1949        }
1950        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
1951        {
1952          printf(" [CRC:%s]", digestStr);
1953        }
1954        else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
1955        {
1956          printf(" [Checksum:%s]", digestStr);
1957        }
1958      }
1959#if RATE_CONTROL_LAMBDA_DOMAIN
1960      if ( m_pcCfg->getUseRateCtrl() )
1961      {
1962#if !M0036_RC_IMPROVEMENT
1963        Double effectivePercentage = m_pcRateCtrl->getRCPic()->getEffectivePercentage();
1964#endif
1965        Double avgQP     = m_pcRateCtrl->getRCPic()->calAverageQP();
1966        Double avgLambda = m_pcRateCtrl->getRCPic()->calAverageLambda();
1967        if ( avgLambda < 0.0 )
1968        {
1969          avgLambda = lambda;
1970        }
1971#if M0036_RC_IMPROVEMENT
1972#if RATE_CONTROL_INTRA
1973        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, pcSlice->getSliceType());
1974#else
1975        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda );
1976#endif
1977#else
1978        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, effectivePercentage );
1979#endif
1980        m_pcRateCtrl->getRCPic()->addToPictureLsit( m_pcRateCtrl->getPicList() );
1981
1982        m_pcRateCtrl->getRCSeq()->updateAfterPic( actualTotalBits );
1983        if ( pcSlice->getSliceType() != I_SLICE )
1984        {
1985          m_pcRateCtrl->getRCGOP()->updateAfterPicture( actualTotalBits );
1986        }
1987        else    // for intra picture, the estimated bits are used to update the current status in the GOP
1988        {
1989          m_pcRateCtrl->getRCGOP()->updateAfterPicture( estimatedBits );
1990        }
1991      }
1992#else
1993      if(m_pcCfg->getUseRateCtrl())
1994      {
1995        UInt  frameBits = m_vRVM_RP[m_vRVM_RP.size()-1];
1996        m_pcRateCtrl->updataRCFrameStatus((Int)frameBits, pcSlice->getSliceType());
1997      }
1998#endif
1999
2000      if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
2001          ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
2002          ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() ) 
2003         || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
2004      {
2005        TComVUI *vui = pcSlice->getSPS()->getVuiParameters();
2006        TComHRD *hrd = vui->getHrdParameters();
2007
2008        if( hrd->getSubPicCpbParamsPresentFlag() )
2009        {
2010          Int i;
2011          UInt64 ui64Tmp;
2012          UInt uiPrev = 0;
2013          UInt numDU = ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 );
2014          UInt *pCRD = &pictureTimingSEI.m_duCpbRemovalDelayMinus1[0];
2015          UInt maxDiff = ( hrd->getTickDivisorMinus2() + 2 ) - 1;
2016
2017          for( i = 0; i < numDU; i ++ )
2018          {
2019            pictureTimingSEI.m_numNalusInDuMinus1[ i ]       = ( i == 0 ) ? ( accumNalsDU[ i ] - 1 ) : ( accumNalsDU[ i ] - accumNalsDU[ i - 1] - 1 );
2020          }
2021
2022          if( numDU == 1 )
2023          {
2024            pCRD[ 0 ] = 0; /* don't care */
2025          }
2026          else
2027          {
2028            pCRD[ numDU - 1 ] = 0;/* by definition */
2029            UInt tmp = 0;
2030            UInt accum = 0;
2031
2032            for( i = ( numDU - 2 ); i >= 0; i -- )
2033            {
2034              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
2035              if( (UInt)ui64Tmp > maxDiff )
2036              {
2037                tmp ++;
2038              }
2039            }
2040            uiPrev = 0;
2041
2042            UInt flag = 0;
2043            for( i = ( numDU - 2 ); i >= 0; i -- )
2044            {
2045              flag = 0;
2046              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
2047
2048              if( (UInt)ui64Tmp > maxDiff )
2049              {
2050                if(uiPrev >= maxDiff - tmp)
2051                {
2052                  ui64Tmp = uiPrev + 1;
2053                  flag = 1;
2054                }
2055                else                            ui64Tmp = maxDiff - tmp + 1;
2056              }
2057              pCRD[ i ] = (UInt)ui64Tmp - uiPrev - 1;
2058              if( (Int)pCRD[ i ] < 0 )
2059              {
2060                pCRD[ i ] = 0;
2061              }
2062              else if (tmp > 0 && flag == 1) 
2063              {
2064                tmp --;
2065              }
2066              accum += pCRD[ i ] + 1;
2067              uiPrev = accum;
2068            }
2069          }
2070        }
2071        if( m_pcCfg->getPictureTimingSEIEnabled() )
2072        {
2073          {
2074            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
2075          m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
2076          pictureTimingSEI.m_picStruct = (isField && pcSlice->getPic()->isTopField())? 1 : isField? 2 : 0;
2077          m_seiWriter.writeSEImessage(nalu.m_Bitstream, pictureTimingSEI, pcSlice->getSPS());
2078          writeRBSPTrailingBits(nalu.m_Bitstream);
2079          UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
2080          UInt offsetPosition = m_activeParameterSetSEIPresentInAU
2081                                    + m_bufferingPeriodSEIPresentInAU;    // Insert PT SEI after APS and BP SEI
2082          AccessUnit::iterator it;
2083          for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
2084          {
2085            it++;
2086          }
2087          accessUnit.insert(it, new NALUnitEBSP(nalu));
2088          m_pictureTimingSEIPresentInAU = true;
2089        }
2090          if ( m_pcCfg->getScalableNestingSEIEnabled() ) // put picture timing SEI into scalable nesting SEI
2091          {
2092            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
2093            m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
2094            scalableNestingSEI.m_nestedSEIs.clear();
2095            scalableNestingSEI.m_nestedSEIs.push_back(&pictureTimingSEI);
2096            m_seiWriter.writeSEImessage(nalu.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
2097            writeRBSPTrailingBits(nalu.m_Bitstream);
2098            UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
2099            UInt offsetPosition = m_activeParameterSetSEIPresentInAU
2100              + m_bufferingPeriodSEIPresentInAU + m_pictureTimingSEIPresentInAU + m_nestedBufferingPeriodSEIPresentInAU;    // Insert PT SEI after APS and BP SEI
2101            AccessUnit::iterator it;
2102            for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
2103            {
2104              it++;
2105            }
2106            accessUnit.insert(it, new NALUnitEBSP(nalu));
2107            m_nestedPictureTimingSEIPresentInAU = true;
2108          }
2109        }
2110        if( m_pcCfg->getDecodingUnitInfoSEIEnabled() && hrd->getSubPicCpbParamsPresentFlag() )
2111        {             
2112          m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
2113          for( Int i = 0; i < ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 ); i ++ )
2114          {
2115            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
2116
2117            SEIDecodingUnitInfo tempSEI;
2118            tempSEI.m_decodingUnitIdx = i;
2119            tempSEI.m_duSptCpbRemovalDelay = pictureTimingSEI.m_duCpbRemovalDelayMinus1[i] + 1;
2120            tempSEI.m_dpbOutputDuDelayPresentFlag = false;
2121            tempSEI.m_picSptDpbOutputDuDelay = picSptDpbOutputDuDelay;
2122
2123            AccessUnit::iterator it;
2124            // Insert the first one in the right location, before the first slice
2125            if(i == 0)
2126            {
2127              // Insert before the first slice.
2128              m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, pcSlice->getSPS());
2129              writeRBSPTrailingBits(nalu.m_Bitstream);
2130
2131              UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
2132              UInt offsetPosition = m_activeParameterSetSEIPresentInAU
2133                                    + m_bufferingPeriodSEIPresentInAU
2134                                    + m_pictureTimingSEIPresentInAU;  // Insert DU info SEI after APS, BP and PT SEI
2135              for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
2136              {
2137                it++;
2138              }
2139              accessUnit.insert(it, new NALUnitEBSP(nalu));
2140            }
2141            else
2142            {
2143              Int ctr;
2144              // For the second decoding unit onwards we know how many NALUs are present
2145              for (ctr = 0, it = accessUnit.begin(); it != accessUnit.end(); it++)
2146              {           
2147                if(ctr == accumNalsDU[ i - 1 ])
2148                {
2149                  // Insert before the first slice.
2150                  m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, pcSlice->getSPS());
2151                  writeRBSPTrailingBits(nalu.m_Bitstream);
2152
2153                  accessUnit.insert(it, new NALUnitEBSP(nalu));
2154                  break;
2155                }
2156                if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
2157                {
2158                  ctr++;
2159                }
2160              }
2161            }           
2162          }
2163        }
2164      }
2165      xResetNonNestedSEIPresentFlags();
2166      xResetNestedSEIPresentFlags();
2167      pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
2168
2169      pcPic->setReconMark   ( true );
2170#if H_MV
2171      TComSlice::markIvRefPicsAsShortTerm( m_refPicSetInterLayer0, m_refPicSetInterLayer1 ); 
2172      std::vector<Int> temp; 
2173      TComSlice::markCurrPic( pcPic ); 
2174      TComSlice::markIvRefPicsAsUnused   ( m_ivPicLists, temp, pcPic->getSlice(0)->getVPS(), m_layerId, pcPic->getPOC() ); 
2175#endif
2176      m_bFirst = false;
2177      m_iNumPicCoded++;
2178      m_totalCoded ++;
2179      /* logging: insert a newline at end of picture period */
2180      printf("\n");
2181      fflush(stdout);
2182
2183      delete[] pcSubstreamsOut;
2184  }
2185#if !KWU_FIX_URQ && !RATE_CONTROL_LAMBDA_DOMAIN
2186  if(m_pcCfg->getUseRateCtrl())
2187  {
2188    m_pcRateCtrl->updateRCGOPStatus();
2189  }
2190#endif
2191  delete pcBitstreamRedirect;
2192
2193  if( accumBitsDU != NULL) delete accumBitsDU;
2194  if( accumNalsDU != NULL) delete accumNalsDU;
2195
2196#if !H_MV
2197  assert ( (m_iNumPicCoded == iNumPicRcvd) || (isField && iPOCLast == 1) );
2198#endif
2199}
2200
2201#if !H_MV
2202Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded, bool isField)
2203{
2204  assert (uiNumAllPicCoded == m_gcAnalyzeAll.getNumPic());
2205 
2206   
2207  //--CFG_KDY
2208  if(isField)
2209  {
2210    m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() * 2);
2211    m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() * 2);
2212    m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() * 2);
2213    m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() * 2);
2214  }
2215  else
2216  {
2217  m_gcAnalyzeAll.setFrmRate( m_pcCfg->getFrameRate() );
2218  m_gcAnalyzeI.setFrmRate( m_pcCfg->getFrameRate() );
2219  m_gcAnalyzeP.setFrmRate( m_pcCfg->getFrameRate() );
2220  m_gcAnalyzeB.setFrmRate( m_pcCfg->getFrameRate() );
2221  }
2222 
2223  //-- all
2224  printf( "\n\nSUMMARY --------------------------------------------------------\n" );
2225  m_gcAnalyzeAll.printOut('a');
2226 
2227  printf( "\n\nI Slices--------------------------------------------------------\n" );
2228  m_gcAnalyzeI.printOut('i');
2229 
2230  printf( "\n\nP Slices--------------------------------------------------------\n" );
2231  m_gcAnalyzeP.printOut('p');
2232 
2233  printf( "\n\nB Slices--------------------------------------------------------\n" );
2234  m_gcAnalyzeB.printOut('b');
2235 
2236#if _SUMMARY_OUT_
2237  m_gcAnalyzeAll.printSummaryOut();
2238#endif
2239#if _SUMMARY_PIC_
2240  m_gcAnalyzeI.printSummary('I');
2241  m_gcAnalyzeP.printSummary('P');
2242  m_gcAnalyzeB.printSummary('B');
2243#endif
2244
2245  if(isField)
2246  {
2247    //-- interlaced summary
2248    m_gcAnalyzeAll_in.setFrmRate( m_pcCfg->getFrameRate());
2249    printf( "\n\nSUMMARY INTERLACED ---------------------------------------------\n" );
2250    m_gcAnalyzeAll_in.printOutInterlaced('a',  m_gcAnalyzeAll.getBits());
2251   
2252#if _SUMMARY_OUT_
2253    m_gcAnalyzeAll_in.printSummaryOutInterlaced();
2254#endif
2255  }
2256
2257  printf("\nRVM: %.3lf\n" , xCalculateRVM());
2258}
2259#endif
2260#if H_3D_VSO
2261Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, Dist64& ruiDist, UInt64& ruiBits )
2262#else
2263Void TEncGOP::preLoopFilterPicAll( TComPic* pcPic, UInt64& ruiDist, UInt64& ruiBits )
2264#endif
2265{
2266  TComSlice* pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
2267  Bool bCalcDist = false;
2268  m_pcLoopFilter->setCfg(m_pcCfg->getLFCrossTileBoundaryFlag());
2269  m_pcLoopFilter->loopFilterPic( pcPic );
2270 
2271  m_pcEntropyCoder->setEntropyCoder ( m_pcEncTop->getRDGoOnSbacCoder(), pcSlice );
2272  m_pcEntropyCoder->resetEntropy    ();
2273  m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
2274  pcSlice = pcPic->getSlice(0);
2275  if(pcSlice->getSPS()->getUseSAO())
2276  {
2277    std::vector<Bool> LFCrossSliceBoundaryFlag(1, true);
2278    std::vector<Int>  sliceStartAddress;
2279    sliceStartAddress.push_back(0);
2280    sliceStartAddress.push_back(pcPic->getNumCUsInFrame()* pcPic->getNumPartInCU());
2281    pcPic->createNonDBFilterInfo(sliceStartAddress, 0, &LFCrossSliceBoundaryFlag);
2282  }
2283 
2284  if( pcSlice->getSPS()->getUseSAO())
2285  {
2286    pcPic->destroyNonDBFilterInfo();
2287  }
2288 
2289  m_pcEntropyCoder->resetEntropy    ();
2290  ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
2291 
2292  if (!bCalcDist)
2293    ruiDist = xFindDistortionFrame(pcPic->getPicYuvOrg(), pcPic->getPicYuvRec());
2294}
2295
2296// ====================================================================================================================
2297// Protected member functions
2298// ====================================================================================================================
2299
2300
2301Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, bool isField )
2302{
2303  assert( iNumPicRcvd > 0 );
2304  //  Exception for the first frames
2305  if ( ( isField && (iPOCLast == 0 || iPOCLast == 1) ) || (!isField  && (iPOCLast == 0))  )
2306  {
2307    m_iGopSize    = 1;
2308  }
2309  else
2310  {
2311    m_iGopSize    = m_pcCfg->getGOPSize();
2312  }
2313  assert (m_iGopSize > 0);
2314 
2315  return;
2316}
2317
2318Void TEncGOP::xInitGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut )
2319{
2320  assert( iNumPicRcvd > 0 );
2321  //  Exception for the first frame
2322  if ( iPOCLast == 0 )
2323  {
2324    m_iGopSize    = 1;
2325  }
2326  else
2327    m_iGopSize    = m_pcCfg->getGOPSize();
2328 
2329  assert (m_iGopSize > 0); 
2330
2331  return;
2332}
2333
2334Void TEncGOP::xGetBuffer( TComList<TComPic*>&      rcListPic,
2335                         TComList<TComPicYuv*>&    rcListPicYuvRecOut,
2336                         Int                       iNumPicRcvd,
2337                         Int                       iTimeOffset,
2338                         TComPic*&                 rpcPic,
2339                         TComPicYuv*&              rpcPicYuvRecOut,
2340                         Int                       pocCurr,
2341                         bool                      isField)
2342{
2343  Int i;
2344  //  Rec. output
2345  TComList<TComPicYuv*>::iterator     iterPicYuvRec = rcListPicYuvRecOut.end();
2346 
2347  if (isField)
2348  {
2349    for ( i = 0; i < ( (pocCurr == 0 ) || (pocCurr == 1 ) ? (iNumPicRcvd - iTimeOffset + 1) : (iNumPicRcvd - iTimeOffset + 2) ); i++ )
2350    {
2351      iterPicYuvRec--;
2352    }
2353  }
2354  else
2355  {
2356    for ( i = 0; i < (iNumPicRcvd - iTimeOffset + 1); i++ )
2357  {
2358    iterPicYuvRec--;
2359  }
2360 
2361  }
2362 
2363  if (isField)
2364  {
2365    if(pocCurr == 1)
2366    {
2367      iterPicYuvRec++;
2368    }
2369  }
2370  rpcPicYuvRecOut = *(iterPicYuvRec);
2371 
2372  //  Current pic.
2373  TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
2374  while (iterPic != rcListPic.end())
2375  {
2376    rpcPic = *(iterPic);
2377    rpcPic->setCurrSliceIdx(0);
2378    if (rpcPic->getPOC() == pocCurr)
2379    {
2380      break;
2381    }
2382    iterPic++;
2383  }
2384
2385#if !H_MV
2386  assert( rpcPic != NULL );
2387#endif
2388  assert (rpcPic->getPOC() == pocCurr);
2389 
2390  return;
2391}
2392
2393#if H_3D_VSO
2394Dist64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1)
2395#else
2396UInt64 TEncGOP::xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1)
2397#endif
2398{
2399  Int     x, y;
2400  Pel*  pSrc0   = pcPic0 ->getLumaAddr();
2401  Pel*  pSrc1   = pcPic1 ->getLumaAddr();
2402  UInt  uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthY-8);
2403  Int   iTemp;
2404 
2405  Int   iStride = pcPic0->getStride();
2406  Int   iWidth  = pcPic0->getWidth();
2407  Int   iHeight = pcPic0->getHeight();
2408 
2409#if H_3D_VSO
2410  Dist64  uiTotalDiff = 0;
2411#else
2412  UInt64  uiTotalDiff = 0;
2413#endif
2414 
2415  for( y = 0; y < iHeight; y++ )
2416  {
2417    for( x = 0; x < iWidth; x++ )
2418    {
2419      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
2420    }
2421    pSrc0 += iStride;
2422    pSrc1 += iStride;
2423  }
2424 
2425  uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthC-8);
2426  iHeight >>= 1;
2427  iWidth  >>= 1;
2428  iStride >>= 1;
2429 
2430  pSrc0  = pcPic0->getCbAddr();
2431  pSrc1  = pcPic1->getCbAddr();
2432 
2433  for( y = 0; y < iHeight; y++ )
2434  {
2435    for( x = 0; x < iWidth; x++ )
2436    {
2437      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
2438    }
2439    pSrc0 += iStride;
2440    pSrc1 += iStride;
2441  }
2442 
2443  pSrc0  = pcPic0->getCrAddr();
2444  pSrc1  = pcPic1->getCrAddr();
2445 
2446  for( y = 0; y < iHeight; y++ )
2447  {
2448    for( x = 0; x < iWidth; x++ )
2449    {
2450      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
2451    }
2452    pSrc0 += iStride;
2453    pSrc1 += iStride;
2454  }
2455 
2456  return uiTotalDiff;
2457}
2458
2459#if VERBOSE_RATE
2460static const Char* nalUnitTypeToString(NalUnitType type)
2461{
2462  switch (type)
2463  {
2464    case NAL_UNIT_CODED_SLICE_TRAIL_R: return "TRAIL_R";
2465    case NAL_UNIT_CODED_SLICE_TRAIL_N: return "TRAIL_N";
2466    case NAL_UNIT_CODED_SLICE_TLA_R:      return "TLA_R";
2467    case NAL_UNIT_CODED_SLICE_TSA_N: return "TSA_N";
2468    case NAL_UNIT_CODED_SLICE_STSA_R: return "STSA_R";
2469    case NAL_UNIT_CODED_SLICE_STSA_N: return "STSA_N";
2470    case NAL_UNIT_CODED_SLICE_BLA_W_LP:   return "BLA_W_LP";
2471    case NAL_UNIT_CODED_SLICE_BLA_W_RADL: return "BLA_W_RADL";
2472    case NAL_UNIT_CODED_SLICE_BLA_N_LP: return "BLA_N_LP";
2473    case NAL_UNIT_CODED_SLICE_IDR_W_RADL: return "IDR_W_RADL";
2474    case NAL_UNIT_CODED_SLICE_IDR_N_LP: return "IDR_N_LP";
2475    case NAL_UNIT_CODED_SLICE_CRA: return "CRA";
2476    case NAL_UNIT_CODED_SLICE_RADL_R:     return "RADL_R";
2477    case NAL_UNIT_CODED_SLICE_RASL_R:     return "RASL_R";
2478    case NAL_UNIT_VPS: return "VPS";
2479    case NAL_UNIT_SPS: return "SPS";
2480    case NAL_UNIT_PPS: return "PPS";
2481    case NAL_UNIT_ACCESS_UNIT_DELIMITER: return "AUD";
2482    case NAL_UNIT_EOS: return "EOS";
2483    case NAL_UNIT_EOB: return "EOB";
2484    case NAL_UNIT_FILLER_DATA: return "FILLER";
2485    case NAL_UNIT_PREFIX_SEI:             return "SEI";
2486    case NAL_UNIT_SUFFIX_SEI:             return "SEI";
2487    default: return "UNK";
2488  }
2489}
2490#endif
2491
2492Void TEncGOP::xCalculateAddPSNR( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit& accessUnit, Double dEncTime )
2493{
2494  Int     x, y;
2495  UInt64 uiSSDY  = 0;
2496  UInt64 uiSSDU  = 0;
2497  UInt64 uiSSDV  = 0;
2498 
2499  Double  dYPSNR  = 0.0;
2500  Double  dUPSNR  = 0.0;
2501  Double  dVPSNR  = 0.0;
2502 
2503  //===== calculate PSNR =====
2504  Pel*  pOrg    = pcPic ->getPicYuvOrg()->getLumaAddr();
2505  Pel*  pRec    = pcPicD->getLumaAddr();
2506  Int   iStride = pcPicD->getStride();
2507 
2508  Int   iWidth;
2509  Int   iHeight;
2510 
2511  iWidth  = pcPicD->getWidth () - m_pcEncTop->getPad(0);
2512  iHeight = pcPicD->getHeight() - m_pcEncTop->getPad(1);
2513 
2514  Int   iSize   = iWidth*iHeight;
2515 
2516  for( y = 0; y < iHeight; y++ )
2517  {
2518    for( x = 0; x < iWidth; x++ )
2519    {
2520      Int iDiff = (Int)( pOrg[x] - pRec[x] );
2521      uiSSDY   += iDiff * iDiff;
2522    }
2523    pOrg += iStride;
2524    pRec += iStride;
2525  }
2526 
2527#if H_3D_VSO
2528#if H_3D_VSO_SYNTH_DIST_OUT
2529  if ( m_pcRdCost->getUseRenModel() )
2530  {
2531    unsigned int maxval = 255 * (1<<(g_uiBitDepth + g_uiBitIncrement -8));
2532    Double fRefValueY = (double) maxval * maxval * iSize;
2533    Double fRefValueC = fRefValueY / 4.0;
2534    TRenModel*  pcRenModel = m_pcEncTop->getEncTop()->getRenModel();
2535    Int64 iDistVSOY, iDistVSOU, iDistVSOV;
2536    pcRenModel->getTotalSSE( iDistVSOY, iDistVSOU, iDistVSOV );
2537    dYPSNR = ( iDistVSOY ? 10.0 * log10( fRefValueY / (Double) iDistVSOY ) : 99.99 );
2538    dUPSNR = ( iDistVSOU ? 10.0 * log10( fRefValueC / (Double) iDistVSOU ) : 99.99 );
2539    dVPSNR = ( iDistVSOV ? 10.0 * log10( fRefValueC / (Double) iDistVSOV ) : 99.99 );
2540  }
2541  else
2542  {
2543#endif
2544#endif
2545    iHeight >>= 1;
2546  iWidth  >>= 1;
2547  iStride >>= 1;
2548  pOrg  = pcPic ->getPicYuvOrg()->getCbAddr();
2549  pRec  = pcPicD->getCbAddr();
2550 
2551  for( y = 0; y < iHeight; y++ )
2552  {
2553    for( x = 0; x < iWidth; x++ )
2554    {
2555      Int iDiff = (Int)( pOrg[x] - pRec[x] );
2556      uiSSDU   += iDiff * iDiff;
2557    }
2558    pOrg += iStride;
2559    pRec += iStride;
2560  }
2561 
2562  pOrg  = pcPic ->getPicYuvOrg()->getCrAddr();
2563  pRec  = pcPicD->getCrAddr();
2564 
2565  for( y = 0; y < iHeight; y++ )
2566  {
2567    for( x = 0; x < iWidth; x++ )
2568    {
2569      Int iDiff = (Int)( pOrg[x] - pRec[x] );
2570      uiSSDV   += iDiff * iDiff;
2571    }
2572    pOrg += iStride;
2573    pRec += iStride;
2574  }
2575 
2576  Int maxvalY = 255 << (g_bitDepthY-8);
2577  Int maxvalC = 255 << (g_bitDepthC-8);
2578  Double fRefValueY = (Double) maxvalY * maxvalY * iSize;
2579  Double fRefValueC = (Double) maxvalC * maxvalC * iSize / 4.0;
2580  dYPSNR            = ( uiSSDY ? 10.0 * log10( fRefValueY / (Double)uiSSDY ) : 99.99 );
2581  dUPSNR            = ( uiSSDU ? 10.0 * log10( fRefValueC / (Double)uiSSDU ) : 99.99 );
2582  dVPSNR            = ( uiSSDV ? 10.0 * log10( fRefValueC / (Double)uiSSDV ) : 99.99 );
2583#if H_3D_VSO
2584#if H_3D_VSO_SYNTH_DIST_OUT
2585}
2586#endif
2587#endif
2588  /* calculate the size of the access unit, excluding:
2589   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
2590   *  - SEI NAL units
2591   */
2592  UInt numRBSPBytes = 0;
2593  for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
2594  {
2595    UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
2596#if VERBOSE_RATE
2597    printf("*** %6s numBytesInNALunit: %u\n", nalUnitTypeToString((*it)->m_nalUnitType), numRBSPBytes_nal);
2598#endif
2599    if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
2600    {
2601      numRBSPBytes += numRBSPBytes_nal;
2602    }
2603  }
2604
2605  UInt uibits = numRBSPBytes * 8;
2606  m_vRVM_RP.push_back( uibits );
2607
2608  //===== add PSNR =====
2609#if H_MV
2610  m_pcEncTop->getAnalyzeAll()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2611#else
2612  m_gcAnalyzeAll.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2613#endif
2614  TComSlice*  pcSlice = pcPic->getSlice(0);
2615  if (pcSlice->isIntra())
2616  {
2617#if H_MV
2618    m_pcEncTop->getAnalyzeI()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2619#else
2620    m_gcAnalyzeI.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2621#endif
2622  }
2623  if (pcSlice->isInterP())
2624  {
2625#if H_MV
2626    m_pcEncTop->getAnalyzeP()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2627#else
2628    m_gcAnalyzeP.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2629#endif
2630  }
2631  if (pcSlice->isInterB())
2632  {
2633#if H_MV
2634    m_pcEncTop->getAnalyzeB()->addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2635#else
2636    m_gcAnalyzeB.addResult (dYPSNR, dUPSNR, dVPSNR, (Double)uibits);
2637#endif
2638  }
2639
2640  Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
2641  if (!pcSlice->isReferenced()) c += 32;
2642
2643#if ADAPTIVE_QP_SELECTION
2644#if H_MV
2645  printf("Layer %3d   POC %4d TId: %1d ( %c-SLICE, nQP %d QP %d ) %10d  bits",
2646    pcSlice->getLayerId(),
2647    pcSlice->getPOC(),
2648    pcSlice->getTLayer(),
2649    c,
2650    pcSlice->getSliceQpBase(),
2651    pcSlice->getSliceQp(),
2652    uibits );
2653#else
2654  printf("POC %4d TId: %1d ( %c-SLICE, nQP %d QP %d ) %10d bits",
2655         pcSlice->getPOC(),
2656         pcSlice->getTLayer(),
2657         c,
2658         pcSlice->getSliceQpBase(),
2659         pcSlice->getSliceQp(),
2660         uibits );
2661#endif
2662#else
2663#if H_MV
2664  printf("Layer %3d   POC %4d TId: %1d ( %c-SLICE, QP %d ) %10d bits",
2665    pcSlice->getLayerId(),
2666    pcSlice->getPOC()-pcSlice->getLastIDR(),
2667    pcSlice->getTLayer(),
2668    c,
2669    pcSlice->getSliceQp(),
2670    uibits );
2671#else
2672  printf("POC %4d TId: %1d ( %c-SLICE, QP %d ) %10d bits",
2673         pcSlice->getPOC()-pcSlice->getLastIDR(),
2674         pcSlice->getTLayer(),
2675         c,
2676         pcSlice->getSliceQp(),
2677         uibits );
2678#endif
2679#endif
2680
2681  printf(" [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", dYPSNR, dUPSNR, dVPSNR );
2682  printf(" [ET %5.0f ]", dEncTime );
2683 
2684  for (Int iRefList = 0; iRefList < 2; iRefList++)
2685  {
2686    printf(" [L%d ", iRefList);
2687    for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(RefPicList(iRefList)); iRefIndex++)
2688    {
2689#if H_MV
2690      if( pcSlice->getLayerId() != pcSlice->getRefLayerId( RefPicList(iRefList), iRefIndex ) )
2691      {
2692        printf( "V%d ", pcSlice->getRefLayerId( RefPicList(iRefList), iRefIndex ) );
2693      }
2694      else
2695      {
2696#endif
2697      printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)-pcSlice->getLastIDR());
2698#if H_MV
2699      }
2700#endif
2701    }
2702    printf("]");
2703  }
2704}
2705
2706
2707Void reinterlace(Pel* top, Pel* bottom, Pel* dst, UInt stride, UInt width, UInt height, bool isTff)
2708{
2709 
2710  for (Int y = 0; y < height; y++)
2711  {
2712    for (Int x = 0; x < width; x++)
2713    {
2714      dst[x] = isTff ? (UChar) top[x] : (UChar) bottom[x];
2715      dst[stride+x] = isTff ? (UChar) bottom[x] : (UChar) top[x];
2716    }
2717    top += stride;
2718    bottom += stride;
2719    dst += stride*2;
2720  }
2721}
2722
2723
2724Void TEncGOP::xCalculateInterlacedAddPSNR( TComPic* pcPicOrgTop, TComPic* pcPicOrgBottom, TComPicYuv* pcPicRecTop, TComPicYuv* pcPicRecBottom, const AccessUnit& accessUnit, Double dEncTime )
2725{
2726#if  H_MV
2727  assert( 0 ); // Field coding and MV need to be aligned.
2728#else
2729  Int     x, y;
2730 
2731  UInt64 uiSSDY_in  = 0;
2732  UInt64 uiSSDU_in  = 0;
2733  UInt64 uiSSDV_in  = 0;
2734 
2735  Double  dYPSNR_in  = 0.0;
2736  Double  dUPSNR_in  = 0.0;
2737  Double  dVPSNR_in  = 0.0;
2738 
2739  /*------ INTERLACED PSNR -----------*/
2740 
2741  /* Luma */
2742 
2743  Pel*  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getLumaAddr();
2744  Pel*  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getLumaAddr();
2745  Pel*  pRecTop = pcPicRecTop->getLumaAddr();
2746  Pel*  pRecBottom = pcPicRecBottom->getLumaAddr();
2747 
2748  Int   iWidth;
2749  Int   iHeight;
2750  Int iStride;
2751 
2752  iWidth  = pcPicOrgTop->getPicYuvOrg()->getWidth () - m_pcEncTop->getPad(0);
2753  iHeight = pcPicOrgTop->getPicYuvOrg()->getHeight() - m_pcEncTop->getPad(1);
2754  iStride = pcPicOrgTop->getPicYuvOrg()->getStride();
2755  Int   iSize   = iWidth*iHeight;
2756  bool isTff = pcPicOrgTop->isTopField();
2757 
2758  TComPicYuv* pcOrgInterlaced = new TComPicYuv;
2759  pcOrgInterlaced->create( iWidth, iHeight << 1, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
2760 
2761  TComPicYuv* pcRecInterlaced = new TComPicYuv;
2762  pcRecInterlaced->create( iWidth, iHeight << 1, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
2763 
2764  Pel* pOrgInterlaced = pcOrgInterlaced->getLumaAddr();
2765  Pel* pRecInterlaced = pcRecInterlaced->getLumaAddr();
2766 
2767  //=== Interlace fields ====
2768  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
2769  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
2770 
2771  //===== calculate PSNR =====
2772  for( y = 0; y < iHeight << 1; y++ )
2773  {
2774    for( x = 0; x < iWidth; x++ )
2775    {
2776      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
2777      uiSSDY_in   += iDiff * iDiff;
2778    }
2779    pOrgInterlaced += iStride;
2780    pRecInterlaced += iStride;
2781  }
2782 
2783  /*Chroma*/
2784 
2785  iHeight >>= 1;
2786  iWidth  >>= 1;
2787  iStride >>= 1;
2788 
2789  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getCbAddr();
2790  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getCbAddr();
2791  pRecTop = pcPicRecTop->getCbAddr();
2792  pRecBottom = pcPicRecBottom->getCbAddr();
2793  pOrgInterlaced = pcOrgInterlaced->getCbAddr();
2794  pRecInterlaced = pcRecInterlaced->getCbAddr();
2795 
2796  //=== Interlace fields ====
2797  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
2798  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
2799 
2800  //===== calculate PSNR =====
2801  for( y = 0; y < iHeight << 1; y++ )
2802  {
2803    for( x = 0; x < iWidth; x++ )
2804    {
2805      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
2806      uiSSDU_in   += iDiff * iDiff;
2807    }
2808    pOrgInterlaced += iStride;
2809    pRecInterlaced += iStride;
2810  }
2811 
2812  pOrgTop = pcPicOrgTop->getPicYuvOrg()->getCrAddr();
2813  pOrgBottom = pcPicOrgBottom->getPicYuvOrg()->getCrAddr();
2814  pRecTop = pcPicRecTop->getCrAddr();
2815  pRecBottom = pcPicRecBottom->getCrAddr();
2816  pOrgInterlaced = pcOrgInterlaced->getCrAddr();
2817  pRecInterlaced = pcRecInterlaced->getCrAddr();
2818 
2819  //=== Interlace fields ====
2820  reinterlace(pOrgTop, pOrgBottom, pOrgInterlaced, iStride, iWidth, iHeight, isTff);
2821  reinterlace(pRecTop, pRecBottom, pRecInterlaced, iStride, iWidth, iHeight, isTff);
2822 
2823  //===== calculate PSNR =====
2824  for( y = 0; y < iHeight << 1; y++ )
2825  {
2826    for( x = 0; x < iWidth; x++ )
2827    {
2828      Int iDiff = (Int)( pOrgInterlaced[x] - pRecInterlaced[x] );
2829      uiSSDV_in   += iDiff * iDiff;
2830    }
2831    pOrgInterlaced += iStride;
2832    pRecInterlaced += iStride;
2833  }
2834 
2835  Int maxvalY = 255 << (g_bitDepthY-8);
2836  Int maxvalC = 255 << (g_bitDepthC-8);
2837  Double fRefValueY = (Double) maxvalY * maxvalY * iSize*2;
2838  Double fRefValueC = (Double) maxvalC * maxvalC * iSize*2 / 4.0;
2839  dYPSNR_in            = ( uiSSDY_in ? 10.0 * log10( fRefValueY / (Double)uiSSDY_in ) : 99.99 );
2840  dUPSNR_in            = ( uiSSDU_in ? 10.0 * log10( fRefValueC / (Double)uiSSDU_in ) : 99.99 );
2841  dVPSNR_in            = ( uiSSDV_in ? 10.0 * log10( fRefValueC / (Double)uiSSDV_in ) : 99.99 );
2842 
2843  /* calculate the size of the access unit, excluding:
2844   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
2845   *  - SEI NAL units
2846   */
2847  UInt numRBSPBytes = 0;
2848  for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
2849  {
2850    UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
2851   
2852    if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
2853      numRBSPBytes += numRBSPBytes_nal;
2854  }
2855 
2856  UInt uibits = numRBSPBytes * 8 ;
2857 
2858  //===== add PSNR =====
2859  m_gcAnalyzeAll_in.addResult (dYPSNR_in, dUPSNR_in, dVPSNR_in, (Double)uibits);
2860 
2861  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 );
2862 
2863  pcOrgInterlaced->destroy();
2864  delete pcOrgInterlaced;
2865  pcRecInterlaced->destroy();
2866  delete pcRecInterlaced;
2867#endif
2868}
2869/** Function for deciding the nal_unit_type.
2870 * \param pocCurr POC of the current picture
2871 * \returns the nal unit type of the picture
2872 * This function checks the configuration and returns the appropriate nal_unit_type for the picture.
2873 */
2874NalUnitType TEncGOP::getNalUnitType(Int pocCurr, Int lastIDR)
2875{
2876  if (pocCurr == 0)
2877  {
2878    return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
2879  }
2880  if (pocCurr % m_pcCfg->getIntraPeriod() == 0)
2881  {
2882    if (m_pcCfg->getDecodingRefreshType() == 1)
2883    {
2884      return NAL_UNIT_CODED_SLICE_CRA;
2885    }
2886    else if (m_pcCfg->getDecodingRefreshType() == 2)
2887    {
2888      return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
2889    }
2890  }
2891  if(m_pocCRA>0)
2892  {
2893    if(pocCurr<m_pocCRA)
2894    {
2895      // All leading pictures are being marked as TFD pictures here since current encoder uses all
2896      // reference pictures while encoding leading pictures. An encoder can ensure that a leading
2897      // picture can be still decodable when random accessing to a CRA/CRANT/BLA/BLANT picture by
2898      // controlling the reference pictures used for encoding that leading picture. Such a leading
2899      // picture need not be marked as a TFD picture.
2900      return NAL_UNIT_CODED_SLICE_RASL_R;
2901    }
2902  }
2903  if (lastIDR>0)
2904  {
2905    if (pocCurr < lastIDR)
2906    {
2907      return NAL_UNIT_CODED_SLICE_RADL_R;
2908    }
2909  }
2910  return NAL_UNIT_CODED_SLICE_TRAIL_R;
2911}
2912
2913Double TEncGOP::xCalculateRVM()
2914{
2915  Double dRVM = 0;
2916 
2917  if( m_pcCfg->getGOPSize() == 1 && m_pcCfg->getIntraPeriod() != 1 && m_pcCfg->getFramesToBeEncoded() > RVM_VCEGAM10_M * 2 )
2918  {
2919    // calculate RVM only for lowdelay configurations
2920    std::vector<Double> vRL , vB;
2921    size_t N = m_vRVM_RP.size();
2922    vRL.resize( N );
2923    vB.resize( N );
2924   
2925    Int i;
2926    Double dRavg = 0 , dBavg = 0;
2927    vB[RVM_VCEGAM10_M] = 0;
2928    for( i = RVM_VCEGAM10_M + 1 ; i < N - RVM_VCEGAM10_M + 1 ; i++ )
2929    {
2930      vRL[i] = 0;
2931      for( Int j = i - RVM_VCEGAM10_M ; j <= i + RVM_VCEGAM10_M - 1 ; j++ )
2932        vRL[i] += m_vRVM_RP[j];
2933      vRL[i] /= ( 2 * RVM_VCEGAM10_M );
2934      vB[i] = vB[i-1] + m_vRVM_RP[i] - vRL[i];
2935      dRavg += m_vRVM_RP[i];
2936      dBavg += vB[i];
2937    }
2938   
2939    dRavg /= ( N - 2 * RVM_VCEGAM10_M );
2940    dBavg /= ( N - 2 * RVM_VCEGAM10_M );
2941   
2942    Double dSigamB = 0;
2943    for( i = RVM_VCEGAM10_M + 1 ; i < N - RVM_VCEGAM10_M + 1 ; i++ )
2944    {
2945      Double tmp = vB[i] - dBavg;
2946      dSigamB += tmp * tmp;
2947    }
2948    dSigamB = sqrt( dSigamB / ( N - 2 * RVM_VCEGAM10_M ) );
2949   
2950    Double f = sqrt( 12.0 * ( RVM_VCEGAM10_M - 1 ) / ( RVM_VCEGAM10_M + 1 ) );
2951   
2952    dRVM = dSigamB / dRavg * f;
2953  }
2954 
2955  return( dRVM );
2956}
2957
2958/** Attaches the input bitstream to the stream in the output NAL unit
2959    Updates rNalu to contain concatenated bitstream. rpcBitstreamRedirect is cleared at the end of this function call.
2960 *  \param codedSliceData contains the coded slice data (bitstream) to be concatenated to rNalu
2961 *  \param rNalu          target NAL unit
2962 */
2963Void TEncGOP::xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream*& codedSliceData)
2964{
2965  // Byte-align
2966  rNalu.m_Bitstream.writeByteAlignment();   // Slice header byte-alignment
2967
2968  // Perform bitstream concatenation
2969  if (codedSliceData->getNumberOfWrittenBits() > 0)
2970    {
2971    rNalu.m_Bitstream.addSubstream(codedSliceData);
2972  }
2973
2974  m_pcEntropyCoder->setBitstream(&rNalu.m_Bitstream);
2975
2976  codedSliceData->clear();
2977}
2978
2979// Function will arrange the long-term pictures in the decreasing order of poc_lsb_lt,
2980// and among the pictures with the same lsb, it arranges them in increasing delta_poc_msb_cycle_lt value
2981Void TEncGOP::arrangeLongtermPicturesInRPS(TComSlice *pcSlice, TComList<TComPic*>& rcListPic)
2982{
2983  TComReferencePictureSet *rps = pcSlice->getRPS();
2984  if(!rps->getNumberOfLongtermPictures())
2985  {
2986    return;
2987  }
2988
2989  // Arrange long-term reference pictures in the correct order of LSB and MSB,
2990  // and assign values for pocLSBLT and MSB present flag
2991  Int longtermPicsPoc[MAX_NUM_REF_PICS], longtermPicsLSB[MAX_NUM_REF_PICS], indices[MAX_NUM_REF_PICS];
2992  Int longtermPicsMSB[MAX_NUM_REF_PICS];
2993  Bool mSBPresentFlag[MAX_NUM_REF_PICS];
2994  ::memset(longtermPicsPoc, 0, sizeof(longtermPicsPoc));    // Store POC values of LTRP
2995  ::memset(longtermPicsLSB, 0, sizeof(longtermPicsLSB));    // Store POC LSB values of LTRP
2996  ::memset(longtermPicsMSB, 0, sizeof(longtermPicsMSB));    // Store POC LSB values of LTRP
2997  ::memset(indices        , 0, sizeof(indices));            // Indices to aid in tracking sorted LTRPs
2998  ::memset(mSBPresentFlag , 0, sizeof(mSBPresentFlag));     // Indicate if MSB needs to be present
2999
3000  // Get the long-term reference pictures
3001  Int offset = rps->getNumberOfNegativePictures() + rps->getNumberOfPositivePictures();
3002  Int i, ctr = 0;
3003  Int maxPicOrderCntLSB = 1 << pcSlice->getSPS()->getBitsForPOC();
3004  for(i = rps->getNumberOfPictures() - 1; i >= offset; i--, ctr++)
3005  {
3006    longtermPicsPoc[ctr] = rps->getPOC(i);                                  // LTRP POC
3007    longtermPicsLSB[ctr] = getLSB(longtermPicsPoc[ctr], maxPicOrderCntLSB); // LTRP POC LSB
3008    indices[ctr]      = i; 
3009    longtermPicsMSB[ctr] = longtermPicsPoc[ctr] - longtermPicsLSB[ctr];
3010  }
3011  Int numLongPics = rps->getNumberOfLongtermPictures();
3012  assert(ctr == numLongPics);
3013
3014  // Arrange pictures in decreasing order of MSB;
3015  for(i = 0; i < numLongPics; i++)
3016  {
3017    for(Int j = 0; j < numLongPics - 1; j++)
3018    {
3019      if(longtermPicsMSB[j] < longtermPicsMSB[j+1])
3020      {
3021        std::swap(longtermPicsPoc[j], longtermPicsPoc[j+1]);
3022        std::swap(longtermPicsLSB[j], longtermPicsLSB[j+1]);
3023        std::swap(longtermPicsMSB[j], longtermPicsMSB[j+1]);
3024        std::swap(indices[j]        , indices[j+1]        );
3025      }
3026    }
3027  }
3028
3029  for(i = 0; i < numLongPics; i++)
3030  {
3031    // Check if MSB present flag should be enabled.
3032    // Check if the buffer contains any pictures that have the same LSB.
3033    TComList<TComPic*>::iterator  iterPic = rcListPic.begin(); 
3034    TComPic*                      pcPic;
3035    while ( iterPic != rcListPic.end() )
3036    {
3037      pcPic = *iterPic;
3038      if( (getLSB(pcPic->getPOC(), maxPicOrderCntLSB) == longtermPicsLSB[i])   &&     // Same LSB
3039                                      (pcPic->getSlice(0)->isReferenced())     &&    // Reference picture
3040                                        (pcPic->getPOC() != longtermPicsPoc[i])    )  // Not the LTRP itself
3041      {
3042        mSBPresentFlag[i] = true;
3043        break;
3044      }
3045      iterPic++;     
3046    }
3047  }
3048
3049  // tempArray for usedByCurr flag
3050  Bool tempArray[MAX_NUM_REF_PICS]; ::memset(tempArray, 0, sizeof(tempArray));
3051  for(i = 0; i < numLongPics; i++)
3052  {
3053    tempArray[i] = rps->getUsed(indices[i]);
3054  }
3055  // Now write the final values;
3056  ctr = 0;
3057  Int currMSB = 0, currLSB = 0;
3058  // currPicPoc = currMSB + currLSB
3059  currLSB = getLSB(pcSlice->getPOC(), maxPicOrderCntLSB); 
3060  currMSB = pcSlice->getPOC() - currLSB;
3061
3062  for(i = rps->getNumberOfPictures() - 1; i >= offset; i--, ctr++)
3063  {
3064    rps->setPOC                   (i, longtermPicsPoc[ctr]);
3065    rps->setDeltaPOC              (i, - pcSlice->getPOC() + longtermPicsPoc[ctr]);
3066    rps->setUsed                  (i, tempArray[ctr]);
3067    rps->setPocLSBLT              (i, longtermPicsLSB[ctr]);
3068    rps->setDeltaPocMSBCycleLT    (i, (currMSB - (longtermPicsPoc[ctr] - longtermPicsLSB[ctr])) / maxPicOrderCntLSB);
3069    rps->setDeltaPocMSBPresentFlag(i, mSBPresentFlag[ctr]);     
3070
3071    assert(rps->getDeltaPocMSBCycleLT(i) >= 0);   // Non-negative value
3072  }
3073  for(i = rps->getNumberOfPictures() - 1, ctr = 1; i >= offset; i--, ctr++)
3074  {
3075    for(Int j = rps->getNumberOfPictures() - 1 - ctr; j >= offset; j--)
3076    {
3077      // Here at the encoder we know that we have set the full POC value for the LTRPs, hence we
3078      // don't have to check the MSB present flag values for this constraint.
3079      assert( rps->getPOC(i) != rps->getPOC(j) ); // If assert fails, LTRP entry repeated in RPS!!!
3080    }
3081  }
3082}
3083
3084/** Function for finding the position to insert the first of APS and non-nested BP, PT, DU info SEI messages.
3085 * \param accessUnit Access Unit of the current picture
3086 * This function finds the position to insert the first of APS and non-nested BP, PT, DU info SEI messages.
3087 */
3088Int TEncGOP::xGetFirstSeiLocation(AccessUnit &accessUnit)
3089{
3090  // Find the location of the first SEI message
3091  AccessUnit::iterator it;
3092  Int seiStartPos = 0;
3093  for(it = accessUnit.begin(); it != accessUnit.end(); it++, seiStartPos++)
3094  {
3095     if ((*it)->isSei() || (*it)->isVcl())
3096     {
3097       break;
3098     }               
3099  }
3100//  assert(it != accessUnit.end());  // Triggers with some legit configurations
3101  return seiStartPos;
3102}
3103
3104Void TEncGOP::dblMetric( TComPic* pcPic, UInt uiNumSlices )
3105{
3106  TComPicYuv* pcPicYuvRec = pcPic->getPicYuvRec();
3107  Pel* Rec    = pcPicYuvRec->getLumaAddr( 0 );
3108  Pel* tempRec = Rec;
3109  Int  stride = pcPicYuvRec->getStride();
3110  UInt log2maxTB = pcPic->getSlice(0)->getSPS()->getQuadtreeTULog2MaxSize();
3111  UInt maxTBsize = (1<<log2maxTB);
3112  const UInt minBlockArtSize = 8;
3113  const UInt picWidth = pcPicYuvRec->getWidth();
3114  const UInt picHeight = pcPicYuvRec->getHeight();
3115  const UInt noCol = (picWidth>>log2maxTB);
3116  const UInt noRows = (picHeight>>log2maxTB);
3117  assert(noCol > 1);
3118  assert(noRows > 1);
3119  UInt64 *colSAD = (UInt64*)malloc(noCol*sizeof(UInt64));
3120  UInt64 *rowSAD = (UInt64*)malloc(noRows*sizeof(UInt64));
3121  UInt colIdx = 0;
3122  UInt rowIdx = 0;
3123  Pel p0, p1, p2, q0, q1, q2;
3124 
3125  Int qp = pcPic->getSlice(0)->getSliceQp();
3126  Int bitdepthScale = 1 << (g_bitDepthY-8);
3127  Int beta = TComLoopFilter::getBeta( qp ) * bitdepthScale;
3128  const Int thr2 = (beta>>2);
3129  const Int thr1 = 2*bitdepthScale;
3130  UInt a = 0;
3131 
3132  memset(colSAD, 0, noCol*sizeof(UInt64));
3133  memset(rowSAD, 0, noRows*sizeof(UInt64));
3134 
3135  if (maxTBsize > minBlockArtSize)
3136  {
3137    // Analyze vertical artifact edges
3138    for(Int c = maxTBsize; c < picWidth; c += maxTBsize)
3139    {
3140      for(Int r = 0; r < picHeight; r++)
3141      {
3142        p2 = Rec[c-3];
3143        p1 = Rec[c-2];
3144        p0 = Rec[c-1];
3145        q0 = Rec[c];
3146        q1 = Rec[c+1];
3147        q2 = Rec[c+2];
3148        a = ((abs(p2-(p1<<1)+p0)+abs(q0-(q1<<1)+q2))<<1);
3149        if ( thr1 < a && a < thr2)
3150        {
3151          colSAD[colIdx] += abs(p0 - q0);
3152        }
3153        Rec += stride;
3154      }
3155      colIdx++;
3156      Rec = tempRec;
3157    }
3158   
3159    // Analyze horizontal artifact edges
3160    for(Int r = maxTBsize; r < picHeight; r += maxTBsize)
3161    {
3162      for(Int c = 0; c < picWidth; c++)
3163      {
3164        p2 = Rec[c + (r-3)*stride];
3165        p1 = Rec[c + (r-2)*stride];
3166        p0 = Rec[c + (r-1)*stride];
3167        q0 = Rec[c + r*stride];
3168        q1 = Rec[c + (r+1)*stride];
3169        q2 = Rec[c + (r+2)*stride];
3170        a = ((abs(p2-(p1<<1)+p0)+abs(q0-(q1<<1)+q2))<<1);
3171        if (thr1 < a && a < thr2)
3172        {
3173          rowSAD[rowIdx] += abs(p0 - q0);
3174        }
3175      }
3176      rowIdx++;
3177    }
3178  }
3179 
3180  UInt64 colSADsum = 0;
3181  UInt64 rowSADsum = 0;
3182  for(Int c = 0; c < noCol-1; c++)
3183  {
3184    colSADsum += colSAD[c];
3185  }
3186  for(Int r = 0; r < noRows-1; r++)
3187  {
3188    rowSADsum += rowSAD[r];
3189  }
3190 
3191  colSADsum <<= 10;
3192  rowSADsum <<= 10;
3193  colSADsum /= (noCol-1);
3194  colSADsum /= picHeight;
3195  rowSADsum /= (noRows-1);
3196  rowSADsum /= picWidth;
3197 
3198  UInt64 avgSAD = ((colSADsum + rowSADsum)>>1);
3199  avgSAD >>= (g_bitDepthY-8);
3200 
3201  if ( avgSAD > 2048 )
3202  {
3203    avgSAD >>= 9;
3204    Int offset = Clip3(2,6,(Int)avgSAD);
3205    for (Int i=0; i<uiNumSlices; i++)
3206    {
3207      pcPic->getSlice(i)->setDeblockingFilterOverrideFlag(true);
3208      pcPic->getSlice(i)->setDeblockingFilterDisable(false);
3209      pcPic->getSlice(i)->setDeblockingFilterBetaOffsetDiv2( offset );
3210      pcPic->getSlice(i)->setDeblockingFilterTcOffsetDiv2( offset );
3211    }
3212  }
3213  else
3214  {
3215    for (Int i=0; i<uiNumSlices; i++)
3216    {
3217      pcPic->getSlice(i)->setDeblockingFilterOverrideFlag(false);
3218      pcPic->getSlice(i)->setDeblockingFilterDisable(        pcPic->getSlice(i)->getPPS()->getPicDisableDeblockingFilterFlag() );
3219      pcPic->getSlice(i)->setDeblockingFilterBetaOffsetDiv2( pcPic->getSlice(i)->getPPS()->getDeblockingFilterBetaOffsetDiv2() );
3220      pcPic->getSlice(i)->setDeblockingFilterTcOffsetDiv2(   pcPic->getSlice(i)->getPPS()->getDeblockingFilterTcOffsetDiv2()   );
3221    }
3222  }
3223 
3224  free(colSAD);
3225  free(rowSAD);
3226}
3227
3228#if H_MV
3229Void TEncGOP::xSetRefPicListModificationsMv( std::vector<TComPic*> tempPicLists[2], TComSlice* pcSlice, UInt iGOPid )
3230{ 
3231 
3232  if( pcSlice->getSliceType() == I_SLICE || !(pcSlice->getPPS()->getListsModificationPresentFlag()) || pcSlice->getNumActiveRefLayerPics() == 0 )
3233  {
3234    return;
3235  }
3236 
3237  GOPEntry ge = m_pcCfg->getGOPEntry( (pcSlice->getRapPicFlag() && ( pcSlice->getLayerId( ) > 0) ) ? MAX_GOP : iGOPid );
3238  assert( ge.m_numActiveRefLayerPics == pcSlice->getNumActiveRefLayerPics() ); 
3239
3240  Int numPicsInTempList     = pcSlice->getNumRpsCurrTempList(); 
3241
3242  // GT: check if SliceType should be checked here.
3243  for (Int li = 0; li < 2; li ++) // Loop over lists L0 and L1
3244  {
3245    Int numPicsInFinalRefList = pcSlice->getNumRefIdx( ( li == 0 ) ? REF_PIC_LIST_0 : REF_PIC_LIST_1 ); 
3246           
3247    Int finalIdxToTempIdxMap[16];
3248    for( Int k = 0; k < 16; k++ )
3249    {
3250      finalIdxToTempIdxMap[ k ] = -1;
3251    }
3252
3253    Bool isModified = false;
3254    if ( numPicsInTempList > 1 )
3255    {
3256      for( Int k = 0; k < pcSlice->getNumActiveRefLayerPics(); k++ )
3257      {
3258        // get position in temp. list
3259        Int refPicLayerId = pcSlice->getRefPicLayerId(k);
3260        Int idxInTempList = 0; 
3261        for (; idxInTempList < numPicsInTempList; idxInTempList++)
3262        {
3263          if ( (tempPicLists[li][idxInTempList])->getLayerId() == refPicLayerId )
3264          {
3265            break; 
3266          }
3267        }
3268
3269        Int idxInFinalList = ge.m_interViewRefPosL[ li ][ k ];
3270       
3271        // Add negative from behind
3272        idxInFinalList = ( idxInFinalList < 0 )? ( numPicsInTempList + idxInFinalList ) : idxInFinalList; 
3273       
3274        Bool curIsModified = ( idxInFinalList != idxInTempList ) && ( ( idxInTempList < numPicsInFinalRefList ) || ( idxInFinalList < numPicsInFinalRefList ) ) ;
3275        if ( curIsModified )
3276        {
3277          isModified = true; 
3278          assert( finalIdxToTempIdxMap[ idxInFinalList ] == -1 ); // Assert when two inter layer reference pictures are sorted to the same position
3279        }
3280        finalIdxToTempIdxMap[ idxInFinalList ] = idxInTempList;             
3281      }
3282    }
3283
3284    TComRefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
3285    refPicListModification->setRefPicListModificationFlagL( li, isModified ); 
3286
3287    if( isModified )
3288    {
3289      Int refIdx = 0;
3290     
3291      for( Int i = 0; i < numPicsInFinalRefList; i++ )
3292      {
3293        if( finalIdxToTempIdxMap[i] >= 0 ) 
3294        {
3295          refPicListModification->setRefPicSetIdxL( li, i, finalIdxToTempIdxMap[i] );
3296        }
3297        else
3298        {
3299          ///* Fill gaps with temporal references *///
3300          // Forward inter layer reference pictures
3301          while( ( refIdx < numPicsInTempList ) && ( tempPicLists[li][refIdx]->getLayerId() != getLayerId())  )
3302          {
3303            refIdx++; 
3304          }
3305          refPicListModification->setRefPicSetIdxL( li, i, refIdx );
3306          refIdx++;
3307        }
3308      }
3309    }
3310  }
3311}
3312#endif
3313//! \}
Note: See TracBrowser for help on using the repository browser.