source: 3DVCSoftware/trunk/source/Lib/TLibEncoder/TEncGOP.cpp @ 744

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

Merged HTM-9.0-dev0@731. (MV-HEVC 6 HLS)

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