source: SHVCSoftware/branches/SHM-5.1-dev/source/Lib/TLibEncoder/TEncGOP.cpp @ 622

Last change on this file since 622 was 620, checked in by qualcomm, 11 years ago

Bug-fix in r612 and other bug-fix in SHM in case of IDR refresh.

From: Adarsh K. Ramasubramonian <aramasub@…>

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