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

Last change on this file since 1124 was 1124, checked in by tech, 10 years ago

Merged branch 12.2-dev0@1123

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