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

Last change on this file since 1103 was 1103, checked in by tech, 9 years ago

HHI_DEPENDENCY_SIGNALLING_I1_J0107: Integrated IdRefListLayers.

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