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

Last change on this file since 459 was 459, checked in by hhi, 11 years ago

Integation of depth intra methods in macro H_3D_DIM, including:

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