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

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

Merged 8.1-Cleanup@654

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