source: SHVCSoftware/branches/SHM-3.1-dev/source/Lib/TLibEncoder/TEncGOP.cpp @ 375

Last change on this file since 375 was 374, checked in by nokia, 12 years ago

Integration of "early picture marking" of JCTVC-L0188 and fix to ILR_RESTR.

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