source: SHVCSoftware/branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncGOP.cpp @ 157

Last change on this file since 157 was 154, checked in by seregin, 12 years ago

set and check for avc_base_layer_flag

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