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

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

Further removal of unused macros.

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