source: 3DVCSoftware/branches/HTM-DEV-0.1-dev/source/Lib/TLibEncoder/TEncGOP.cpp @ 362

Last change on this file since 362 was 362, checked in by tech, 12 years ago

Update to HM-10.1.

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