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

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

Integrated following MV-HEVC HLS 7 items:

H_MV_HLS7_GEN Stub for further integrations (not tested)
H_MV_HLS_7_OUTPUT_LAYERS_5_10_22_27
Output layer sets, various

(VPS/P0300/alt output layer flag) #27 Change alt output layer flag to be signalled within the loop of output layer sets, from JCTVC-P0300-v2. Decision: Adopt.
(VPS/P0156/Num of output_layer_flag) #10 Proposal 3: The output_layer_flag[ i ][ j ] is signalled for j equal to 0 to NumLayersInIdList[ lsIdx ] inclusive. It was remarked that we might be able to just assume that the top layer is always output; however, this was not entirely clear , so the safe thing to do may be to also send the flag for this layer.
(VPS/P0295/Default output layer sets) #5 Discussion from (P0110). Decision: Three-state approach (text in P0295, decoder shall allow 3 to be present and shall treat 3 the same as the value 2).

H_MV_HLS_7_HRD_P0156_7 (HRD/P0156/MaxSubLayersInLayerSetMinus1) #7 Proposal 1: signal, in the VPS extension, the DPB parameters for an output layer set for sub-DPBs only up to the maximum temporal sub-layers in the corresponding layer set
H_MV_HLS_7_VPS_P0048_14
(VPS/P0048/profile_ref_minus1 rem) #14 Remove profile_ref_minus1 from the VPS extension, from JCTVC-P0048
H_MV_HLS_7_VPS_P0076_15 (VPS/P0076/video signal info move) #15 Move video signal information syntax structure earlier in the VPS VUI.
H_MV_HLS_7_SPS_P0155_16_32
(SPS/P0155/sps_sub_layer_ordering_info) #16, #32 Not signal the sps_max_num_reorder_pics[], sps_max_latency_increase_plus1[], and sps_max_dec_pic_buffering_minus1[] syntax elements in the SPS when nuh_layer_id > 0.
H_MV_HLS_7_GEN_P0166_PPS_EXTENSION (GEN/P0166/pps_extension) #17 Add PPS extension type flags for conditional presence of syntax extensions per extension type, aligned with the SPS extension type flags, from JCTVC-P0166. Further align the SPS extension type flags syntax between RExt and MV-HEVC/SHVC
H_MV_HLS_7_FIX_SET_DPB_SIZE
Fix derivation dpb size parameters
H_MV_HLS_7_RESERVED_FLAGS Added flags

(SPS/P0312/SHVC reserved flag) The flag will be used for the syntax vert_phase_position_enable_flag in SHVC draft
(VPS/O0215/SHVC reserved flag): this flag will be used for the syntax cross_layer_phase_alignment_flag in SHVC draft.
(VPS VUI/O0199,P0312/SHVC reserved flags) the 3 reserved bits will be used for the syntaxes single_layer_for_non_irap_flag, higher_layer_irap_skip_flag and vert_phase_position_not_in_use_flag in SHVC draft.

H_MV_FIX_VPS_LAYER_ID_NOT_EQUAL_ZERO Discard VPS with nuh_layer_Id > 0
H_MV_HLS_7_MISC_P0130_EOS
(MISC/P0130/EOS NAL layer id) #19 Require that end of bitstream NAL unit shall have nuh_layer_id equal to 0, from JCTVC-P0130. Decoders shall allow an end of bitstream NAL unit with nuh_layer_id > 0 to be present, and shall ignore the NAL unit.
H_MV_HLS_7_MISC_P0182_13 (MISC/P0182/BL PS Compatibility flag) #13 Define the flag (in VPS VUI) with the proposed semantics, without specifying an associated extraction process. Editors to select the position in the VPS VUI.
H_MV_HLS_7_MISC_P0068_21
(MISC/P0068/all irap idr flag) #21 Add flag in VUI to indicate that all IRAP pictures are IDRs and that all layer pictures in an AU are IDR aligned, from JCTVC-P0068 proposal 1.
H_MV_HLS_7_FIX_INFER_CROSS_LAYER_IRAP_ALIGNED_FLAG Fix inference of cross_layer_irap_aligned_flag
H_MV_HLS_7_MISC_P0079_18
(MISC/P0079/NumActiveRefLayerPics) #18 Modification of derivation of variable NumActiveRefLayerPics.

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