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

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