source: 3DVCSoftware/branches/HTM-DEV-0.3-dev2/source/Lib/TLibEncoder/TEncGOP.cpp @ 521

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

Integrated following changes:

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