source: 3DVCSoftware/branches/HTM-DEV-0.2-dev/source/Lib/TLibEncoder/TEncGOP.cpp @ 446

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

Added missing parts.

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