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

Last change on this file since 186 was 185, checked in by qualcomm, 13 years ago

Bug fix in JCTVC_M0458_INTERLAYER_RPS_SIG

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