source: 3DVCSoftware/branches/HTM-12.2-dev2-HHI/source/Lib/TLibEncoder/TEncGOP.cpp @ 1106

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