source: 3DVCSoftware/branches/HTM-10.0-dev0/source/Lib/TLibEncoder/TEncGOP.cpp @ 852

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

Update HM-12.0 -> HM-13.0.

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