source: 3DVCSoftware/branches/HTM-14.0-MV-draft-3/source/Lib/TLibEncoder/TEncGOP.cpp @ 1350

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

Removed 3D-HEVC.

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