source: SHVCSoftware/branches/SHM-dev/source/Lib/TLibCommon/TComSlice.cpp @ 1502

Last change on this file since 1502 was 1502, checked in by seregin, 8 years ago

infer parameters in SPS after activation, fixing chroma scaling for non 4:2:0

  • Property svn:eol-style set to native
File size: 119.6 KB
Line 
1/* The copyright in this software is being made available under the BSD
2 * License, included below. This software may be subject to other third party
3 * and contributor rights, including patent rights, and no such rights are
4 * granted under this license.
5 *
6 * Copyright (c) 2010-2015, ITU/ISO/IEC
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
11 *
12 *  * Redistributions of source code must retain the above copyright notice,
13 *    this list of conditions and the following disclaimer.
14 *  * Redistributions in binary form must reproduce the above copyright notice,
15 *    this list of conditions and the following disclaimer in the documentation
16 *    and/or other materials provided with the distribution.
17 *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
18 *    be used to endorse or promote products derived from this software without
19 *    specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31 * THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34/** \file     TComSlice.cpp
35    \brief    slice header and SPS class
36*/
37
38#include "CommonDef.h"
39#include "TComSlice.h"
40#include "TComPic.h"
41#include "TLibEncoder/TEncSbac.h"
42#include "TLibDecoder/TDecSbac.h"
43
44
45//! \ingroup TLibCommon
46//! \{
47
48#if SVC_EXTENSION
49#include <numeric>
50ParameterSetMap<TComVPS> ParameterSetManager::m_vpsMap(MAX_NUM_VPS);
51ParameterSetMap<TComSPS> ParameterSetManager::m_spsMap(MAX_NUM_SPS);
52ParameterSetMap<TComPPS> ParameterSetManager::m_ppsMap(MAX_NUM_PPS);
53Int ParameterSetManager::m_activeVPSId = -1;
54#endif
55
56TComSlice::TComSlice()
57: m_iPPSId                        ( -1 )
58, m_PicOutputFlag                 ( true )
59, m_iPOC                          ( 0 )
60, m_iLastIDR                      ( 0 )
61, m_iAssociatedIRAP               ( 0 )
62, m_iAssociatedIRAPType           ( NAL_UNIT_INVALID )
63, m_pRPS                          ( 0 )
64, m_localRPS                      ( )
65, m_rpsIdx                        ( 0 )
66, m_RefPicListModification        ( )
67, m_eNalUnitType                  ( NAL_UNIT_CODED_SLICE_IDR_W_RADL )
68, m_eSliceType                    ( I_SLICE )
69, m_iSliceQp                      ( 0 )
70, m_dependentSliceSegmentFlag     ( false )
71#if ADAPTIVE_QP_SELECTION
72, m_iSliceQpBase                  ( 0 )
73#endif
74, m_ChromaQpAdjEnabled            ( false )
75, m_deblockingFilterDisable       ( false )
76, m_deblockingFilterOverrideFlag  ( false )
77, m_deblockingFilterBetaOffsetDiv2( 0 )
78, m_deblockingFilterTcOffsetDiv2  ( 0 )
79, m_bCheckLDC                     ( false )
80, m_iSliceQpDelta                 ( 0 )
81, m_iDepth                        ( 0 )
82, m_bRefenced                     ( false )
83, m_pcVPS                         ( NULL )
84, m_pcSPS                         ( NULL )
85, m_pcPPS                         ( NULL )
86, m_pcPic                         ( NULL )
87, m_colFromL0Flag                 ( true )
88, m_noOutputPriorPicsFlag         ( false )
89, m_noRaslOutputFlag              ( false )
90, m_handleCraAsBlaFlag            ( false )
91, m_colRefIdx                     ( 0 )
92, m_maxNumMergeCand               ( 0 )
93, m_uiTLayer                      ( 0 )
94, m_bTLayerSwitchingFlag          ( false )
95, m_sliceMode                     ( NO_SLICES )
96, m_sliceArgument                 ( 0 )
97, m_sliceCurStartCtuTsAddr        ( 0 )
98, m_sliceCurEndCtuTsAddr          ( 0 )
99, m_sliceIdx                      ( 0 )
100, m_sliceSegmentMode              ( NO_SLICES )
101, m_sliceSegmentArgument          ( 0 )
102, m_sliceSegmentCurStartCtuTsAddr ( 0 )
103, m_sliceSegmentCurEndCtuTsAddr   ( 0 )
104, m_nextSlice                     ( false )
105, m_nextSliceSegment              ( false )
106, m_sliceBits                     ( 0 )
107, m_sliceSegmentBits              ( 0 )
108, m_bFinalized                    ( false )
109, m_bTestWeightPred               ( false )
110, m_bTestWeightBiPred             ( false )
111, m_substreamSizes                ( )
112, m_cabacInitFlag                 ( false )
113, m_bLMvdL1Zero                   ( false )
114, m_temporalLayerNonReferenceFlag ( false )
115, m_LFCrossSliceBoundaryFlag      ( false )
116, m_enableTMVPFlag                ( true )
117, m_encCABACTableIdx              (I_SLICE)
118#if SVC_EXTENSION
119, m_firstSliceInPic               ( false )
120, m_availableForTMVPRefFlag       ( true )
121, m_layerId                       ( 0 )
122, m_bMFMEnabledFlag               ( false )
123, m_bDiscardableFlag              ( false )
124, m_bCrossLayerBLAFlag            ( false )
125, m_pocResetIdc                   ( 0 )
126, m_pocResetPeriodId              ( 0 )
127, m_fullPocResetFlag              ( false )
128, m_pocLsbVal                     ( 0 )
129, m_pocMsbVal                     ( 0 )
130, m_pocMsbValRequiredFlag         ( false )
131, m_pocMsbValPresentFlag          ( false )
132, m_pocMsbValNeeded               ( false )
133, m_picOrderCntLsb (0)
134#endif //SVC_EXTENSION
135{
136  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
137  {
138    m_aiNumRefIdx[i] = 0;
139  }
140
141#if SVC_EXTENSION
142  memset( m_pcBaseColPic, 0, sizeof( m_pcBaseColPic ) );
143  m_activeNumILRRefIdx        = 0; 
144  m_interLayerPredEnabledFlag = 0;
145  ::memset( m_interLayerPredLayerIdc, 0, sizeof(m_interLayerPredLayerIdc) );
146#endif //SVC_EXTENSION
147
148  for (UInt component = 0; component < MAX_NUM_COMPONENT; component++)
149  {
150    m_lambdas            [component] = 0.0;
151    m_iSliceChromaQpDelta[component] = 0;
152  }
153
154  initEqualRef();
155
156  for ( Int idx = 0; idx < MAX_NUM_REF; idx++ )
157  {
158    m_list1IdxToList0Idx[idx] = -1;
159  }
160
161  for(Int iNumCount = 0; iNumCount < MAX_NUM_REF; iNumCount++)
162  {
163    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
164    {
165      m_apcRefPicList [i][iNumCount] = NULL;
166      m_aiRefPOCList  [i][iNumCount] = 0;
167    }
168  }
169
170  resetWpScaling();
171  initWpAcDcParam();
172
173  for(Int ch=0; ch < MAX_NUM_CHANNEL_TYPE; ch++)
174  {
175    m_saoEnabledFlag[ch] = false;
176  }
177}
178
179TComSlice::~TComSlice()
180{
181}
182
183
184#if SVC_EXTENSION
185Void TComSlice::initSlice( UInt layerId )
186#else
187Void TComSlice::initSlice()
188#endif
189{
190#if SVC_EXTENSION
191  m_layerId                   = layerId;
192  m_activeNumILRRefIdx        = 0;
193  m_interLayerPredEnabledFlag = 0;
194  m_picOrderCntLsb            = 0;
195  m_pocResetIdc               = 0;
196  m_pocResetPeriodId          = 0;
197  m_fullPocResetFlag          = false;
198  m_pocLsbVal                 = 0;
199  m_pocMsbVal                 = 0;
200  m_pocMsbValRequiredFlag     = false;
201  m_pocMsbValPresentFlag      = false;
202  m_pocMsbValNeeded           = false;
203  m_pocResetDeltaPoc          = 0;
204#endif
205
206  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
207  {
208    m_aiNumRefIdx[i]      = 0;
209  }
210  m_colFromL0Flag = true;
211
212  m_colRefIdx = 0;
213  initEqualRef();
214
215  m_bCheckLDC = false;
216
217  for (UInt component = 0; component < MAX_NUM_COMPONENT; component++)
218  {
219    m_iSliceChromaQpDelta[component] = 0;
220  }
221
222  m_maxNumMergeCand = MRG_MAX_NUM_CANDS;
223
224  m_bFinalized=false;
225
226  m_substreamSizes.clear();
227  m_cabacInitFlag        = false;
228  m_enableTMVPFlag = true;
229}
230
231Bool TComSlice::getRapPicFlag() const
232{
233  return getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
234      || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
235      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
236      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
237      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
238      || getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA;
239}
240
241
242Void  TComSlice::sortPicList        (TComList<TComPic*>& rcListPic)
243{
244  TComPic*    pcPicExtract;
245  TComPic*    pcPicInsert;
246
247  TComList<TComPic*>::iterator    iterPicExtract;
248  TComList<TComPic*>::iterator    iterPicExtract_1;
249  TComList<TComPic*>::iterator    iterPicInsert;
250
251  for (Int i = 1; i < (Int)(rcListPic.size()); i++)
252  {
253    iterPicExtract = rcListPic.begin();
254    for (Int j = 0; j < i; j++)
255    {
256      iterPicExtract++;
257    }
258    pcPicExtract = *(iterPicExtract);
259    pcPicExtract->setCurrSliceIdx(0);
260
261    iterPicInsert = rcListPic.begin();
262    while (iterPicInsert != iterPicExtract)
263    {
264      pcPicInsert = *(iterPicInsert);
265      pcPicInsert->setCurrSliceIdx(0);
266      if (pcPicInsert->getPOC() >= pcPicExtract->getPOC())
267      {
268        break;
269      }
270
271      iterPicInsert++;
272    }
273
274    iterPicExtract_1 = iterPicExtract;    iterPicExtract_1++;
275
276    //  swap iterPicExtract and iterPicInsert, iterPicExtract = curr. / iterPicInsert = insertion position
277    rcListPic.insert (iterPicInsert, iterPicExtract, iterPicExtract_1);
278    rcListPic.erase  (iterPicExtract);
279  }
280}
281
282TComPic* TComSlice::xGetRefPic (TComList<TComPic*>& rcListPic, Int poc)
283{
284  TComList<TComPic*>::iterator  iterPic = rcListPic.begin();
285  TComPic*                      pcPic = *(iterPic);
286  while ( iterPic != rcListPic.end() )
287  {
288#if SVC_EXTENSION
289    if( pcPic->getPOC() == poc && pcPic->getSlice(0)->isReferenced() )
290#else
291    if(pcPic->getPOC() == poc)
292#endif
293    {
294      break;
295    }
296    iterPic++;
297#if SVC_EXTENSION
298    // return NULL, if picture with requested POC is not in the list, otherwise iterator goes outside of the list
299    if( iterPic == rcListPic.end() )
300    {
301      return NULL;
302    }
303#endif
304    pcPic = *(iterPic);
305  }
306#if SVC_EXTENSION
307  assert( pcPic->getSlice(0)->isReferenced() );
308#endif
309  return  pcPic;
310}
311
312
313TComPic* TComSlice::xGetLongTermRefPic(TComList<TComPic*>& rcListPic, Int poc, Bool pocHasMsb)
314{
315  TComList<TComPic*>::iterator  iterPic = rcListPic.begin();
316  TComPic*                      pcPic = *(iterPic);
317  TComPic*                      pcStPic = pcPic;
318
319  Int pocCycle = 1 << getSPS()->getBitsForPOC();
320  if (!pocHasMsb)
321  {
322    poc = poc & (pocCycle - 1);
323  }
324
325  while ( iterPic != rcListPic.end() )
326  {
327    pcPic = *(iterPic);
328    if (pcPic && pcPic->getPOC()!=this->getPOC() && pcPic->getSlice( 0 )->isReferenced())
329    {
330      Int picPoc = pcPic->getPOC();
331      if (!pocHasMsb)
332      {
333        picPoc = picPoc & (pocCycle - 1);
334      }
335
336      if (poc == picPoc)
337      {
338        if(pcPic->getIsLongTerm())
339        {
340          return pcPic;
341        }
342        else
343        {
344          pcStPic = pcPic;
345        }
346        break;
347      }
348    }
349
350    iterPic++;
351  }
352
353  return  pcStPic;
354}
355
356Void TComSlice::setRefPOCList       ()
357{
358  for (Int iDir = 0; iDir < NUM_REF_PIC_LIST_01; iDir++)
359  {
360    for (Int iNumRefIdx = 0; iNumRefIdx < m_aiNumRefIdx[iDir]; iNumRefIdx++)
361    {
362      m_aiRefPOCList[iDir][iNumRefIdx] = m_apcRefPicList[iDir][iNumRefIdx]->getPOC();
363    }
364  }
365
366}
367
368Void TComSlice::setList1IdxToList0Idx()
369{
370  Int idxL0, idxL1;
371  for ( idxL1 = 0; idxL1 < getNumRefIdx( REF_PIC_LIST_1 ); idxL1++ )
372  {
373    m_list1IdxToList0Idx[idxL1] = -1;
374    for ( idxL0 = 0; idxL0 < getNumRefIdx( REF_PIC_LIST_0 ); idxL0++ )
375    {
376      if ( m_apcRefPicList[REF_PIC_LIST_0][idxL0]->getPOC() == m_apcRefPicList[REF_PIC_LIST_1][idxL1]->getPOC() )
377      {
378        m_list1IdxToList0Idx[idxL1] = idxL0;
379        break;
380      }
381    }
382  }
383}
384
385#if SVC_EXTENSION
386Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr, TComPic** ilpPic)
387#else
388Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr )
389#endif
390{
391  if ( m_eSliceType == I_SLICE)
392  {
393    ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
394    ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
395
396    if (!checkNumPocTotalCurr)
397    {
398      return;
399    }
400  }
401
402  TComPic*  pcRefPic= NULL;
403  static const UInt MAX_NUM_NEGATIVE_PICTURES=16;
404  TComPic*  RefPicSetStCurr0[MAX_NUM_NEGATIVE_PICTURES];
405  TComPic*  RefPicSetStCurr1[MAX_NUM_NEGATIVE_PICTURES];
406  TComPic*  RefPicSetLtCurr[MAX_NUM_NEGATIVE_PICTURES];
407  UInt NumPicStCurr0 = 0;
408  UInt NumPicStCurr1 = 0;
409  UInt NumPicLtCurr = 0;
410  Int i;
411
412#if SVC_EXTENSION
413  if( m_layerId == 0 || ( m_layerId > 0 && ( m_activeNumILRRefIdx == 0 || !((getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP) && (getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA)) ) ) )
414  {
415#endif
416  for(i=0; i < m_pRPS->getNumberOfNegativePictures(); i++)
417  {
418    if(m_pRPS->getUsed(i))
419    {
420      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pRPS->getDeltaPOC(i));
421      pcRefPic->setIsLongTerm(0);
422      pcRefPic->getPicYuvRec()->extendPicBorder();
423      RefPicSetStCurr0[NumPicStCurr0] = pcRefPic;
424      NumPicStCurr0++;
425      pcRefPic->setCheckLTMSBPresent(false);
426    }
427  }
428
429  for(; i < m_pRPS->getNumberOfNegativePictures()+m_pRPS->getNumberOfPositivePictures(); i++)
430  {
431    if(m_pRPS->getUsed(i))
432    {
433      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pRPS->getDeltaPOC(i));
434      pcRefPic->setIsLongTerm(0);
435      pcRefPic->getPicYuvRec()->extendPicBorder();
436      RefPicSetStCurr1[NumPicStCurr1] = pcRefPic;
437      NumPicStCurr1++;
438      pcRefPic->setCheckLTMSBPresent(false);
439    }
440  }
441
442  for(i = m_pRPS->getNumberOfNegativePictures()+m_pRPS->getNumberOfPositivePictures()+m_pRPS->getNumberOfLongtermPictures()-1; i > m_pRPS->getNumberOfNegativePictures()+m_pRPS->getNumberOfPositivePictures()-1 ; i--)
443  {
444    if(m_pRPS->getUsed(i))
445    {
446      pcRefPic = xGetLongTermRefPic(rcListPic, m_pRPS->getPOC(i), m_pRPS->getCheckLTMSBPresent(i));
447      pcRefPic->setIsLongTerm(1);
448      pcRefPic->getPicYuvRec()->extendPicBorder();
449      RefPicSetLtCurr[NumPicLtCurr] = pcRefPic;
450      NumPicLtCurr++;
451    }
452    if(pcRefPic==NULL)
453    {
454      pcRefPic = xGetLongTermRefPic(rcListPic, m_pRPS->getPOC(i), m_pRPS->getCheckLTMSBPresent(i));
455    }
456    pcRefPic->setCheckLTMSBPresent(m_pRPS->getCheckLTMSBPresent(i));
457  }
458#if SVC_EXTENSION
459  }
460#endif
461
462  // ref_pic_list_init
463  TComPic*  rpsCurrList0[MAX_NUM_REF+1];
464  TComPic*  rpsCurrList1[MAX_NUM_REF+1];
465#if SVC_EXTENSION
466  Int numInterLayerRPSPics = 0;
467  if( m_layerId > 0 && m_activeNumILRRefIdx > 0 )
468  {
469    for( i=0; i < m_pcVPS->getNumDirectRefLayers( m_layerId ); i++ )
470    {
471      Int maxTidIlRefPicsPlus1 = getVPS()->getMaxTidIlRefPicsPlus1(ilpPic[i]->getSlice(0)->getLayerIdx(), getLayerIdx());
472
473      if( ((Int)(ilpPic[i]->getSlice(0)->getTLayer())<= maxTidIlRefPicsPlus1-1) || (maxTidIlRefPicsPlus1==0 && ilpPic[i]->getSlice(0)->getRapPicFlag() ) )
474      {
475        numInterLayerRPSPics++;
476
477        assert( ilpPic[i]->getSlice(0)->getDiscardableFlag() == 0 );    // Inter-layer RPS shall not contain picture with discardable_flag = 1.
478      }
479    }
480    if (numInterLayerRPSPics < m_activeNumILRRefIdx)
481    {
482      m_activeNumILRRefIdx = numInterLayerRPSPics;
483    }
484
485    // max one resampling direct layer
486    if( m_pcVPS->getScalabilityMask( SCALABILITY_ID ) )
487    {
488      Int numResampler = 0;
489
490      // motion resampling constraint
491      Int numMotionResamplers = 0;
492      Int refResamplingLayer[MAX_LAYERS];
493      memset( refResamplingLayer, 0, sizeof( refResamplingLayer ) );
494
495      for( i=0; i < m_activeNumILRRefIdx; i++ )
496      {
497        UInt refLayerIdc = m_interLayerPredLayerIdc[i];
498        UInt refLayerId = m_pcVPS->getRefLayerId( m_layerId, refLayerIdc );
499
500        const Window &scalEL = getPPS()->getScaledRefLayerWindowForLayer(refLayerId);
501
502        Int scalingOffset = ((scalEL.getWindowLeftOffset()   == 0 ) && 
503                             (scalEL.getWindowRightOffset()  == 0 ) && 
504                             (scalEL.getWindowTopOffset()    == 0 ) && 
505                             (scalEL.getWindowBottomOffset() == 0 ) 
506                            );
507
508        Bool sameBitDepths = ( m_pcSPS->getBitDepth(CHANNEL_TYPE_LUMA) == ilpPic[refLayerIdc]->getSlice(0)->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) ) && ( m_pcSPS->getBitDepth(CHANNEL_TYPE_CHROMA) == ilpPic[refLayerIdc]->getSlice(0)->getSPS()->getBitDepth(CHANNEL_TYPE_CHROMA) );
509
510        // motion resampling constraint
511        // Allow maximum of one motion resampling process for direct reference layers, and use motion inter-layer prediction from the same layer as texture inter-layer prediction
512        if( !( m_pcPic->getPosScalingFactor(refLayerIdc, 0) == POS_SCALING_FACTOR_1X && m_pcPic->getPosScalingFactor(refLayerIdc, 1) == POS_SCALING_FACTOR_1X ) || !scalingOffset || !sameBitDepths
513#if CGS_3D_ASYMLUT
514          || getPPS()->getCGSFlag()
515#endif
516          ) // ratio 1x
517        {
518          UInt predType = m_pcVPS->getDirectDependencyType( m_layerId, refLayerId ) + 1;
519
520          if( predType & 0x1 )
521          {
522            numResampler++;
523            refResamplingLayer[i] = refLayerIdc + 1;
524          }
525
526          if( predType & 0x2 )
527          {
528            numMotionResamplers++;
529            refResamplingLayer[i] -= refLayerIdc + 1;
530          }
531        }
532      }
533     
534      // When both picture sample values and picture motion field resampling processes are invoked for decoding of a particular picture, they shall be applied to the same reference layer picture.
535      if( m_activeNumILRRefIdx > 1 && numResampler > 0 )
536      {
537        for( i=0; i < m_activeNumILRRefIdx; i++ )
538        {
539          assert( refResamplingLayer[i] >= 0 && "Motion and sample inter-layer prediction shall be from the same layer" );
540        }
541      }
542
543      // Bitstream constraint for SHVC: The picture resampling process as specified in subclause G.8.1.4.1 shall not be invoked more than once for decoding of each particular picture.
544      assert(numResampler <= 1);
545      assert( numMotionResamplers <= 1  && "Up to 1 motion resampling is allowed" );
546    }
547  }
548  Int numPicTotalCurr = NumPicStCurr0 + NumPicStCurr1 + NumPicLtCurr + m_activeNumILRRefIdx;
549#else //SVC_EXTENSION
550  Int numPicTotalCurr = NumPicStCurr0 + NumPicStCurr1 + NumPicLtCurr;
551#endif //SVC_EXTENSION
552
553  if (checkNumPocTotalCurr)
554  {
555    // The variable NumPocTotalCurr is derived as specified in subclause 7.4.7.2. It is a requirement of bitstream conformance that the following applies to the value of NumPocTotalCurr:
556#if SVC_EXTENSION    // inter-layer prediction is allowed for BLA, CRA pictures of nuh_layer_id>0
557    // - If the current picture is a BLA or CRA picture with nuh_layer_id equal to 0, the value of NumPocTotalCurr shall be equal to 0.
558    // - Otherwise, when the current picture contains a P or B slice, the value of NumPocTotalCurr shall not be equal to 0.
559    if (getRapPicFlag() && getLayerId()==0)
560#else
561    // - If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
562    // - Otherwise, when the current picture contains a P or B slice, the value of NumPocTotalCurr shall not be equal to 0.
563    if (getRapPicFlag())
564#endif
565    {
566      assert(numPicTotalCurr == 0);
567    }
568
569    if (m_eSliceType == I_SLICE)
570    {
571      return;
572    }
573
574    assert(numPicTotalCurr > 0);
575    // general tier and level limit:
576    assert(numPicTotalCurr <= 8);
577  }
578
579  Int cIdx = 0;
580  for ( i=0; i<NumPicStCurr0; i++, cIdx++)
581  {
582    rpsCurrList0[cIdx] = RefPicSetStCurr0[i];
583  }
584
585#if SVC_EXTENSION
586    // initial reference picture list construction
587    if( m_layerId > 0 )
588    {     
589      for( i = 0; i < m_activeNumILRRefIdx && cIdx < numPicTotalCurr; cIdx ++, i ++)     
590      {
591        Int refLayerIdc = m_interLayerPredLayerIdc[i];
592        Int maxTidIlRefPicsPlus1 = getVPS()->getMaxTidIlRefPicsPlus1(ilpPic[refLayerIdc]->getSlice(0)->getLayerIdx(), getLayerIdx());
593        if( ((Int)(ilpPic[refLayerIdc]->getSlice(0)->getTLayer())<=maxTidIlRefPicsPlus1-1) || (maxTidIlRefPicsPlus1==0 && ilpPic[refLayerIdc]->getSlice(0)->getRapPicFlag()) )
594        {
595          rpsCurrList0[cIdx] = ilpPic[refLayerIdc];
596        }
597      }
598    }
599#endif //SVC_EXTENSION
600
601  for ( i=0; i<NumPicStCurr1; i++, cIdx++)
602  {
603    rpsCurrList0[cIdx] = RefPicSetStCurr1[i];
604  }
605  for ( i=0; i<NumPicLtCurr;  i++, cIdx++)
606  {
607    rpsCurrList0[cIdx] = RefPicSetLtCurr[i];
608  }
609  assert(cIdx == numPicTotalCurr);
610
611  if (m_eSliceType==B_SLICE)
612  {
613    cIdx = 0;
614    for ( i=0; i<NumPicStCurr1; i++, cIdx++)
615    {
616      rpsCurrList1[cIdx] = RefPicSetStCurr1[i];
617    }
618    for ( i=0; i<NumPicStCurr0; i++, cIdx++)
619    {
620      rpsCurrList1[cIdx] = RefPicSetStCurr0[i];
621    }
622    for ( i=0; i<NumPicLtCurr;  i++, cIdx++)
623    {
624      rpsCurrList1[cIdx] = RefPicSetLtCurr[i];
625    }   
626
627#if SVC_EXTENSION
628    if( m_layerId > 0 )
629    {
630      for( i = 0; i < m_activeNumILRRefIdx && cIdx < numPicTotalCurr; cIdx ++, i ++)
631      {
632        Int refLayerIdc = m_interLayerPredLayerIdc[i];
633        Int maxTidIlRefPicsPlus1 = getVPS()->getMaxTidIlRefPicsPlus1( ilpPic[refLayerIdc]->getSlice(0)->getLayerIdx(), getLayerIdx() );
634        if( ((Int)(ilpPic[refLayerIdc]->getSlice(0)->getTLayer())<=maxTidIlRefPicsPlus1-1) || (maxTidIlRefPicsPlus1==0 && ilpPic[refLayerIdc]->getSlice(0)->getRapPicFlag()) )
635        {
636          rpsCurrList1[cIdx] = ilpPic[refLayerIdc];
637        }
638      }
639    }
640#endif //SVC_EXTENSION
641
642    assert(cIdx == numPicTotalCurr);
643  }
644
645  ::memset(m_bIsUsedAsLongTerm, 0, sizeof(m_bIsUsedAsLongTerm));
646
647  for (Int rIdx = 0; rIdx < m_aiNumRefIdx[REF_PIC_LIST_0]; rIdx ++)
648  {
649    cIdx = m_RefPicListModification.getRefPicListModificationFlagL0() ? m_RefPicListModification.getRefPicSetIdxL0(rIdx) : rIdx % numPicTotalCurr;
650    assert(cIdx >= 0 && cIdx < numPicTotalCurr);
651    m_apcRefPicList[REF_PIC_LIST_0][rIdx] = rpsCurrList0[ cIdx ];
652
653#if SVC_EXTENSION
654    m_bIsUsedAsLongTerm[0][rIdx] = ( cIdx >= NumPicStCurr0 && cIdx < NumPicStCurr0 + m_activeNumILRRefIdx ) || ( cIdx >= NumPicStCurr0 + NumPicStCurr1 + m_activeNumILRRefIdx );
655#else
656    m_bIsUsedAsLongTerm[REF_PIC_LIST_0][rIdx] = ( cIdx >= NumPicStCurr0 + NumPicStCurr1 );
657#endif
658  }
659  if ( m_eSliceType != B_SLICE )
660  {
661    m_aiNumRefIdx[REF_PIC_LIST_1] = 0;
662    ::memset( m_apcRefPicList[REF_PIC_LIST_1], 0, sizeof(m_apcRefPicList[REF_PIC_LIST_1]));
663  }
664  else
665  {
666    for (Int rIdx = 0; rIdx < m_aiNumRefIdx[REF_PIC_LIST_1]; rIdx ++)
667    {
668      cIdx = m_RefPicListModification.getRefPicListModificationFlagL1() ? m_RefPicListModification.getRefPicSetIdxL1(rIdx) : rIdx % numPicTotalCurr;
669      assert(cIdx >= 0 && cIdx < numPicTotalCurr);
670      m_apcRefPicList[REF_PIC_LIST_1][rIdx] = rpsCurrList1[ cIdx ];
671      m_bIsUsedAsLongTerm[REF_PIC_LIST_1][rIdx] = ( cIdx >= NumPicStCurr0 + NumPicStCurr1 );
672    }
673  }
674}
675
676Int TComSlice::getNumRpsCurrTempList() const
677{
678  Int numRpsCurrTempList = 0;
679
680#if SVC_EXTENSION
681  if( m_eSliceType == I_SLICE || ( m_layerId && 
682    (m_eNalUnitType >= NAL_UNIT_CODED_SLICE_BLA_W_LP) &&
683    (m_eNalUnitType <= NAL_UNIT_CODED_SLICE_CRA) ) )
684#else
685  if (m_eSliceType == I_SLICE)
686#endif
687  {
688#if SVC_EXTENSION
689    return m_activeNumILRRefIdx;
690#else
691    return 0;
692#endif
693  }
694  for(UInt i=0; i < m_pRPS->getNumberOfNegativePictures()+ m_pRPS->getNumberOfPositivePictures() + m_pRPS->getNumberOfLongtermPictures(); i++)
695  {
696    if(m_pRPS->getUsed(i))
697    {
698      numRpsCurrTempList++;
699    }
700  }
701#if SVC_EXTENSION
702  if( m_layerId > 0 )
703  {
704    numRpsCurrTempList += m_activeNumILRRefIdx;
705  }
706#endif
707
708  return numRpsCurrTempList;
709}
710
711Void TComSlice::initEqualRef()
712{
713  for (Int iDir = 0; iDir < NUM_REF_PIC_LIST_01; iDir++)
714  {
715    for (Int iRefIdx1 = 0; iRefIdx1 < MAX_NUM_REF; iRefIdx1++)
716    {
717      for (Int iRefIdx2 = iRefIdx1; iRefIdx2 < MAX_NUM_REF; iRefIdx2++)
718      {
719        m_abEqualRef[iDir][iRefIdx1][iRefIdx2] = m_abEqualRef[iDir][iRefIdx2][iRefIdx1] = (iRefIdx1 == iRefIdx2? true : false);
720      }
721    }
722  }
723}
724
725Void TComSlice::checkColRefIdx(UInt curSliceIdx, TComPic* pic)
726{
727  Int i;
728  TComSlice* curSlice = pic->getSlice(curSliceIdx);
729  Int currColRefPOC =  curSlice->getRefPOC( RefPicList(1 - curSlice->getColFromL0Flag()), curSlice->getColRefIdx());
730  TComSlice* preSlice;
731  Int preColRefPOC;
732  for(i=curSliceIdx-1; i>=0; i--)
733  {
734    preSlice = pic->getSlice(i);
735    if(preSlice->getSliceType() != I_SLICE)
736    {
737      preColRefPOC  = preSlice->getRefPOC( RefPicList(1 - preSlice->getColFromL0Flag()), preSlice->getColRefIdx());
738      if(currColRefPOC != preColRefPOC)
739      {
740        printf("Collocated_ref_idx shall always be the same for all slices of a coded picture!\n");
741        exit(EXIT_FAILURE);
742      }
743      else
744      {
745        break;
746      }
747    }
748  }
749}
750
751Void TComSlice::checkCRA(const TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, NalUnitType& associatedIRAPType, TComList<TComPic *>& rcListPic)
752{
753  for(Int i = 0; i < pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i++)
754  {
755    if(pocCRA < MAX_UINT && getPOC() > pocCRA)
756    {
757      assert(getPOC()+pReferencePictureSet->getDeltaPOC(i) >= pocCRA);
758    }
759  }
760  for(Int i = pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i < pReferencePictureSet->getNumberOfPictures(); i++)
761  {
762    if(pocCRA < MAX_UINT && getPOC() > pocCRA)
763    {
764      if (!pReferencePictureSet->getCheckLTMSBPresent(i))
765      {
766        assert(xGetLongTermRefPic(rcListPic, pReferencePictureSet->getPOC(i), false)->getPOC() >= pocCRA);
767      }
768      else
769      {
770        assert(pReferencePictureSet->getPOC(i) >= pocCRA);
771      }
772    }
773  }
774  if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP ) // IDR picture found
775  {
776    pocCRA = getPOC();
777    associatedIRAPType = getNalUnitType();
778  }
779  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
780  {
781    pocCRA = getPOC();
782    associatedIRAPType = getNalUnitType();
783  }
784  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
785         || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
786         || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP ) // BLA picture found
787  {
788    pocCRA = getPOC();
789    associatedIRAPType = getNalUnitType();
790  }
791}
792
793/** Function for marking the reference pictures when an IDR/CRA/CRANT/BLA/BLANT is encountered.
794 * \param pocCRA POC of the CRA/CRANT/BLA/BLANT picture
795 * \param bRefreshPending flag indicating if a deferred decoding refresh is pending
796 * \param rcListPic reference to the reference picture list
797 * This function marks the reference pictures as "unused for reference" in the following conditions.
798 * If the nal_unit_type is IDR/BLA/BLANT, all pictures in the reference picture list
799 * are marked as "unused for reference"
800 *    If the nal_unit_type is BLA/BLANT, set the pocCRA to the temporal reference of the current picture.
801 * Otherwise
802 *    If the bRefreshPending flag is true (a deferred decoding refresh is pending) and the current
803 *    temporal reference is greater than the temporal reference of the latest CRA/CRANT/BLA/BLANT picture (pocCRA),
804 *    mark all reference pictures except the latest CRA/CRANT/BLA/BLANT picture as "unused for reference" and set
805 *    the bRefreshPending flag to false.
806 *    If the nal_unit_type is CRA/CRANT, set the bRefreshPending flag to true and pocCRA to the temporal
807 *    reference of the current picture.
808 * Note that the current picture is already placed in the reference list and its marking is not changed.
809 * If the current picture has a nal_ref_idc that is not 0, it will remain marked as "used for reference".
810 */
811#if NO_CLRAS_OUTPUT_FLAG
812Void TComSlice::decodingRefreshMarking( TComList<TComPic*>& rcListPic, Bool noClrasOutputFlag, UInt smallestLayerId )
813{
814  if( !isIRAP() )
815  {
816    return;
817  }
818
819  Int pocCurr = getPOC();
820  TComPic* rpcPic = NULL;
821
822  // When the current picture is an IRAP picture with nuh_layer_id equal to 0 and NoClrasOutputFlag is equal to 1,
823  // all reference pictures with any value of nuh_layer_id currently in the DPB (if any) are marked as "unused for reference".
824  if (m_layerId == smallestLayerId && noClrasOutputFlag)
825  {
826    // mark all pictures for all layers as not used for reference
827    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
828    while( iterPic != rcListPic.end() )
829    {
830      rpcPic = *(iterPic);
831      if( rpcPic->getPOC() != pocCurr )
832      {
833        rpcPic->getSlice(0)->setReferenced(false);
834      }
835      iterPic++;
836    }
837  }
838
839  // When the current picture is an IRAP picture with NoRaslOutputFlag equal to 1,
840  // all reference pictures with nuh_layer_id equal to currPicLayerId currently in the DPB (if any) are marked as "unused for reference".
841  if( m_noRaslOutputFlag )
842  {
843    // mark all pictures of a current layer as not used for reference
844    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
845    while( iterPic != rcListPic.end() )
846    {
847      rpcPic = *(iterPic);
848      if( rpcPic->getPOC() != pocCurr && rpcPic->getLayerId() == m_layerId )
849      {
850        rpcPic->getSlice(0)->setReferenced(false);
851      }
852      iterPic++;
853    }
854  }
855}
856
857Void TComSlice::decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic, Bool noClrasOutputFlag, const bool bEfficientFieldIRAPEnabled)
858#else
859Void TComSlice::decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic, const bool bEfficientFieldIRAPEnabled)
860#endif
861{
862  TComPic* rpcPic;
863  Int      pocCurr = getPOC();
864
865  if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
866    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
867    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
868    || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
869    || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )  // IDR or BLA picture
870  {
871    // mark all pictures as not used for reference
872    TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
873    while (iterPic != rcListPic.end())
874    {
875      rpcPic = *(iterPic);
876      rpcPic->setCurrSliceIdx(0);
877#if NO_CLRAS_OUTPUT_FLAG
878      if( noClrasOutputFlag )
879      {
880        rpcPic->getSlice(0)->setReferenced(false);  // all layers // TODO. This does not mark all layers
881      }
882      else
883      {
884        if( rpcPic->getLayerId() == m_layerId )
885        {
886          rpcPic->getSlice(0)->setReferenced(false);  // only current layer
887        }
888      }
889#else
890      if (rpcPic->getPOC() != pocCurr)
891      {
892        rpcPic->getSlice(0)->setReferenced(false);
893      }
894#endif
895      iterPic++;
896    }
897
898#if SVC_EXTENSION
899    m_pcPic->getSlice(0)->setReferenced(true);   // Mark the current picture back as refererced.
900#endif
901
902    if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
903      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
904      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
905    {
906      pocCRA = pocCurr;
907    }
908    if (bEfficientFieldIRAPEnabled)
909    {
910      bRefreshPending = true;
911    }
912  }
913  else // CRA or No DR
914  {
915    if(bEfficientFieldIRAPEnabled && (getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_IDR_N_LP || getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL))
916    {
917      if (bRefreshPending==true && pocCurr > m_iLastIDR) // IDR reference marking pending
918      {
919        TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
920        while (iterPic != rcListPic.end())
921        {
922          rpcPic = *(iterPic);
923          if (rpcPic->getPOC() != pocCurr && rpcPic->getPOC() != m_iLastIDR)
924          {
925            rpcPic->getSlice(0)->setReferenced(false);
926          }
927          iterPic++;
928        }
929        bRefreshPending = false; 
930      }
931    }
932    else
933    {
934      if (bRefreshPending==true && pocCurr > pocCRA) // CRA reference marking pending
935      {
936        TComList<TComPic*>::iterator iterPic = rcListPic.begin();
937        while (iterPic != rcListPic.end())
938        {
939          rpcPic = *(iterPic);
940          if (rpcPic->getPOC() != pocCurr && rpcPic->getPOC() != pocCRA)
941          {
942            rpcPic->getSlice(0)->setReferenced(false);
943          }
944          iterPic++;
945        }
946        bRefreshPending = false;
947      }
948    }
949    if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
950    {
951      bRefreshPending = true;
952      pocCRA = pocCurr;
953    }
954  }
955}
956
957Void TComSlice::copySliceInfo(TComSlice *pSrc)
958{
959  assert( pSrc != NULL );
960
961  Int i, j, k;
962
963  m_iPOC                 = pSrc->m_iPOC;
964  m_eNalUnitType         = pSrc->m_eNalUnitType;
965  m_eSliceType           = pSrc->m_eSliceType;
966  m_iSliceQp             = pSrc->m_iSliceQp;
967#if ADAPTIVE_QP_SELECTION
968  m_iSliceQpBase         = pSrc->m_iSliceQpBase;
969#endif
970  m_ChromaQpAdjEnabled = pSrc->m_ChromaQpAdjEnabled;
971  m_deblockingFilterDisable   = pSrc->m_deblockingFilterDisable;
972  m_deblockingFilterOverrideFlag = pSrc->m_deblockingFilterOverrideFlag;
973  m_deblockingFilterBetaOffsetDiv2 = pSrc->m_deblockingFilterBetaOffsetDiv2;
974  m_deblockingFilterTcOffsetDiv2 = pSrc->m_deblockingFilterTcOffsetDiv2;
975
976  for (i = 0; i < NUM_REF_PIC_LIST_01; i++)
977  {
978    m_aiNumRefIdx[i]     = pSrc->m_aiNumRefIdx[i];
979  }
980
981  for (i = 0; i < MAX_NUM_REF; i++)
982  {
983    m_list1IdxToList0Idx[i] = pSrc->m_list1IdxToList0Idx[i];
984  }
985
986  m_bCheckLDC             = pSrc->m_bCheckLDC;
987  m_iSliceQpDelta        = pSrc->m_iSliceQpDelta;
988  for (UInt component = 0; component < MAX_NUM_COMPONENT; component++)
989  {
990    m_iSliceChromaQpDelta[component] = pSrc->m_iSliceChromaQpDelta[component];
991  }
992  for (i = 0; i < NUM_REF_PIC_LIST_01; i++)
993  {
994    for (j = 0; j < MAX_NUM_REF; j++)
995    {
996      m_apcRefPicList[i][j]  = pSrc->m_apcRefPicList[i][j];
997      m_aiRefPOCList[i][j]   = pSrc->m_aiRefPOCList[i][j];
998      m_bIsUsedAsLongTerm[i][j] = pSrc->m_bIsUsedAsLongTerm[i][j];
999    }
1000    m_bIsUsedAsLongTerm[i][MAX_NUM_REF] = pSrc->m_bIsUsedAsLongTerm[i][MAX_NUM_REF];
1001  }
1002  m_iDepth               = pSrc->m_iDepth;
1003
1004  // referenced slice
1005  m_bRefenced            = pSrc->m_bRefenced;
1006
1007  // access channel
1008#if SVC_EXTENSION
1009  m_pcVPS                      = pSrc->m_pcVPS;
1010  m_layerId                    = pSrc->m_layerId;
1011  m_activeNumILRRefIdx         = pSrc->m_activeNumILRRefIdx;
1012  m_interLayerPredEnabledFlag  = pSrc->m_interLayerPredEnabledFlag;
1013  memcpy( m_interLayerPredLayerIdc, pSrc->m_interLayerPredLayerIdc, sizeof( m_interLayerPredLayerIdc ) );
1014#endif
1015  m_pRPS                = pSrc->m_pRPS;
1016  m_iLastIDR             = pSrc->m_iLastIDR;
1017
1018  m_pcPic                = pSrc->m_pcPic;
1019
1020  m_colFromL0Flag        = pSrc->m_colFromL0Flag;
1021  m_colRefIdx            = pSrc->m_colRefIdx;
1022
1023  setLambdas(pSrc->getLambdas());
1024
1025  for (i = 0; i < NUM_REF_PIC_LIST_01; i++)
1026  {
1027    for (j = 0; j < MAX_NUM_REF; j++)
1028    {
1029      for (k =0; k < MAX_NUM_REF; k++)
1030      {
1031        m_abEqualRef[i][j][k] = pSrc->m_abEqualRef[i][j][k];
1032      }
1033    }
1034  }
1035
1036  m_uiTLayer                      = pSrc->m_uiTLayer;
1037  m_bTLayerSwitchingFlag          = pSrc->m_bTLayerSwitchingFlag;
1038
1039  m_sliceMode                     = pSrc->m_sliceMode;
1040  m_sliceArgument                 = pSrc->m_sliceArgument;
1041  m_sliceCurStartCtuTsAddr        = pSrc->m_sliceCurStartCtuTsAddr;
1042  m_sliceCurEndCtuTsAddr          = pSrc->m_sliceCurEndCtuTsAddr;
1043  m_sliceIdx                      = pSrc->m_sliceIdx;
1044  m_sliceSegmentMode              = pSrc->m_sliceSegmentMode;
1045  m_sliceSegmentArgument          = pSrc->m_sliceSegmentArgument;
1046  m_sliceSegmentCurStartCtuTsAddr = pSrc->m_sliceSegmentCurStartCtuTsAddr;
1047  m_sliceSegmentCurEndCtuTsAddr   = pSrc->m_sliceSegmentCurEndCtuTsAddr;
1048  m_nextSlice                     = pSrc->m_nextSlice;
1049  m_nextSliceSegment              = pSrc->m_nextSliceSegment;
1050
1051  for ( UInt e=0 ; e<NUM_REF_PIC_LIST_01 ; e++ )
1052  {
1053    for ( UInt n=0 ; n<MAX_NUM_REF ; n++ )
1054    {
1055      memcpy(m_weightPredTable[e][n], pSrc->m_weightPredTable[e][n], sizeof(WPScalingParam)*MAX_NUM_COMPONENT );
1056    }
1057  }
1058
1059  for( UInt ch = 0 ; ch < MAX_NUM_CHANNEL_TYPE; ch++)
1060  {
1061    m_saoEnabledFlag[ch] = pSrc->m_saoEnabledFlag[ch];
1062  }
1063
1064  m_cabacInitFlag                 = pSrc->m_cabacInitFlag;
1065
1066  m_bLMvdL1Zero                   = pSrc->m_bLMvdL1Zero;
1067  m_LFCrossSliceBoundaryFlag      = pSrc->m_LFCrossSliceBoundaryFlag;
1068  m_enableTMVPFlag                = pSrc->m_enableTMVPFlag;
1069  m_maxNumMergeCand               = pSrc->m_maxNumMergeCand;
1070  m_encCABACTableIdx              = pSrc->m_encCABACTableIdx;
1071}
1072
1073
1074/** Function for setting the slice's temporal layer ID and corresponding temporal_layer_switching_point_flag.
1075 * \param uiTLayer Temporal layer ID of the current slice
1076 * The decoder calls this function to set temporal_layer_switching_point_flag for each temporal layer based on
1077 * the SPS's temporal_id_nesting_flag and the parsed PPS.  Then, current slice's temporal layer ID and
1078 * temporal_layer_switching_point_flag is set accordingly.
1079 */
1080Void TComSlice::setTLayerInfo( UInt uiTLayer )
1081{
1082  m_uiTLayer = uiTLayer;
1083}
1084
1085/** Function for checking if this is a switching-point
1086*/
1087Bool TComSlice::isTemporalLayerSwitchingPoint(TComList<TComPic*>& rcListPic)
1088{
1089  TComPic* rpcPic;
1090  // loop through all pictures in the reference picture buffer
1091  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1092  while ( iterPic != rcListPic.end())
1093  {
1094    rpcPic = *(iterPic++);
1095    if(rpcPic->getSlice(0)->isReferenced() && rpcPic->getPOC() != getPOC())
1096    {
1097      if(rpcPic->getTLayer() >= getTLayer())
1098      {
1099        return false;
1100      }
1101    }
1102  }
1103  return true;
1104}
1105
1106/** Function for checking if this is a STSA candidate
1107 */
1108Bool TComSlice::isStepwiseTemporalLayerSwitchingPointCandidate(TComList<TComPic*>& rcListPic)
1109{
1110  TComPic* rpcPic;
1111
1112  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1113  while ( iterPic != rcListPic.end())
1114  {
1115    rpcPic = *(iterPic++);
1116    if(rpcPic->getSlice(0)->isReferenced() &&  (rpcPic->getUsedByCurr()==true) && rpcPic->getPOC() != getPOC())
1117    {
1118      if(rpcPic->getTLayer() >= getTLayer())
1119      {
1120        return false;
1121      }
1122    }
1123  }
1124  return true;
1125}
1126
1127#if SVC_POC
1128Void TComSlice::checkLeadingPictureRestrictions(TComList<TComPic*>& rcListPic, Bool usePocBeforeReset)
1129#else
1130Void TComSlice::checkLeadingPictureRestrictions(TComList<TComPic*>& rcListPic)
1131#endif
1132{
1133  TComPic* rpcPic;
1134
1135  Int nalUnitType = this->getNalUnitType();
1136
1137  // When a picture is a leading picture, it shall be a RADL or RASL picture.
1138  if(this->getAssociatedIRAPPOC() > this->getPOC())
1139  {
1140    // Do not check IRAP pictures since they may get a POC lower than their associated IRAP
1141    if(nalUnitType < NAL_UNIT_CODED_SLICE_BLA_W_LP ||
1142       nalUnitType > NAL_UNIT_RESERVED_IRAP_VCL23)
1143    {
1144      assert(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1145             nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R ||
1146             nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
1147             nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R);
1148    }
1149  }
1150
1151  // When a picture is a trailing picture, it shall not be a RADL or RASL picture.
1152  if(this->getAssociatedIRAPPOC() < this->getPOC())
1153  {
1154    assert(nalUnitType != NAL_UNIT_CODED_SLICE_RASL_N &&
1155           nalUnitType != NAL_UNIT_CODED_SLICE_RASL_R &&
1156           nalUnitType != NAL_UNIT_CODED_SLICE_RADL_N &&
1157           nalUnitType != NAL_UNIT_CODED_SLICE_RADL_R);
1158  }
1159
1160  // No RASL pictures shall be present in the bitstream that are associated
1161  // with a BLA picture having nal_unit_type equal to BLA_W_RADL or BLA_N_LP.
1162  if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1163     nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
1164  {
1165    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_W_RADL &&
1166           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_N_LP);
1167  }
1168
1169  // No RASL pictures shall be present in the bitstream that are associated with
1170  // an IDR picture.
1171  if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1172     nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
1173  {
1174    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_N_LP   &&
1175           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_W_RADL);
1176  }
1177
1178  // No RADL pictures shall be present in the bitstream that are associated with
1179  // a BLA picture having nal_unit_type equal to BLA_N_LP or that are associated
1180  // with an IDR picture having nal_unit_type equal to IDR_N_LP.
1181  if(nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
1182     nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R)
1183  {
1184    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_N_LP   &&
1185           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_N_LP);
1186  }
1187
1188  // loop through all pictures in the reference picture buffer
1189  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1190  while ( iterPic != rcListPic.end())
1191  {
1192    rpcPic = *(iterPic++);
1193    if(!rpcPic->getReconMark())
1194    {
1195      continue;
1196    }
1197    if (rpcPic->getPOC() == this->getPOC())
1198    {
1199      continue;
1200    }
1201
1202    // Any picture that has PicOutputFlag equal to 1 that precedes an IRAP picture
1203    // in decoding order shall precede the IRAP picture in output order.
1204    // (Note that any picture following in output order would be present in the DPB)
1205    if(rpcPic->getSlice(0)->getPicOutputFlag() == 1 && !this->getNoOutputPriorPicsFlag())
1206    {
1207      if(nalUnitType == NAL_UNIT_CODED_SLICE_BLA_N_LP    ||
1208         nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_LP    ||
1209         nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_RADL  ||
1210         nalUnitType == NAL_UNIT_CODED_SLICE_CRA         ||
1211         nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP    ||
1212         nalUnitType == NAL_UNIT_CODED_SLICE_IDR_W_RADL)
1213      {
1214#if SVC_POC
1215        if( usePocBeforeReset )
1216        {
1217          assert(rpcPic->getSlice(0)->getPocValueBeforeReset() < this->getPocValueBeforeReset());
1218        }
1219        else
1220        {
1221          assert(rpcPic->getPOC() < this->getPOC());
1222        }
1223#else
1224        assert(rpcPic->getPOC() < this->getPOC());
1225#endif
1226      }
1227    }
1228
1229    // Any picture that has PicOutputFlag equal to 1 that precedes an IRAP picture
1230    // in decoding order shall precede any RADL picture associated with the IRAP
1231    // picture in output order.
1232    if(rpcPic->getSlice(0)->getPicOutputFlag() == 1)
1233    {
1234      if((nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
1235          nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R))
1236      {
1237        // rpcPic precedes the IRAP in decoding order
1238        if(this->getAssociatedIRAPPOC() > rpcPic->getSlice(0)->getAssociatedIRAPPOC())
1239        {
1240          // rpcPic must not be the IRAP picture
1241          if(this->getAssociatedIRAPPOC() != rpcPic->getPOC())
1242          {
1243#if SVC_POC
1244            if( usePocBeforeReset )
1245            {
1246              assert(rpcPic->getSlice(0)->getPocValueBeforeReset() < this->getPocValueBeforeReset());
1247            }
1248            else
1249            {
1250              assert(rpcPic->getPOC() < this->getPOC());
1251            }
1252#else
1253            assert(rpcPic->getPOC() < this->getPOC());
1254#endif
1255          }
1256        }
1257      }
1258    }
1259
1260    // When a picture is a leading picture, it shall precede, in decoding order,
1261    // all trailing pictures that are associated with the same IRAP picture.
1262      if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1263         nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R ||
1264         nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
1265         nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R)
1266      {
1267        if(rpcPic->getSlice(0)->getAssociatedIRAPPOC() == this->getAssociatedIRAPPOC())
1268        {
1269          // rpcPic is a picture that preceded the leading in decoding order since it exist in the DPB
1270          // rpcPic would violate the constraint if it was a trailing picture
1271#if SVC_POC
1272          if( usePocBeforeReset )
1273          {
1274            assert(rpcPic->getPOC() <= this->getAssociatedIrapPocBeforeReset());
1275          }
1276          else
1277          {
1278            assert(rpcPic->getPOC() <= this->getAssociatedIRAPPOC());
1279          }
1280#else
1281          assert(rpcPic->getPOC() <= this->getAssociatedIRAPPOC());
1282#endif
1283        }
1284      }
1285
1286    // Any RASL picture associated with a CRA or BLA picture shall precede any
1287    // RADL picture associated with the CRA or BLA picture in output order
1288    if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1289       nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
1290    {
1291      if((this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_N_LP   ||
1292          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_W_LP   ||
1293          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL ||
1294          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_CRA)       &&
1295          this->getAssociatedIRAPPOC() == rpcPic->getSlice(0)->getAssociatedIRAPPOC())
1296      {
1297        if(rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N ||
1298           rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_R)
1299        {
1300          assert(rpcPic->getPOC() > this->getPOC());
1301        }
1302      }
1303    }
1304
1305    // Any RASL picture associated with a CRA picture shall follow, in output
1306    // order, any IRAP picture that precedes the CRA picture in decoding order.
1307    if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1308       nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
1309    {
1310      if(this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_CRA)
1311      {
1312        if(rpcPic->getSlice(0)->getPOC() < this->getAssociatedIRAPPOC() &&
1313           (rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP   ||
1314            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP   ||
1315            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL ||
1316            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP   ||
1317            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL ||
1318            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA))
1319        {
1320          assert(this->getPOC() > rpcPic->getSlice(0)->getPOC());
1321        }
1322      }
1323    }
1324  }
1325}
1326
1327
1328
1329/** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
1330*/
1331Void TComSlice::applyReferencePictureSet( TComList<TComPic*>& rcListPic, const TComReferencePictureSet *pReferencePictureSet)
1332{
1333  TComPic* rpcPic;
1334  Int i, isReference;
1335
1336#if !ALIGNED_BUMPING
1337  checkLeadingPictureRestrictions(rcListPic);
1338#endif
1339
1340  // loop through all pictures in the reference picture buffer
1341  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1342  while ( iterPic != rcListPic.end())
1343  {
1344    rpcPic = *(iterPic++);
1345
1346    if(!rpcPic->getSlice( 0 )->isReferenced())
1347    {
1348      continue;
1349    }
1350
1351    isReference = 0;
1352    // loop through all pictures in the Reference Picture Set
1353    // to see if the picture should be kept as reference picture
1354    for(i=0;i<pReferencePictureSet->getNumberOfPositivePictures()+pReferencePictureSet->getNumberOfNegativePictures();i++)
1355    {
1356      if(!rpcPic->getIsLongTerm() && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i))
1357      {
1358        isReference = 1;
1359        rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
1360        rpcPic->setIsLongTerm(0);
1361      }
1362    }
1363    for(;i<pReferencePictureSet->getNumberOfPictures();i++)
1364    {
1365      if(pReferencePictureSet->getCheckLTMSBPresent(i)==true)
1366      {
1367        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()) == pReferencePictureSet->getPOC(i))
1368        {
1369          isReference = 1;
1370          rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
1371        }
1372      }
1373      else
1374      {
1375        Int pocCycle = 1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
1376        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC() & (pocCycle-1);
1377        Int refPoc = pReferencePictureSet->getPOC(i) & (pocCycle-1);
1378        if(rpcPic->getIsLongTerm() && curPoc == refPoc)
1379        {
1380          isReference = 1;
1381          rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
1382        }
1383      }
1384
1385    }
1386
1387#if SVC_EXTENSION
1388    if( isReference ) // Current picture is in the temporal RPS
1389    {
1390      assert( rpcPic->getSlice(0)->getDiscardableFlag() == 0 ); // Temporal RPS shall not contain picture with discardable_flag equal to 1
1391    }
1392#endif
1393
1394    // mark the picture as "unused for reference" if it is not in
1395    // the Reference Picture Set
1396    if(rpcPic->getPicSym()->getSlice(0)->getPOC() != this->getPOC() && isReference == 0)
1397    {
1398      rpcPic->getSlice( 0 )->setReferenced( false );
1399      rpcPic->setUsedByCurr(0);
1400      rpcPic->setIsLongTerm(0);
1401    }
1402    //check that pictures of higher temporal layers are not used
1403    assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getUsedByCurr()==0||rpcPic->getTLayer()<=this->getTLayer());
1404    //check that pictures of higher or equal temporal layer are not in the RPS if the current picture is a TSA picture
1405    if(this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R || this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N)
1406    {
1407      assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getTLayer()<this->getTLayer());
1408    }
1409    //check that pictures marked as temporal layer non-reference pictures are not used for reference
1410    if(rpcPic->getPicSym()->getSlice(0)->getPOC() != this->getPOC() && rpcPic->getTLayer()==this->getTLayer())
1411    {
1412      assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getUsedByCurr()==0||rpcPic->getSlice( 0 )->getTemporalLayerNonReferenceFlag()==false);
1413    }
1414  }
1415}
1416
1417/** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
1418*/
1419Int TComSlice::checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, const TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess, Bool bUseRecoveryPoint)
1420{
1421  Int atLeastOneUnabledByRecoveryPoint = 0;
1422  Int atLeastOneFlushedByPreviousIDR = 0;
1423  TComPic* rpcPic;
1424  Int i, isAvailable;
1425  Int atLeastOneLost = 0;
1426  Int atLeastOneRemoved = 0;
1427  Int iPocLost = 0;
1428
1429  // loop through all long-term pictures in the Reference Picture Set
1430  // to see if the picture should be kept as reference picture
1431  for(i=pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures();i<pReferencePictureSet->getNumberOfPictures();i++)
1432  {
1433    isAvailable = 0;
1434    // loop through all pictures in the reference picture buffer
1435    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1436    while ( iterPic != rcListPic.end())
1437    {
1438      rpcPic = *(iterPic++);
1439      if(pReferencePictureSet->getCheckLTMSBPresent(i)==true)
1440      {
1441        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()) == pReferencePictureSet->getPOC(i) && rpcPic->getSlice(0)->isReferenced())
1442        {
1443          if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
1444          {
1445            isAvailable = 0;
1446          }
1447          else
1448          {
1449            isAvailable = 1;
1450          }
1451        }
1452      }
1453      else
1454      {
1455        Int pocCycle = 1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
1456        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC() & (pocCycle-1);
1457        Int refPoc = pReferencePictureSet->getPOC(i) & (pocCycle-1);
1458        if(rpcPic->getIsLongTerm() && curPoc == refPoc && rpcPic->getSlice(0)->isReferenced())
1459        {
1460          if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
1461          {
1462            isAvailable = 0;
1463          }
1464          else
1465          {
1466            isAvailable = 1;
1467          }
1468        }
1469      }
1470    }
1471    // if there was no such long-term check the short terms
1472    if(!isAvailable)
1473    {
1474      iterPic = rcListPic.begin();
1475      while ( iterPic != rcListPic.end())
1476      {
1477        rpcPic = *(iterPic++);
1478
1479        Int pocCycle = 1 << rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
1480        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC();
1481        Int refPoc = pReferencePictureSet->getPOC(i);
1482        if (!pReferencePictureSet->getCheckLTMSBPresent(i))
1483        {
1484          curPoc = curPoc & (pocCycle - 1);
1485          refPoc = refPoc & (pocCycle - 1);
1486        }
1487
1488        if (rpcPic->getSlice(0)->isReferenced() && curPoc == refPoc)
1489        {
1490          if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
1491          {
1492            isAvailable = 0;
1493          }
1494          else
1495          {
1496            isAvailable = 1;
1497            rpcPic->setIsLongTerm(1);
1498            break;
1499          }
1500        }
1501      }
1502    }
1503    // report that a picture is lost if it is in the Reference Picture Set
1504    // but not available as reference picture
1505    if(isAvailable == 0)
1506    {
1507      if (this->getPOC() + pReferencePictureSet->getDeltaPOC(i) >= pocRandomAccess)
1508      {
1509        if(!pReferencePictureSet->getUsed(i) )
1510        {
1511          if(printErrors)
1512          {
1513            printf("\nLong-term reference picture with POC = %3d seems to have been removed or not correctly decoded.", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
1514          }
1515          atLeastOneRemoved = 1;
1516        }
1517        else
1518        {
1519          if(printErrors)
1520          {
1521            printf("\nLong-term reference picture with POC = %3d is lost or not correctly decoded!", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
1522          }
1523          atLeastOneLost = 1;
1524          iPocLost=this->getPOC() + pReferencePictureSet->getDeltaPOC(i);
1525        }
1526      }
1527      else if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess)
1528      {
1529        atLeastOneUnabledByRecoveryPoint = 1;
1530      }
1531      else if(bUseRecoveryPoint && (this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_N_LP || this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_W_RADL))
1532      {
1533        atLeastOneFlushedByPreviousIDR = 1;
1534      }
1535    }
1536  }
1537  // loop through all short-term pictures in the Reference Picture Set
1538  // to see if the picture should be kept as reference picture
1539  for(i=0;i<pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures();i++)
1540  {
1541    isAvailable = 0;
1542    // loop through all pictures in the reference picture buffer
1543    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1544    while ( iterPic != rcListPic.end())
1545    {
1546      rpcPic = *(iterPic++);
1547
1548      if(!rpcPic->getIsLongTerm() && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i) && rpcPic->getSlice(0)->isReferenced())
1549      {
1550        if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
1551        {
1552          isAvailable = 0;
1553        }
1554        else
1555        {
1556          isAvailable = 1;
1557        }
1558      }
1559    }
1560    // report that a picture is lost if it is in the Reference Picture Set
1561    // but not available as reference picture
1562    if(isAvailable == 0)
1563    {
1564#if !UNAVAILABLE_PIC_BUGFIX
1565      if (this->getPOC() + pReferencePictureSet->getDeltaPOC(i) >= pocRandomAccess)
1566#endif
1567      {
1568        if(!pReferencePictureSet->getUsed(i) )
1569        {
1570          if(printErrors)
1571          {
1572            printf("\nShort-term reference picture with POC = %3d seems to have been removed or not correctly decoded.", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
1573          }
1574          atLeastOneRemoved = 1;
1575        }
1576        else
1577        {
1578          if(printErrors)
1579          {
1580            printf("\nShort-term reference picture with POC = %3d is lost or not correctly decoded!", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
1581          }
1582          atLeastOneLost = 1;
1583          iPocLost=this->getPOC() + pReferencePictureSet->getDeltaPOC(i);
1584        }
1585      }
1586#if UNAVAILABLE_PIC_BUGFIX
1587      if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess)
1588#else
1589      else if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess)
1590#endif
1591      {
1592        atLeastOneUnabledByRecoveryPoint = 1;
1593      }
1594      else if(bUseRecoveryPoint && (this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_N_LP || this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_W_RADL))
1595      {
1596        atLeastOneFlushedByPreviousIDR = 1;
1597      }
1598    }
1599  }
1600
1601  if(atLeastOneUnabledByRecoveryPoint || atLeastOneFlushedByPreviousIDR)
1602  {
1603    return -1;
1604  }   
1605  if(atLeastOneLost)
1606  {
1607    return iPocLost+1;
1608  }
1609  if(atLeastOneRemoved)
1610  {
1611    return -2;
1612  }
1613  else
1614  {
1615    return 0;
1616  }
1617}
1618
1619/** Function for constructing an explicit Reference Picture Set out of the available pictures in a referenced Reference Picture Set
1620*/
1621Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, const TComReferencePictureSet *pReferencePictureSet, Bool isRAP, Int pocRandomAccess, Bool bUseRecoveryPoint, const Bool bEfficientFieldIRAPEnabled)
1622{
1623  TComPic* rpcPic;
1624  Int i, j;
1625  Int k = 0;
1626  Int nrOfNegativePictures = 0;
1627  Int nrOfPositivePictures = 0;
1628  TComReferencePictureSet* pLocalRPS = this->getLocalRPS();
1629  (*pLocalRPS)=TComReferencePictureSet();
1630
1631  Bool irapIsInRPS = false; // Used when bEfficientFieldIRAPEnabled==true
1632#if SVC_POC
1633  Bool pocsAdjusted = false;
1634#endif
1635
1636  // loop through all pictures in the Reference Picture Set
1637  for(i=0;i<pReferencePictureSet->getNumberOfPictures();i++)
1638  {
1639    j = 0;
1640    // loop through all pictures in the reference picture buffer
1641    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1642    while ( iterPic != rcListPic.end())
1643    {
1644      j++;
1645      rpcPic = *(iterPic++);
1646
1647#if SVC_POC
1648      // poc adjustement by poc reset needs to be taken into account here
1649      Int deltaPOC = pReferencePictureSet->getDeltaPOC(i) - rpcPic->getPicSym()->getSlice(0)->getPocResetDeltaPoc();
1650      if (rpcPic->getPicSym()->getSlice(0)->getPocResetDeltaPoc() != 0)
1651      {
1652        pocsAdjusted = true;
1653      }
1654
1655      if (rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + deltaPOC && rpcPic->getSlice(0)->isReferenced())
1656#else
1657      if(rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i) && rpcPic->getSlice(0)->isReferenced())
1658#endif
1659      {
1660        // This picture exists as a reference picture
1661        // and should be added to the explicit Reference Picture Set
1662#if SVC_POC
1663        pLocalRPS->setDeltaPOC(k, deltaPOC);
1664#else
1665        pLocalRPS->setDeltaPOC(k, pReferencePictureSet->getDeltaPOC(i));
1666#endif
1667        pLocalRPS->setUsed(k, pReferencePictureSet->getUsed(i) && (!isRAP));
1668        if (bEfficientFieldIRAPEnabled)
1669        {
1670#if SVC_POC
1671          pLocalRPS->setUsed(k, pLocalRPS->getUsed(k) && !(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + deltaPOC < pocRandomAccess) );
1672#else
1673          pLocalRPS->setUsed(k, pLocalRPS->getUsed(k) && !(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess) );
1674#endif
1675        }
1676
1677        if(pLocalRPS->getDeltaPOC(k) < 0)
1678        {
1679          nrOfNegativePictures++;
1680        }
1681        else
1682        {
1683          if(bEfficientFieldIRAPEnabled && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getAssociatedIRAPPOC() && this->getAssociatedIRAPPOC() == this->getPOC()+1)
1684          {
1685            irapIsInRPS = true;
1686          }
1687          nrOfPositivePictures++;
1688        }
1689        k++;
1690      }
1691    }
1692  }
1693
1694  Bool useNewRPS = false;
1695  // if current picture is complimentary field associated to IRAP, add the IRAP to its RPS.
1696  if(bEfficientFieldIRAPEnabled && m_pcPic->isField() && !irapIsInRPS)
1697  {
1698    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1699    while ( iterPic != rcListPic.end())
1700    {
1701      rpcPic = *(iterPic++);
1702      if(rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getAssociatedIRAPPOC() && this->getAssociatedIRAPPOC() == this->getPOC()+1)
1703      {
1704        pLocalRPS->setDeltaPOC(k, 1);
1705        pLocalRPS->setUsed(k, true);
1706        nrOfPositivePictures++;
1707        k ++;
1708        useNewRPS = true;
1709      }
1710    }
1711  }
1712  pLocalRPS->setNumberOfNegativePictures(nrOfNegativePictures);
1713  pLocalRPS->setNumberOfPositivePictures(nrOfPositivePictures);
1714  pLocalRPS->setNumberOfPictures(nrOfNegativePictures+nrOfPositivePictures);
1715  // This is a simplistic inter rps example. A smarter encoder will look for a better reference RPS to do the
1716  // inter RPS prediction with.  Here we just use the reference used by pReferencePictureSet.
1717  // If pReferencePictureSet is not inter_RPS_predicted, then inter_RPS_prediction is for the current RPS also disabled.
1718  if (!pReferencePictureSet->getInterRPSPrediction() || useNewRPS
1719#if SVC_POC
1720    || pocsAdjusted  // inter RPS prediction does not work if POCs have been adjusted
1721#endif
1722    )
1723  {
1724    pLocalRPS->setInterRPSPrediction(false);
1725    pLocalRPS->setNumRefIdc(0);
1726  }
1727  else
1728  {
1729    Int rIdx =  this->getRPSidx() - pReferencePictureSet->getDeltaRIdxMinus1() - 1;
1730    Int deltaRPS = pReferencePictureSet->getDeltaRPS();
1731    const TComReferencePictureSet* pcRefRPS = this->getSPS()->getRPSList()->getReferencePictureSet(rIdx);
1732    Int iRefPics = pcRefRPS->getNumberOfPictures();
1733    Int iNewIdc=0;
1734    for(i=0; i<= iRefPics; i++)
1735    {
1736      Int deltaPOC = ((i != iRefPics)? pcRefRPS->getDeltaPOC(i) : 0);  // check if the reference abs POC is >= 0
1737      Int iRefIdc = 0;
1738      for (j=0; j < pLocalRPS->getNumberOfPictures(); j++) // loop through the  pictures in the new RPS
1739      {
1740        if ( (deltaPOC + deltaRPS) == pLocalRPS->getDeltaPOC(j))
1741        {
1742          if (pLocalRPS->getUsed(j))
1743          {
1744            iRefIdc = 1;
1745          }
1746          else
1747          {
1748            iRefIdc = 2;
1749          }
1750        }
1751      }
1752      pLocalRPS->setRefIdc(i, iRefIdc);
1753      iNewIdc++;
1754    }
1755    pLocalRPS->setInterRPSPrediction(true);
1756    pLocalRPS->setNumRefIdc(iNewIdc);
1757    pLocalRPS->setDeltaRPS(deltaRPS);
1758    pLocalRPS->setDeltaRIdxMinus1(pReferencePictureSet->getDeltaRIdxMinus1() + this->getSPS()->getRPSList()->getNumberOfReferencePictureSets() - this->getRPSidx());
1759  }
1760
1761  this->setRPS(pLocalRPS);
1762  this->setRPSidx(-1);
1763}
1764
1765//! get AC and DC values for weighted pred
1766Void  TComSlice::getWpAcDcParam(WPACDCParam *&wp)
1767{
1768  wp = m_weightACDCParam;
1769}
1770
1771//! init AC and DC values for weighted pred
1772Void  TComSlice::initWpAcDcParam()
1773{
1774  for(Int iComp = 0; iComp < MAX_NUM_COMPONENT; iComp++ )
1775  {
1776    m_weightACDCParam[iComp].iAC = 0;
1777    m_weightACDCParam[iComp].iDC = 0;
1778  }
1779}
1780
1781//! get tables for weighted prediction
1782Void  TComSlice::getWpScaling( RefPicList e, Int iRefIdx, WPScalingParam *&wp )
1783{
1784  assert (e<NUM_REF_PIC_LIST_01);
1785  wp = m_weightPredTable[e][iRefIdx];
1786}
1787
1788//! reset Default WP tables settings : no weight.
1789Void  TComSlice::resetWpScaling()
1790{
1791  for ( Int e=0 ; e<NUM_REF_PIC_LIST_01 ; e++ )
1792  {
1793    for ( Int i=0 ; i<MAX_NUM_REF ; i++ )
1794    {
1795      for ( Int yuv=0 ; yuv<MAX_NUM_COMPONENT ; yuv++ )
1796      {
1797        WPScalingParam  *pwp = &(m_weightPredTable[e][i][yuv]);
1798        pwp->bPresentFlag      = false;
1799        pwp->uiLog2WeightDenom = 0;
1800        pwp->uiLog2WeightDenom = 0;
1801        pwp->iWeight           = 1;
1802        pwp->iOffset           = 0;
1803      }
1804    }
1805  }
1806}
1807
1808//! init WP table
1809Void  TComSlice::initWpScaling(const TComSPS *sps)
1810{
1811  const Bool bUseHighPrecisionPredictionWeighting = sps->getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag();
1812  for ( Int e=0 ; e<NUM_REF_PIC_LIST_01 ; e++ )
1813  {
1814    for ( Int i=0 ; i<MAX_NUM_REF ; i++ )
1815    {
1816      for ( Int yuv=0 ; yuv<MAX_NUM_COMPONENT ; yuv++ )
1817      {
1818        WPScalingParam  *pwp = &(m_weightPredTable[e][i][yuv]);
1819        if ( !pwp->bPresentFlag )
1820        {
1821          // Inferring values not present :
1822          pwp->iWeight = (1 << pwp->uiLog2WeightDenom);
1823          pwp->iOffset = 0;
1824        }
1825
1826        const Int offsetScalingFactor = bUseHighPrecisionPredictionWeighting ? 1 : (1 << (sps->getBitDepth(toChannelType(ComponentID(yuv)))-8));
1827
1828        pwp->w      = pwp->iWeight;
1829        pwp->o      = pwp->iOffset * offsetScalingFactor; //NOTE: This value of the ".o" variable is never used - .o is set immediately before it gets used
1830        pwp->shift  = pwp->uiLog2WeightDenom;
1831        pwp->round  = (pwp->uiLog2WeightDenom>=1) ? (1 << (pwp->uiLog2WeightDenom-1)) : (0);
1832      }
1833    }
1834  }
1835}
1836
1837// ------------------------------------------------------------------------------------------------
1838// Video parameter set (VPS)
1839// ------------------------------------------------------------------------------------------------
1840#if SVC_EXTENSION
1841TComVPS::TComVPS()
1842: m_VPSId                     (  0)
1843, m_uiMaxTLayers              (  1)
1844, m_uiMaxLayers               (  1)
1845, m_bTemporalIdNestingFlag    (false)
1846, m_numHrdParameters          (  0)
1847, m_hrdParameters             ()
1848, m_hrdOpSetIdx               ()
1849, m_cprmsPresentFlag          ()
1850, m_baseLayerInternalFlag     (true)
1851, m_baseLayerAvailableFlag    (true)
1852, m_maxLayerId                (0)
1853, m_numLayerSets              (0)
1854, m_numOutputLayerSets        (0) 
1855, m_numProfileTierLevel       (0)
1856, m_numAddOutputLayerSets     (0)
1857, m_defaultTargetOutputLayerIdc(0)
1858, m_bitRatePresentVpsFlag     (false)
1859, m_picRatePresentVpsFlag     (false)
1860, m_repFormatIdxPresentFlag   (false)
1861, m_vpsNumRepFormats          (1)
1862, m_viewIdLen                (0)
1863, m_vpsNonVuiExtLength (0)
1864, m_vpsPocLsbAlignedFlag(false)
1865{
1866  for( Int i = 0; i < MAX_TLAYER; i++)
1867  {
1868    m_numReorderPics[i] = 0;
1869    m_uiMaxDecPicBuffering[i] = 1;
1870    m_uiMaxLatencyIncrease[i] = 0;
1871  }
1872
1873  m_nonHEVCBaseLayerFlag = false;
1874  m_splittingFlag = false;
1875  m_nuhLayerIdPresentFlag = false;
1876  ::memset(m_scalabilityMask, 0, sizeof(m_scalabilityMask));
1877  ::memset(m_dimensionIdLen, 0, sizeof(m_dimensionIdLen));
1878  ::memset(m_layerIdInNuh, 0, sizeof(m_layerIdInNuh));
1879  ::memset(m_dimensionId, 0, sizeof(m_dimensionId));
1880
1881  m_numScalabilityTypes = 0;
1882  ::memset(m_layerIdxInVps, 0, sizeof(m_layerIdxInVps));
1883  ::memset(m_profilePresentFlag, 0, sizeof(m_profilePresentFlag));
1884
1885  ::memset(m_layerIdIncludedFlag, 0, sizeof(m_layerIdIncludedFlag));
1886  // Consider dynamic allocation for outputLayerSetIdx and outputLayerFlag
1887  ::memset(m_outputLayerSetIdx, 0, sizeof(m_outputLayerSetIdx));
1888  ::memset(m_outputLayerFlag, 0, sizeof(m_outputLayerFlag));
1889
1890  ::memset(m_directDependencyFlag, 0, sizeof(m_directDependencyFlag));
1891  ::memset(m_numDirectRefLayers,   0, sizeof(m_numDirectRefLayers  ));
1892  ::memset(m_refLayerId,           0, sizeof(m_refLayerId          ));
1893  m_directDepTypeLen = 2;
1894  ::memset(m_directDependencyType, 0, sizeof(m_directDependencyType));
1895
1896  m_maxOneActiveRefLayerFlag = true;
1897  ::memset(m_pocLsbNotPresentFlag, 0, sizeof(m_pocLsbNotPresentFlag));
1898  m_crossLayerPictureTypeAlignFlag = true;
1899  m_crossLayerIrapAlignFlag = true;
1900  m_crossLayerAlignedIdrOnlyFlag = false;
1901  m_maxTidRefPresentFlag = true;
1902  for( Int i = 0; i < MAX_VPS_LAYER_IDX_PLUS1 - 1; i++)
1903  {
1904    for( Int j = 0; j < MAX_VPS_LAYER_IDX_PLUS1; j++)
1905    {
1906      m_maxTidIlRefPicsPlus1[i][j] = m_uiMaxTLayers + 1;
1907    }
1908  }
1909
1910  m_tilesNotInUseFlag = true;
1911  m_wppNotInUseFlag = true;
1912  ::memset(m_tilesInUseFlag,  0, sizeof(m_tilesInUseFlag));
1913  ::memset(m_loopFilterNotAcrossTilesFlag,  0, sizeof(m_loopFilterNotAcrossTilesFlag));
1914  ::memset(m_tileBoundariesAlignedFlag,  0, sizeof(m_tileBoundariesAlignedFlag));
1915  ::memset(m_wppInUseFlag,  0, sizeof(m_wppInUseFlag));
1916
1917  m_ilpRestrictedRefLayersFlag = false;
1918  ::memset(m_minSpatialSegmentOffsetPlus1,  0, sizeof(m_minSpatialSegmentOffsetPlus1));
1919  ::memset(m_ctuBasedOffsetEnabledFlag,     0, sizeof(m_ctuBasedOffsetEnabledFlag));
1920  ::memset(m_minHorizontalCtuOffsetPlus1,   0, sizeof(m_minHorizontalCtuOffsetPlus1));
1921
1922  m_vidSigPresentVpsFlag=true;
1923  m_vpsVidSigInfo=1;
1924  ::memset( m_vpsVidSigIdx, 0, sizeof(m_vpsVidSigIdx) );
1925  m_vpsVidSigIdx[0]=0;
1926  for (Int i=0; i < 16; i++)
1927  {
1928    m_vpsVidFormat[i] = 5;
1929    m_vpsFullRangeFlag[i] = false;
1930    m_vpsColorPrimaries[i] = 2;
1931    m_vpsTransChar[i] = 2;
1932    m_vpsMatCoeff[i] = 2;
1933  }
1934
1935  ::memset( m_bitRatePresentFlag, 0, sizeof(m_bitRatePresentFlag) );
1936  ::memset( m_picRatePresentFlag, 0, sizeof(m_picRatePresentFlag) );
1937  ::memset( m_avgBitRate        , 0, sizeof(m_avgBitRate)         );
1938  ::memset( m_maxBitRate        , 0, sizeof(m_maxBitRate)         );
1939  ::memset( m_constPicRateIdc   , 0, sizeof(m_constPicRateIdc)    );
1940  ::memset( m_avgPicRate        , 0, sizeof(m_avgPicRate)         );
1941  ::memset( m_vpsRepFormatIdx   , 0, sizeof(m_vpsRepFormatIdx)    );
1942  ::memset( m_viewIdVal         , 0, sizeof(m_viewIdVal))         ;
1943
1944  for( Int i = 0; i < MAX_NUM_LAYER_IDS; i++ )
1945  {
1946    m_numberRefLayers[i] = 0;
1947    for( Int j = 0; j < MAX_NUM_LAYER_IDS; j++ )
1948    {
1949      m_recursiveRefLayerFlag[i][j] = 0;
1950    }
1951  }
1952
1953  ::memset( m_subLayerFlagInfoPresentFlag,  0, sizeof(m_subLayerFlagInfoPresentFlag ) );
1954  ::memset( m_subLayerDpbInfoPresentFlag,   0, sizeof(m_subLayerDpbInfoPresentFlag )  );
1955  ::memset( m_maxVpsDecPicBufferingMinus1,  0, sizeof(m_maxVpsDecPicBufferingMinus1 ) );
1956  ::memset( m_maxVpsNumReorderPics,         0, sizeof(m_maxVpsNumReorderPics )        );
1957  ::memset( m_maxVpsLatencyIncreasePlus1,   0, sizeof(m_maxVpsLatencyIncreasePlus1 )  );
1958  ::memset( m_numSubDpbs                ,   0, sizeof(m_numSubDpbs)                   );
1959  ::memset( m_baseLayerPSCompatibilityFlag, 0, sizeof(m_baseLayerPSCompatibilityFlag) );
1960}
1961#else
1962TComVPS::TComVPS()
1963: m_VPSId                     (  0)
1964, m_uiMaxTLayers              (  1)
1965, m_uiMaxLayers               (  1)
1966, m_bTemporalIdNestingFlag    (false)
1967, m_numHrdParameters          (  0)
1968, m_maxNuhReservedZeroLayerId (  0)
1969, m_hrdParameters             ()
1970, m_hrdOpSetIdx               ()
1971, m_cprmsPresentFlag          ()
1972{
1973
1974  for( Int i = 0; i < MAX_TLAYER; i++)
1975  {
1976    m_numReorderPics[i] = 0;
1977    m_uiMaxDecPicBuffering[i] = 1;
1978    m_uiMaxLatencyIncrease[i] = 0;
1979  }
1980}
1981#endif //SVC_EXTENSION
1982
1983TComVPS::~TComVPS()
1984{
1985}
1986
1987// ------------------------------------------------------------------------------------------------
1988// Sequence parameter set (SPS)
1989// ------------------------------------------------------------------------------------------------
1990
1991TComSPSRExt::TComSPSRExt()
1992 : m_transformSkipRotationEnabledFlag   (false)
1993 , m_transformSkipContextEnabledFlag    (false)
1994// m_rdpcmEnabledFlag initialized below
1995 , m_extendedPrecisionProcessingFlag    (false)
1996 , m_intraSmoothingDisabledFlag         (false)
1997 , m_highPrecisionOffsetsEnabledFlag    (false)
1998 , m_persistentRiceAdaptationEnabledFlag(false)
1999 , m_cabacBypassAlignmentEnabledFlag    (false)
2000{
2001  for (UInt signallingModeIndex = 0; signallingModeIndex < NUMBER_OF_RDPCM_SIGNALLING_MODES; signallingModeIndex++)
2002  {
2003    m_rdpcmEnabledFlag[signallingModeIndex] = false;
2004  }
2005}
2006
2007TComSPS::TComSPS()
2008: m_SPSId                     (  0)
2009, m_VPSId                     (  0)
2010, m_chromaFormatIdc           (CHROMA_420)
2011, m_uiMaxTLayers              (  1)
2012// Structure
2013, m_picWidthInLumaSamples     (352)
2014, m_picHeightInLumaSamples    (288)
2015, m_log2MinCodingBlockSize    (  0)
2016, m_log2DiffMaxMinCodingBlockSize(0)
2017, m_uiMaxCUWidth              ( 32)
2018, m_uiMaxCUHeight             ( 32)
2019, m_uiMaxTotalCUDepth         (  3)
2020, m_bLongTermRefsPresent      (false)
2021, m_uiQuadtreeTULog2MaxSize   (  0)
2022, m_uiQuadtreeTULog2MinSize   (  0)
2023, m_uiQuadtreeTUMaxDepthInter (  0)
2024, m_uiQuadtreeTUMaxDepthIntra (  0)
2025// Tool list
2026, m_usePCM                    (false)
2027, m_pcmLog2MaxSize            (  5)
2028, m_uiPCMLog2MinSize          (  7)
2029, m_bPCMFilterDisableFlag     (false)
2030, m_uiBitsForPOC              (  8)
2031, m_numLongTermRefPicSPS      (  0)
2032, m_uiMaxTrSize               ( 32)
2033, m_bUseSAO                   (false)
2034, m_bTemporalIdNestingFlag    (false)
2035, m_scalingListEnabledFlag    (false)
2036, m_useStrongIntraSmoothing   (false)
2037, m_vuiParametersPresentFlag  (false)
2038, m_vuiParameters             ()
2039#if SVC_EXTENSION
2040, m_layerId                   ( 0 )
2041, m_extensionFlag             ( false )
2042, m_bV1CompatibleSPSFlag      (  0)
2043, m_updateRepFormatFlag       (false)
2044, m_updateRepFormatIndex      (0)
2045, m_inferScalingListFlag      ( false )
2046, m_scalingListRefLayerId     ( 0 )
2047#endif //SVC_EXTENSION
2048{
2049  for(Int ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
2050  {
2051    m_bitDepths.recon[ch] = 8;
2052#if O0043_BEST_EFFORT_DECODING
2053    m_bitDepths.stream[ch] = 8;
2054#endif
2055    m_pcmBitDepths[ch] = 8;
2056    m_qpBDOffset   [ch] = 0;
2057  }
2058
2059  for ( Int i = 0; i < MAX_TLAYER; i++ )
2060  {
2061    m_uiMaxLatencyIncreasePlus1[i] = 0;
2062    m_uiMaxDecPicBuffering[i] = 1;
2063    m_numReorderPics[i]       = 0;
2064  }
2065
2066  ::memset(m_ltRefPicPocLsbSps, 0, sizeof(m_ltRefPicPocLsbSps));
2067  ::memset(m_usedByCurrPicLtSPSFlag, 0, sizeof(m_usedByCurrPicLtSPSFlag));
2068}
2069
2070TComSPS::~TComSPS()
2071{
2072  m_RPSList.destroy();
2073}
2074
2075Void  TComSPS::createRPSList( Int numRPS )
2076{
2077  m_RPSList.destroy();
2078  m_RPSList.create(numRPS);
2079}
2080
2081
2082const Int TComSPS::m_winUnitX[]={1,2,2,1};
2083const Int TComSPS::m_winUnitY[]={1,2,1,1};
2084
2085TComPPSRExt::TComPPSRExt()
2086: m_log2MaxTransformSkipBlockSize      (2)
2087, m_crossComponentPredictionEnabledFlag(false)
2088, m_diffCuChromaQpOffsetDepth          (0)
2089, m_chromaQpOffsetListLen              (0)
2090// m_ChromaQpAdjTableIncludingNullEntry initialized below
2091// m_log2SaoOffsetScale initialized below
2092{
2093  m_ChromaQpAdjTableIncludingNullEntry[0].u.comp.CbOffset = 0; // Array includes entry [0] for the null offset used when cu_chroma_qp_offset_flag=0. This is initialised here and never subsequently changed.
2094  m_ChromaQpAdjTableIncludingNullEntry[0].u.comp.CrOffset = 0;
2095  for(Int ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
2096  {
2097    m_log2SaoOffsetScale[ch] = 0;
2098  }
2099}
2100
2101TComPPS::TComPPS()
2102: m_PPSId                            (0)
2103, m_SPSId                            (0)
2104, m_picInitQPMinus26                 (0)
2105, m_useDQP                           (false)
2106, m_bConstrainedIntraPred            (false)
2107, m_bSliceChromaQpFlag               (false)
2108, m_uiMaxCuDQPDepth                  (0)
2109, m_chromaCbQpOffset                 (0)
2110, m_chromaCrQpOffset                 (0)
2111, m_numRefIdxL0DefaultActive         (1)
2112, m_numRefIdxL1DefaultActive         (1)
2113, m_TransquantBypassEnableFlag       (false)
2114, m_useTransformSkip                 (false)
2115, m_dependentSliceSegmentsEnabledFlag(false)
2116, m_tilesEnabledFlag                 (false)
2117, m_entropyCodingSyncEnabledFlag     (false)
2118, m_loopFilterAcrossTilesEnabledFlag (true)
2119, m_uniformSpacingFlag               (false)
2120, m_numTileColumnsMinus1             (0)
2121, m_numTileRowsMinus1                (0)
2122, m_signHideFlag                     (false)
2123, m_cabacInitPresentFlag             (false)
2124, m_sliceHeaderExtensionPresentFlag  (false)
2125, m_loopFilterAcrossSlicesEnabledFlag(false)
2126, m_listsModificationPresentFlag     (0)
2127, m_numExtraSliceHeaderBits          (0)
2128
2129#if SVC_EXTENSION
2130, m_extensionFlag(false)
2131, m_layerId(0)
2132, m_inferScalingListFlag ( false )
2133, m_scalingListRefLayerId ( 0 )
2134, m_pocResetInfoPresentFlag   (false)
2135, m_numRefLayerLocationOffsets  ( 0 )
2136#if CGS_3D_ASYMLUT
2137, m_nCGSFlag(0)
2138, m_nCGSOutputBitDepthY(0)
2139, m_nCGSOutputBitDepthC(0)
2140#endif
2141#endif //SVC_EXTENSION
2142{
2143#if SVC_EXTENSION
2144  ::memset(m_scaledRefLayerOffsetPresentFlag,   0, sizeof(m_scaledRefLayerOffsetPresentFlag));
2145  ::memset(m_refRegionOffsetPresentFlag,   0, sizeof(m_refRegionOffsetPresentFlag));
2146#endif //SVC_EXTENSION
2147}
2148
2149TComPPS::~TComPPS()
2150{
2151}
2152
2153TComReferencePictureSet::TComReferencePictureSet()
2154: m_numberOfPictures (0)
2155, m_numberOfNegativePictures (0)
2156, m_numberOfPositivePictures (0)
2157, m_numberOfLongtermPictures (0)
2158, m_interRPSPrediction (0)
2159, m_deltaRIdxMinus1 (0)
2160, m_deltaRPS (0)
2161, m_numRefIdc (0)
2162{
2163  ::memset( m_deltaPOC, 0, sizeof(m_deltaPOC) );
2164  ::memset( m_POC, 0, sizeof(m_POC) );
2165  ::memset( m_used, 0, sizeof(m_used) );
2166  ::memset( m_refIdc, 0, sizeof(m_refIdc) );
2167  ::memset( m_bCheckLTMSB, 0, sizeof(m_bCheckLTMSB) );
2168  ::memset( m_pocLSBLT, 0, sizeof(m_pocLSBLT) );
2169  ::memset( m_deltaPOCMSBCycleLT, 0, sizeof(m_deltaPOCMSBCycleLT) );
2170  ::memset( m_deltaPocMSBPresentFlag, 0, sizeof(m_deltaPocMSBPresentFlag) );
2171}
2172
2173TComReferencePictureSet::~TComReferencePictureSet()
2174{
2175}
2176
2177Void TComReferencePictureSet::setUsed(Int bufferNum, Bool used)
2178{
2179  m_used[bufferNum] = used;
2180}
2181
2182Void TComReferencePictureSet::setDeltaPOC(Int bufferNum, Int deltaPOC)
2183{
2184  m_deltaPOC[bufferNum] = deltaPOC;
2185}
2186
2187Void TComReferencePictureSet::setNumberOfPictures(Int numberOfPictures)
2188{
2189  m_numberOfPictures = numberOfPictures;
2190}
2191
2192Int TComReferencePictureSet::getUsed(Int bufferNum) const
2193{
2194  return m_used[bufferNum];
2195}
2196
2197Int TComReferencePictureSet::getDeltaPOC(Int bufferNum) const
2198{
2199  return m_deltaPOC[bufferNum];
2200}
2201
2202Int TComReferencePictureSet::getNumberOfPictures() const
2203{
2204  return m_numberOfPictures;
2205}
2206
2207Int TComReferencePictureSet::getPOC(Int bufferNum) const
2208{
2209  return m_POC[bufferNum];
2210}
2211
2212Void TComReferencePictureSet::setPOC(Int bufferNum, Int POC)
2213{
2214  m_POC[bufferNum] = POC;
2215}
2216
2217Bool TComReferencePictureSet::getCheckLTMSBPresent(Int bufferNum) const
2218{
2219  return m_bCheckLTMSB[bufferNum];
2220}
2221
2222Void TComReferencePictureSet::setCheckLTMSBPresent(Int bufferNum, Bool b)
2223{
2224  m_bCheckLTMSB[bufferNum] = b;
2225}
2226
2227//! set the reference idc value at uiBufferNum entry to the value of iRefIdc
2228Void TComReferencePictureSet::setRefIdc(Int bufferNum, Int refIdc)
2229{
2230  m_refIdc[bufferNum] = refIdc;
2231}
2232
2233//! get the reference idc value at uiBufferNum
2234Int  TComReferencePictureSet::getRefIdc(Int bufferNum) const
2235{
2236  return m_refIdc[bufferNum];
2237}
2238
2239/** Sorts the deltaPOC and Used by current values in the RPS based on the deltaPOC values.
2240 *  deltaPOC values are sorted with -ve values before the +ve values.  -ve values are in decreasing order.
2241 *  +ve values are in increasing order.
2242 * \returns Void
2243 */
2244Void TComReferencePictureSet::sortDeltaPOC()
2245{
2246  // sort in increasing order (smallest first)
2247  for(Int j=1; j < getNumberOfPictures(); j++)
2248  {
2249    Int deltaPOC = getDeltaPOC(j);
2250    Bool used = getUsed(j);
2251    for (Int k=j-1; k >= 0; k--)
2252    {
2253      Int temp = getDeltaPOC(k);
2254      if (deltaPOC < temp)
2255      {
2256        setDeltaPOC(k+1, temp);
2257        setUsed(k+1, getUsed(k));
2258        setDeltaPOC(k, deltaPOC);
2259        setUsed(k, used);
2260      }
2261    }
2262  }
2263  // flip the negative values to largest first
2264  Int numNegPics = getNumberOfNegativePictures();
2265  for(Int j=0, k=numNegPics-1; j < numNegPics>>1; j++, k--)
2266  {
2267    Int deltaPOC = getDeltaPOC(j);
2268    Bool used = getUsed(j);
2269    setDeltaPOC(j, getDeltaPOC(k));
2270    setUsed(j, getUsed(k));
2271    setDeltaPOC(k, deltaPOC);
2272    setUsed(k, used);
2273  }
2274}
2275
2276/** Prints the deltaPOC and RefIdc (if available) values in the RPS.
2277 *  A "*" is added to the deltaPOC value if it is Used bu current.
2278 * \returns Void
2279 */
2280Void TComReferencePictureSet::printDeltaPOC() const
2281{
2282  printf("DeltaPOC = { ");
2283  for(Int j=0; j < getNumberOfPictures(); j++)
2284  {
2285    printf("%d%s ", getDeltaPOC(j), (getUsed(j)==1)?"*":"");
2286  }
2287  if (getInterRPSPrediction())
2288  {
2289    printf("}, RefIdc = { ");
2290    for(Int j=0; j < getNumRefIdc(); j++)
2291    {
2292      printf("%d ", getRefIdc(j));
2293    }
2294  }
2295  printf("}\n");
2296}
2297
2298TComRefPicListModification::TComRefPicListModification()
2299: m_refPicListModificationFlagL0 (false)
2300, m_refPicListModificationFlagL1 (false)
2301{
2302  ::memset( m_RefPicSetIdxL0, 0, sizeof(m_RefPicSetIdxL0) );
2303  ::memset( m_RefPicSetIdxL1, 0, sizeof(m_RefPicSetIdxL1) );
2304}
2305
2306TComRefPicListModification::~TComRefPicListModification()
2307{
2308}
2309
2310TComScalingList::TComScalingList()
2311{
2312  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
2313  {
2314    for(UInt listId = 0; listId < SCALING_LIST_NUM; listId++)
2315    {
2316      m_scalingListCoef[sizeId][listId].resize(min<Int>(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
2317    }
2318  }
2319}
2320
2321/** set default quantization matrix to array
2322*/
2323Void TComScalingList::setDefaultScalingList()
2324{
2325  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
2326  {
2327    for(UInt listId=0;listId<SCALING_LIST_NUM;listId++)
2328    {
2329      processDefaultMatrix(sizeId, listId);
2330    }
2331  }
2332}
2333/** check if use default quantization matrix
2334 * \returns true if use default quantization matrix in all size
2335*/
2336Bool TComScalingList::checkDefaultScalingList()
2337{
2338  UInt defaultCounter=0;
2339
2340  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
2341  {
2342    for(UInt listId=0;listId<SCALING_LIST_NUM;listId++)
2343    {
2344      if( !memcmp(getScalingListAddress(sizeId,listId), getScalingListDefaultAddress(sizeId, listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
2345     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == 16))) // check DC value
2346      {
2347        defaultCounter++;
2348      }
2349    }
2350  }
2351
2352  return (defaultCounter == (SCALING_LIST_NUM * SCALING_LIST_SIZE_NUM )) ? false : true;
2353}
2354
2355/** get scaling matrix from RefMatrixID
2356 * \param sizeId    size index
2357 * \param listId    index of input matrix
2358 * \param refListId index of reference matrix
2359 */
2360Void TComScalingList::processRefMatrix( UInt sizeId, UInt listId , UInt refListId )
2361{
2362  ::memcpy(getScalingListAddress(sizeId, listId),((listId == refListId)? getScalingListDefaultAddress(sizeId, refListId): getScalingListAddress(sizeId, refListId)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
2363}
2364
2365Void TComScalingList::checkPredMode(UInt sizeId, UInt listId)
2366{
2367  Int predListStep = (sizeId == SCALING_LIST_32x32? (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) : 1); // if 32x32, skip over chroma entries.
2368
2369  for(Int predListIdx = (Int)listId ; predListIdx >= 0; predListIdx-=predListStep)
2370  {
2371    if( !memcmp(getScalingListAddress(sizeId,listId),((listId == predListIdx) ?
2372      getScalingListDefaultAddress(sizeId, predListIdx): getScalingListAddress(sizeId, predListIdx)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
2373     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == getScalingListDC(sizeId,predListIdx)))) // check DC value
2374    {
2375      setRefMatrixId(sizeId, listId, predListIdx);
2376      setScalingListPredModeFlag(sizeId, listId, false);
2377      return;
2378    }
2379  }
2380  setScalingListPredModeFlag(sizeId, listId, true);
2381}
2382
2383static Void outputScalingListHelp(std::ostream &os)
2384{
2385  os << "The scaling list file specifies all matrices and their DC values; none can be missing,\n"
2386         "but their order is arbitrary.\n\n"
2387         "The matrices are specified by:\n"
2388         "<matrix name><unchecked data>\n"
2389         "  <value>,<value>,<value>,....\n\n"
2390         "  Line-feeds can be added arbitrarily between values, and the number of values needs to be\n"
2391         "  at least the number of entries for the matrix (superfluous entries are ignored).\n"
2392         "  The <unchecked data> is text on the same line as the matrix that is not checked\n"
2393         "  except to ensure that the matrix name token is unique. It is recommended that it is ' ='\n"
2394         "  The values in the matrices are the absolute values (0-255), not the delta values as\n"
2395         "  exchanged between the encoder and decoder\n\n"
2396         "The DC values (for matrix sizes larger than 8x8) are specified by:\n"
2397         "<matrix name>_DC<unchecked data>\n"
2398         "  <value>\n";
2399
2400  os << "The permitted matrix names are:\n";
2401  for(UInt sizeIdc = 0; sizeIdc < SCALING_LIST_SIZE_NUM; sizeIdc++)
2402  {
2403    for(UInt listIdc = 0; listIdc < SCALING_LIST_NUM; listIdc++)
2404    {
2405      if ((sizeIdc!=SCALING_LIST_32x32) || (listIdc%(SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) == 0))
2406      {
2407        os << "  " << MatrixType[sizeIdc][listIdc] << '\n';
2408      }
2409    }
2410  }
2411}
2412
2413Void TComScalingList::outputScalingLists(std::ostream &os) const
2414{
2415  for(UInt sizeIdc = 0; sizeIdc < SCALING_LIST_SIZE_NUM; sizeIdc++)
2416  {
2417    const UInt size = min(8,4<<(sizeIdc));
2418    for(UInt listIdc = 0; listIdc < SCALING_LIST_NUM; listIdc++)
2419    {
2420      if ((sizeIdc!=SCALING_LIST_32x32) || (listIdc%(SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) == 0))
2421      {
2422        const Int *src = getScalingListAddress(sizeIdc, listIdc);
2423        os << (MatrixType[sizeIdc][listIdc]) << " =\n  ";
2424        for(UInt y=0; y<size; y++)
2425        {
2426          for(UInt x=0; x<size; x++, src++)
2427          {
2428            os << std::setw(3) << (*src) << ", ";
2429          }
2430          os << (y+1<size?"\n  ":"\n");
2431        }
2432        if(sizeIdc > SCALING_LIST_8x8)
2433        {
2434          os << MatrixType_DC[sizeIdc][listIdc] << " = \n  " << std::setw(3) << getScalingListDC(sizeIdc, listIdc) << "\n";
2435        }
2436        os << "\n";
2437      }
2438    }
2439  }
2440}
2441
2442Bool TComScalingList::xParseScalingList(const std::string &fileName)
2443{
2444  static const Int LINE_SIZE=1024;
2445  FILE *fp = NULL;
2446  TChar line[LINE_SIZE];
2447
2448  if (fileName.empty())
2449  {
2450    fprintf(stderr, "Error: no scaling list file specified. Help on scaling lists being output\n");
2451    outputScalingListHelp(std::cout);
2452    std::cout << "\n\nExample scaling list file using default values:\n\n";
2453    outputScalingLists(std::cout);
2454    exit (1);
2455    return true;
2456  }
2457  else if ((fp = fopen(fileName.c_str(),"r")) == (FILE*)NULL)
2458  {
2459    fprintf(stderr, "Error: cannot open scaling list file %s for reading\n", fileName.c_str());
2460    return true;
2461  }
2462
2463  for(UInt sizeIdc = 0; sizeIdc < SCALING_LIST_SIZE_NUM; sizeIdc++)
2464  {
2465    const UInt size = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeIdc]);
2466
2467    for(UInt listIdc = 0; listIdc < SCALING_LIST_NUM; listIdc++)
2468    {
2469      Int * const src = getScalingListAddress(sizeIdc, listIdc);
2470
2471      if ((sizeIdc==SCALING_LIST_32x32) && (listIdc%(SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) != 0)) // derive chroma32x32 from chroma16x16
2472      {
2473        const Int *srcNextSmallerSize = getScalingListAddress(sizeIdc-1, listIdc);
2474        for(UInt i=0; i<size; i++)
2475        {
2476          src[i] = srcNextSmallerSize[i];
2477        }
2478        setScalingListDC(sizeIdc,listIdc,(sizeIdc > SCALING_LIST_8x8) ? getScalingListDC(sizeIdc-1, listIdc) : src[0]);
2479      }
2480      else
2481      {
2482        {
2483          fseek(fp, 0, SEEK_SET);
2484          Bool bFound=false;
2485          while ((!feof(fp)) && (!bFound))
2486          {
2487            TChar *ret = fgets(line, LINE_SIZE, fp);
2488            TChar *findNamePosition= ret==NULL ? NULL : strstr(line, MatrixType[sizeIdc][listIdc]);
2489            // This could be a match against the DC string as well, so verify it isn't
2490            if (findNamePosition!= NULL && (MatrixType_DC[sizeIdc][listIdc]==NULL || strstr(line, MatrixType_DC[sizeIdc][listIdc])==NULL))
2491            {
2492              bFound=true;
2493            }
2494          }
2495          if (!bFound)
2496          {
2497            fprintf(stderr, "Error: cannot find Matrix %s from scaling list file %s\n", MatrixType[sizeIdc][listIdc], fileName.c_str());
2498            return true;
2499          }
2500        }
2501        for (UInt i=0; i<size; i++)
2502        {
2503          Int data;
2504          if (fscanf(fp, "%d,", &data)!=1)
2505          {
2506            fprintf(stderr, "Error: cannot read value #%d for Matrix %s from scaling list file %s at file position %ld\n", i, MatrixType[sizeIdc][listIdc], fileName.c_str(), ftell(fp));
2507            return true;
2508          }
2509          if (data<0 || data>255)
2510          {
2511            fprintf(stderr, "Error: QMatrix entry #%d of value %d for Matrix %s from scaling list file %s at file position %ld is out of range (0 to 255)\n", i, data, MatrixType[sizeIdc][listIdc], fileName.c_str(), ftell(fp));
2512            return true;
2513          }
2514          src[i] = data;
2515        }
2516
2517        //set DC value for default matrix check
2518        setScalingListDC(sizeIdc,listIdc,src[0]);
2519
2520        if(sizeIdc > SCALING_LIST_8x8)
2521        {
2522          {
2523            fseek(fp, 0, SEEK_SET);
2524            Bool bFound=false;
2525            while ((!feof(fp)) && (!bFound))
2526            {
2527              TChar *ret = fgets(line, LINE_SIZE, fp);
2528              TChar *findNamePosition= ret==NULL ? NULL : strstr(line, MatrixType_DC[sizeIdc][listIdc]);
2529              if (findNamePosition!= NULL)
2530              {
2531                // This won't be a match against the non-DC string.
2532                bFound=true;
2533              }
2534            }
2535            if (!bFound)
2536            {
2537              fprintf(stderr, "Error: cannot find DC Matrix %s from scaling list file %s\n", MatrixType_DC[sizeIdc][listIdc], fileName.c_str());
2538              return true;
2539            }
2540          }
2541          Int data;
2542          if (fscanf(fp, "%d,", &data)!=1)
2543          {
2544            fprintf(stderr, "Error: cannot read DC %s from scaling list file %s at file position %ld\n", MatrixType_DC[sizeIdc][listIdc], fileName.c_str(), ftell(fp));
2545            return true;
2546          }
2547          if (data<0 || data>255)
2548          {
2549            fprintf(stderr, "Error: DC value %d for Matrix %s from scaling list file %s at file position %ld is out of range (0 to 255)\n", data, MatrixType[sizeIdc][listIdc], fileName.c_str(), ftell(fp));
2550            return true;
2551          }
2552          //overwrite DC value when size of matrix is larger than 16x16
2553          setScalingListDC(sizeIdc,listIdc,data);
2554        }
2555      }
2556    }
2557  }
2558//  std::cout << "\n\nRead scaling lists of:\n\n";
2559//  outputScalingLists(std::cout);
2560
2561  fclose(fp);
2562  return false;
2563}
2564
2565
2566/** get default address of quantization matrix
2567 * \param sizeId size index
2568 * \param listId list index
2569 * \returns pointer of quantization matrix
2570 */
2571const Int* TComScalingList::getScalingListDefaultAddress(UInt sizeId, UInt listId)
2572{
2573  const Int *src = 0;
2574  switch(sizeId)
2575  {
2576    case SCALING_LIST_4x4:
2577      src = g_quantTSDefault4x4;
2578      break;
2579    case SCALING_LIST_8x8:
2580    case SCALING_LIST_16x16:
2581    case SCALING_LIST_32x32:
2582      src = (listId < (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) ) ? g_quantIntraDefault8x8 : g_quantInterDefault8x8;
2583      break;
2584    default:
2585      assert(0);
2586      src = NULL;
2587      break;
2588  }
2589  return src;
2590}
2591
2592/** process of default matrix
2593 * \param sizeId size index
2594 * \param listId index of input matrix
2595 */
2596Void TComScalingList::processDefaultMatrix(UInt sizeId, UInt listId)
2597{
2598  ::memcpy(getScalingListAddress(sizeId, listId),getScalingListDefaultAddress(sizeId,listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
2599  setScalingListDC(sizeId,listId,SCALING_LIST_DC);
2600}
2601
2602/** check DC value of matrix for default matrix signaling
2603 */
2604Void TComScalingList::checkDcOfMatrix()
2605{
2606  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
2607  {
2608    for(UInt listId = 0; listId < SCALING_LIST_NUM; listId++)
2609    {
2610      //check default matrix?
2611      if(getScalingListDC(sizeId,listId) == 0)
2612      {
2613        processDefaultMatrix(sizeId, listId);
2614      }
2615    }
2616  }
2617}
2618
2619ParameterSetManager::ParameterSetManager()
2620#if SVC_EXTENSION
2621: m_activePPSId(-1)
2622#else
2623: m_vpsMap(MAX_NUM_VPS)
2624, m_spsMap(MAX_NUM_SPS)
2625, m_ppsMap(MAX_NUM_PPS)
2626, m_activeVPSId(-1)
2627#endif
2628, m_activeSPSId(-1)
2629{
2630}
2631
2632
2633ParameterSetManager::~ParameterSetManager()
2634{
2635}
2636
2637//! activate a SPS from a active parameter sets SEI message
2638//! \returns true, if activation is successful
2639//Bool ParameterSetManager::activateSPSWithSEI(Int spsId)
2640//{
2641//  TComSPS *sps = m_spsMap.getPS(spsId);
2642//  if (sps)
2643//  {
2644//    Int vpsId = sps->getVPSId();
2645//    TComVPS *vps = m_vpsMap.getPS(vpsId);
2646//    if (vps)
2647//    {
2648//      m_activeVPS = *(vps);
2649//      m_activeSPS = *(sps);
2650//      return true;
2651//    }
2652//    else
2653//    {
2654//      printf("Warning: tried to activate SPS using an Active parameter sets SEI message. Referenced VPS does not exist.");
2655//    }
2656//  }
2657//  else
2658//  {
2659//    printf("Warning: tried to activate non-existing SPS using an Active parameter sets SEI message.");
2660//  }
2661//  return false;
2662//}
2663
2664//! activate a PPS and depending on isIDR parameter also SPS and VPS
2665//! \returns true, if activation is successful
2666Bool ParameterSetManager::activatePPS(Int ppsId, Bool isIRAP)
2667{
2668  TComPPS *pps = m_ppsMap.getPS(ppsId);
2669  if (pps)
2670  {
2671#if SVC_EXTENSION
2672    m_activePPSId = ppsId;
2673#endif
2674    Int spsId = pps->getSPSId();
2675    if (!isIRAP && (spsId != m_activeSPSId ))
2676    {
2677      printf("Warning: tried to activate PPS referring to a inactive SPS at non-IDR.");
2678    }
2679    else
2680    {
2681      TComSPS *sps = m_spsMap.getPS(spsId);
2682      if (sps)
2683      {
2684        Int vpsId = sps->getVPSId();
2685        if (!isIRAP && (vpsId != m_activeVPSId ))
2686        {
2687          printf("Warning: tried to activate PPS referring to a inactive VPS at non-IDR.");
2688        }
2689        else
2690        {
2691          TComVPS *vps =m_vpsMap.getPS(vpsId);
2692          if (vps)
2693          {
2694            m_activeVPSId = vpsId;
2695            m_activeSPSId = spsId;
2696            return true;
2697          }
2698          else
2699          {
2700            printf("Warning: tried to activate PPS that refers to a non-existing VPS.");
2701          }
2702        }
2703      }
2704      else
2705      {
2706        printf("Warning: tried to activate a PPS that refers to a non-existing SPS.");
2707      }
2708    }
2709  }
2710  else
2711  {
2712    printf("Warning: tried to activate non-existing PPS.");
2713  }
2714
2715  // Failed to activate if reach here.
2716  m_activeSPSId=-1;
2717  m_activeVPSId=-1;
2718  return false;
2719}
2720
2721ProfileTierLevel::ProfileTierLevel()
2722  : m_profileSpace    (0)
2723  , m_tierFlag        (Level::MAIN)
2724  , m_profileIdc      (Profile::NONE)
2725  , m_levelIdc        (Level::NONE)
2726  , m_progressiveSourceFlag  (false)
2727  , m_interlacedSourceFlag   (false)
2728  , m_nonPackedConstraintFlag(false)
2729  , m_frameOnlyConstraintFlag(false)
2730{
2731  ::memset(m_profileCompatibilityFlag, 0, sizeof(m_profileCompatibilityFlag));
2732}
2733
2734TComPTL::TComPTL()
2735{
2736  ::memset(m_subLayerProfilePresentFlag, 0, sizeof(m_subLayerProfilePresentFlag));
2737  ::memset(m_subLayerLevelPresentFlag,   0, sizeof(m_subLayerLevelPresentFlag  ));
2738}
2739
2740Void calculateParameterSetChangedFlag(Bool &bChanged, const std::vector<UChar> *pOldData, const std::vector<UChar> &newData)
2741{
2742  if (!bChanged)
2743  {
2744    if ((pOldData==0 && pOldData!=0) || (pOldData!=0 && pOldData==0))
2745    {
2746      bChanged=true;
2747    }
2748    else if (pOldData!=0 && pOldData!=0)
2749    {
2750      // compare the two
2751      if (pOldData->size() != pOldData->size())
2752      {
2753        bChanged=true;
2754      }
2755      else
2756      {
2757        const UChar *pNewDataArray=&(newData)[0];
2758        const UChar *pOldDataArray=&(*pOldData)[0];
2759        if (memcmp(pOldDataArray, pNewDataArray, pOldData->size()))
2760        {
2761          bChanged=true;
2762        }
2763      }
2764    }
2765  }
2766}
2767
2768#if SVC_EXTENSION
2769Void ProfileTierLevel::copyProfileInfo(ProfileTierLevel *ptl)
2770{
2771  this->setProfileSpace          ( ptl->getProfileSpace()      );
2772  this->setTierFlag              ( ptl->getTierFlag()          );
2773  this->setProfileIdc            ( ptl->getProfileIdc()        );
2774  for(Int j = 0; j < 32; j++)
2775  {
2776    this->setProfileCompatibilityFlag(j, ptl->getProfileCompatibilityFlag(j));
2777  }
2778  this->setProgressiveSourceFlag  ( ptl->getProgressiveSourceFlag()  );
2779  this->setInterlacedSourceFlag   ( ptl->getInterlacedSourceFlag()   );
2780  this->setNonPackedConstraintFlag( ptl->getNonPackedConstraintFlag());
2781  this->setFrameOnlyConstraintFlag( ptl->getFrameOnlyConstraintFlag()); 
2782}
2783
2784const Window& TComPPS::getScaledRefLayerWindowForLayer(Int layerId) const
2785{
2786  static const Window win;
2787
2788  for( Int i = m_numRefLayerLocationOffsets-1; i >= 0; i-- )
2789  {
2790    if( layerId == m_refLocationOffsetLayerId[i] )
2791    {
2792      return m_scaledRefLayerWindow[i];
2793    }
2794  }
2795 
2796  return win;
2797}
2798
2799const Window& TComPPS::getRefLayerWindowForLayer(Int layerId) const
2800{
2801  static const Window win;
2802
2803  for( Int i = m_numRefLayerLocationOffsets-1; i >= 0; i-- )
2804  {
2805    if( layerId == m_refLocationOffsetLayerId[i] )
2806    {
2807      return m_refLayerWindow[i];
2808    }
2809  }
2810
2811  return win;
2812}
2813
2814Bool TComPPS::hasZeroResamplingPhase(Int refLayerId) const
2815{
2816  const ResamplingPhase &resamplingPhase = getResamplingPhase(refLayerId);
2817
2818  return ( resamplingPhase.phaseHorLuma == 0 && resamplingPhase.phaseHorChroma == 0 && resamplingPhase.phaseVerLuma == 0 && resamplingPhase.phaseVerChroma == 0 );
2819}
2820
2821const ResamplingPhase& TComPPS::getResamplingPhase(Int refLayerId) const
2822{
2823  static const ResamplingPhase resamplingPhase;
2824
2825  for( Int i = m_numRefLayerLocationOffsets-1; i >= 0; i-- )
2826  {
2827    if( refLayerId == m_refLocationOffsetLayerId[i] )
2828    {
2829      return m_resamplingPhase[i];
2830    }
2831  }
2832
2833  return resamplingPhase;
2834}
2835
2836Void TComVPS::deriveLayerIdListVariables()
2837{
2838  // For layer 0
2839  m_numLayerInIdList.push_back(1);
2840  m_layerSetLayerIdList.resize(m_vpsNumLayerSetsMinus1 + 1);
2841  m_layerSetLayerIdList[0].push_back(0);
2842 
2843  // For other layers
2844  for (Int i = 1; i <= m_vpsNumLayerSetsMinus1; i++)
2845  {
2846    for( Int m = 0; m <= m_maxLayerId; m++)
2847    {
2848      if( m_layerIdIncludedFlag[i][m] )
2849      {
2850        m_layerSetLayerIdList[i].push_back(m);
2851      }
2852    }
2853    m_numLayerInIdList.push_back((Int)m_layerSetLayerIdList[i].size());
2854  }
2855}
2856
2857Void TComVPS::deriveNumberOfSubDpbs()
2858{
2859  // Derive number of sub-DPBs
2860  // For layer set 0
2861  m_numSubDpbs[0] = 1;
2862  // For other layer sets
2863  for( Int i = 1; i < m_numLayerSets; i++)
2864  {
2865    m_numSubDpbs[i] = m_numLayerInIdList[i];
2866  }
2867}
2868
2869Void TComVPS::setTilesNotInUseFlag(Bool x)
2870{
2871  m_tilesNotInUseFlag = x;
2872
2873  if( m_tilesNotInUseFlag )
2874  {
2875    for( Int i = 0; i < getMaxLayers(); i++ )
2876    {
2877      m_tilesInUseFlag[i] = m_loopFilterNotAcrossTilesFlag[i] = m_tilesNotInUseFlag;
2878    }
2879 
2880    for( Int i = 1; i < getMaxLayers(); i++ )
2881    {
2882      for( Int j = 0; j < getNumDirectRefLayers(getLayerIdInNuh(i)); j++)
2883      {
2884        setTileBoundariesAlignedFlag(i, j, m_tilesNotInUseFlag);
2885      }
2886    }
2887  }
2888}
2889
2890Void TComVPS::setWppNotInUseFlag(Bool x)
2891{
2892  m_wppNotInUseFlag = x;
2893
2894  if( m_wppNotInUseFlag )
2895  {
2896    for( Int i = 0; i < getMaxLayers(); i++ )
2897    {
2898      m_wppInUseFlag[i] = m_wppNotInUseFlag;
2899    }
2900  }
2901}
2902
2903Void TComVPS::setRefLayersFlags(Int currLayerId)
2904{
2905  for (Int i = 0; i < m_numDirectRefLayers[currLayerId]; i++)
2906  {
2907    UInt refLayerId = getRefLayerId(currLayerId, i);
2908    m_recursiveRefLayerFlag[currLayerId][refLayerId] = true;
2909    for (Int k = 0; k < MAX_NUM_LAYER_IDS; k++)
2910    {
2911      m_recursiveRefLayerFlag[currLayerId][k] = m_recursiveRefLayerFlag[currLayerId][k] | m_recursiveRefLayerFlag[refLayerId][k];
2912    }
2913  }
2914}
2915
2916Void TComVPS::setNumRefLayers()
2917{
2918  memset( m_numberRefLayers, 0, sizeof( m_numberRefLayers ) );
2919
2920  for (Int i = 0; i < m_uiMaxLayers; i++)
2921  {
2922    UInt iNuhLId = m_layerIdInNuh[i];
2923    setRefLayersFlags(iNuhLId);
2924    for (UInt j = 0; j < MAX_NUM_LAYER_IDS; j++)
2925    {
2926      m_numberRefLayers[iNuhLId] += (m_recursiveRefLayerFlag[iNuhLId][j] == true ? 1 : 0);
2927    }
2928  }
2929}
2930
2931Void TComVPS::setPredictedLayerIds()
2932{
2933  for (UInt i = 0; i < m_uiMaxLayers - 1; i++)
2934  {
2935    UInt iNuhLId = m_layerIdInNuh[i];
2936    UInt predIdx = 0;
2937    for (UInt j = iNuhLId + 1; j < MAX_NUM_LAYER_IDS; j++)
2938    {
2939      if( m_recursiveRefLayerFlag[j][iNuhLId] )
2940      {
2941        m_predictedLayerId[iNuhLId][predIdx] = j;
2942        predIdx++;
2943      }
2944    }
2945    m_numPredictedLayers[iNuhLId] = predIdx;
2946  }
2947  m_numPredictedLayers[m_layerIdInNuh[m_uiMaxLayers-1]] = 0;
2948}
2949
2950Void TComVPS::setTreePartitionLayerIdList()
2951{
2952  Bool countedLayerIdxFlag[MAX_NUM_LAYER_IDS];
2953  memset( countedLayerIdxFlag, 0, sizeof(countedLayerIdxFlag) );
2954
2955  Int numIndependentLayers = 0;
2956
2957  for (UInt i = 0; i < m_uiMaxLayers; i++)
2958  {
2959    UInt iNuhLId = m_layerIdInNuh[i];
2960    if( m_numDirectRefLayers[iNuhLId] == 0 )
2961    {
2962      m_treePartitionLayerIdList[numIndependentLayers][0] = iNuhLId;
2963      m_numLayersInTreePartition[numIndependentLayers] = 1;
2964      for( UInt j = 0; j < m_numPredictedLayers[iNuhLId]; j++ )
2965      {
2966        if( !countedLayerIdxFlag[m_layerIdxInVps[iNuhLId]] )
2967        {
2968          m_treePartitionLayerIdList[numIndependentLayers][m_numLayersInTreePartition[numIndependentLayers]] = m_predictedLayerId[iNuhLId][j];
2969          m_numLayersInTreePartition[numIndependentLayers] = m_numLayersInTreePartition[numIndependentLayers] + 1;
2970          countedLayerIdxFlag[m_layerIdxInVps[m_predictedLayerId[iNuhLId][j]]] = true;
2971        }
2972      }
2973      numIndependentLayers++;
2974    }
2975  }
2976
2977  m_numIndependentLayers = numIndependentLayers;
2978}
2979
2980Void TComVPS::deriveLayerIdListVariablesForAddLayerSets()
2981{
2982  m_layerSetLayerIdList.resize(m_vpsNumLayerSetsMinus1 + 1 + m_numAddLayerSets);
2983
2984  for (UInt i = 0; i < m_numAddLayerSets; i++)
2985  {
2986    Int layerNum = 0;
2987    Int lsIdx = m_vpsNumLayerSetsMinus1 + 1 + i;
2988    for (Int treeIdx = 1; treeIdx < m_numIndependentLayers; treeIdx++)
2989    {
2990      for (Int layerCnt = 0; layerCnt < m_highestLayerIdxPlus1[i][treeIdx]; layerCnt++)
2991      {
2992        m_layerSetLayerIdList[lsIdx].push_back(m_treePartitionLayerIdList[treeIdx][layerCnt]);
2993        layerNum++;
2994      }
2995    }
2996    m_numLayerInIdList.push_back(layerNum);
2997  }
2998}
2999
3000Int TComVPS::getNumViews() const
3001{
3002  Int numViews = 1; 
3003  for( Int i = 0; i < m_uiMaxLayers; i++ )
3004  {
3005    Int lId = m_layerIdInNuh[i]; 
3006    if( i > 0 )
3007    {
3008      UChar newViewFlag = 1;
3009
3010      for( Int j = 0; j < i; j++ )
3011      {
3012        if( getViewIndex(lId) == getScalabilityId( m_layerIdInNuh[j], VIEW_ORDER_INDEX ) )
3013        {
3014          newViewFlag = 0;
3015          break;
3016        }
3017      }
3018
3019      numViews += newViewFlag; 
3020    }
3021  }
3022
3023  return numViews;
3024}
3025
3026Int TComVPS::getScalabilityId( Int layerIdInVps, ScalabilityType scalType ) const
3027{
3028  return getScalabilityMask( scalType ) ? getDimensionId( layerIdInVps, scalTypeToScalIdx( scalType ) ) : 0;
3029}
3030
3031Int TComVPS::scalTypeToScalIdx( ScalabilityType scalType ) const
3032{
3033  assert( (Int)scalType >= 0 && (Int)scalType <= MAX_VPS_NUM_SCALABILITY_TYPES ); 
3034  assert( (Int)scalType == MAX_VPS_NUM_SCALABILITY_TYPES || getScalabilityMask( scalType ) );
3035  Int scalIdx = 0; 
3036  for( Int curScalType = 0; curScalType < scalType; curScalType++ )
3037  {
3038    scalIdx += ( getScalabilityMask( curScalType ) ? 1 : 0 );
3039
3040  }
3041
3042  return scalIdx; 
3043}
3044
3045Int TComVPS::getLayerIdcForOls( Int olsIdx, Int layerId ) const
3046{
3047  Int layerIdc = -1;
3048  UInt lsIdx = m_outputLayerSetIdx[olsIdx];
3049
3050  std::vector<Int>::const_iterator it = std::find( m_layerSetLayerIdList[lsIdx].begin(), m_layerSetLayerIdList[lsIdx].end(), layerId );
3051
3052  if( it != m_layerSetLayerIdList[lsIdx].end() )
3053  {
3054    layerIdc = (Int)std::distance( m_layerSetLayerIdList[lsIdx].begin(), it );
3055  }
3056
3057  assert( layerIdc >= 0 );
3058
3059  return layerIdc;
3060}
3061
3062Void TComVPS::determineSubDpbInfoFlags()
3063{
3064  for(Int i = 1; i < getNumOutputLayerSets(); i++)
3065  {
3066    Int layerSetIdxForOutputLayerSet = getOutputLayerSetIdx( i );
3067    // For each output layer set, set the DPB size for each layer and the reorder/latency value the maximum for all layers
3068    Bool checkFlagOuter = false;      // Used to calculate sub_layer_flag_info_present_flag
3069    Bool checkFlagInner[MAX_TLAYER];  // Used to calculate sub_layer_dpb_info_present_flag
3070
3071    for(Int j = 0; j < getMaxTLayers(); j++)
3072    {
3073      // --------------------------------------------------------
3074      // To determine value of m_subLayerDpbInfoPresentFlag
3075      // --------------------------------------------------------
3076      if( j == 0 )  // checkFlagInner[0] is always 1
3077      {
3078        checkFlagInner[j] = true;     // Always signal sub-layer DPB information for the first sub-layer
3079      }
3080      else
3081      {
3082        checkFlagInner[j] = false;    // Initialize to be false. If the values of the current sub-layers matches with the earlier sub-layer,
3083                                      // then will be continue to be false - i.e. the j-th sub-layer DPB info is not signaled
3084        checkFlagInner[j] |= ( getMaxVpsNumReorderPics(i, j) != getMaxVpsNumReorderPics(i, j - 1) );
3085
3086        for(Int subDpbIdx = 0; subDpbIdx < getNumSubDpbs(layerSetIdxForOutputLayerSet) && !checkFlagInner[j]; subDpbIdx++)  // If checkFlagInner[j] is true, break and signal the values
3087        {
3088          checkFlagInner[j] |= ( getMaxVpsDecPicBufferingMinus1(i, subDpbIdx, j - 1) != getMaxVpsDecPicBufferingMinus1(i, subDpbIdx, j) );
3089        }
3090      }
3091      // If checkFlagInner[j] = true, then some value needs to be signalled for the j-th sub-layer
3092      setSubLayerDpbInfoPresentFlag( i, j, checkFlagInner[j] );
3093    }
3094
3095    // --------------------------------------------------------
3096    // To determine value of m_subLayerFlagInfoPresentFlag
3097    // --------------------------------------------------------
3098
3099    for(Int j = 1; j < getMaxTLayers(); j++) // Check if DPB info of any of non-zero sub-layers is signaled. If so set flag to one
3100    {
3101      if( getSubLayerDpbInfoPresentFlag(i, j) )
3102      {
3103        checkFlagOuter = true;
3104        break;
3105      }
3106    }
3107    setSubLayerFlagInfoPresentFlag( i, checkFlagOuter );
3108  }
3109}
3110
3111#if O0164_MULTI_LAYER_HRD
3112Void TComVPS::setBspHrdParameters( UInt hrdIdx, UInt frameRate, UInt numDU, UInt bitRate, Bool randomAccess )
3113{
3114  if( !getVpsVuiBspHrdPresentFlag() )
3115  {
3116    return;
3117  }
3118
3119  TComHRD *hrd = getBspHrd(hrdIdx);
3120
3121  Bool rateCnt = ( bitRate > 0 );
3122  hrd->setNalHrdParametersPresentFlag( rateCnt );
3123  hrd->setVclHrdParametersPresentFlag( rateCnt );
3124
3125  hrd->setSubPicCpbParamsPresentFlag( ( numDU > 1 ) );
3126
3127  if( hrd->getSubPicCpbParamsPresentFlag() )
3128  {
3129    hrd->setTickDivisorMinus2( 100 - 2 );                          //
3130    hrd->setDuCpbRemovalDelayLengthMinus1( 7 );                    // 8-bit precision ( plus 1 for last DU in AU )
3131    hrd->setSubPicCpbParamsInPicTimingSEIFlag( true );
3132    hrd->setDpbOutputDelayDuLengthMinus1( 5 + 7 );                 // With sub-clock tick factor of 100, at least 7 bits to have the same value as AU dpb delay
3133  }
3134  else
3135  {
3136    hrd->setSubPicCpbParamsInPicTimingSEIFlag( false ); 
3137  }
3138
3139  hrd->setBitRateScale( 4 );                                       // in units of 2~( 6 + 4 ) = 1,024 bps
3140  hrd->setCpbSizeScale( 6 );                                       // in units of 2~( 4 + 4 ) = 1,024 bit
3141  hrd->setDuCpbSizeScale( 6 );                                       // in units of 2~( 4 + 4 ) = 1,024 bit
3142
3143  hrd->setInitialCpbRemovalDelayLengthMinus1(15);                  // assuming 0.5 sec, log2( 90,000 * 0.5 ) = 16-bit
3144  if( randomAccess )
3145  {
3146    hrd->setCpbRemovalDelayLengthMinus1(5);                        // 32 = 2^5 (plus 1)
3147    hrd->setDpbOutputDelayLengthMinus1 (5);                        // 32 + 3 = 2^6
3148  }
3149  else
3150  {
3151    hrd->setCpbRemovalDelayLengthMinus1(9);                        // max. 2^10
3152    hrd->setDpbOutputDelayLengthMinus1 (9);                        // max. 2^10
3153  }
3154
3155  /*
3156  Note: only the case of "vps_max_temporal_layers_minus1 = 0" is supported.
3157  */
3158  Int i, j;
3159  UInt birateValue, cpbSizeValue;
3160  UInt ducpbSizeValue;
3161  UInt duBitRateValue = 0;
3162
3163  for( i = 0; i < MAX_TLAYER; i ++ )
3164  {
3165    hrd->setFixedPicRateFlag( i, 1 );
3166    hrd->setPicDurationInTcMinus1( i, 0 );
3167    hrd->setLowDelayHrdFlag( i, 0 );
3168    hrd->setCpbCntMinus1( i, 0 );
3169
3170    birateValue  = bitRate;
3171    cpbSizeValue = bitRate;                                     // 1 second
3172    ducpbSizeValue = bitRate/numDU;
3173    duBitRateValue = bitRate;
3174    for( j = 0; j < ( hrd->getCpbCntMinus1( i ) + 1 ); j ++ )
3175    {
3176      hrd->setBitRateValueMinus1( i, j, 0, ( birateValue  - 1 ) );
3177      hrd->setCpbSizeValueMinus1( i, j, 0, ( cpbSizeValue - 1 ) );
3178      hrd->setDuCpbSizeValueMinus1( i, j, 0, ( ducpbSizeValue - 1 ) );
3179      hrd->setCbrFlag( i, j, 0, ( j == 0 ) );
3180
3181      hrd->setBitRateValueMinus1( i, j, 1, ( birateValue  - 1) );
3182      hrd->setCpbSizeValueMinus1( i, j, 1, ( cpbSizeValue - 1 ) );
3183      hrd->setDuCpbSizeValueMinus1( i, j, 1, ( ducpbSizeValue - 1 ) );
3184      hrd->setDuBitRateValueMinus1( i, j, 1, ( duBitRateValue - 1 ) );
3185      hrd->setCbrFlag( i, j, 1, ( j == 0 ) );
3186    }
3187  }
3188}
3189#endif
3190
3191Void TComVPS::deriveNecessaryLayerFlag()
3192{
3193  m_necessaryLayerFlag.empty();
3194  m_numNecessaryLayers.empty();
3195  // Assumed that output layer sets and variables RecursiveRefLayer are already derived
3196  for( Int olsIdx = 0; olsIdx < m_numOutputLayerSets; olsIdx++)
3197  {
3198    deriveNecessaryLayerFlag(olsIdx);
3199  }
3200}
3201
3202Void TComVPS::deriveNecessaryLayerFlag(const Int olsIdx)
3203{
3204  Int lsIdx = m_outputLayerSetIdx[olsIdx];
3205  Int numLayersInLs = m_numLayerInIdList[lsIdx];
3206  assert( m_necessaryLayerFlag.size() == olsIdx );   // Function should be called in the correct order.
3207  m_necessaryLayerFlag.push_back( std::vector<Bool>( numLayersInLs, false ) ); // Initialize to false
3208  for( Int lsLayerIdx = 0; lsLayerIdx < numLayersInLs; lsLayerIdx++ )
3209  {
3210    if( m_outputLayerFlag[olsIdx][lsLayerIdx] )
3211    {
3212      m_necessaryLayerFlag[olsIdx][lsLayerIdx] = true;
3213      Int currNuhLayerId = m_layerSetLayerIdList[lsIdx][lsLayerIdx];
3214      for( Int rLsLayerIdx = 0; rLsLayerIdx < lsLayerIdx; rLsLayerIdx++ )
3215      {
3216        Int refNuhLayerId = m_layerSetLayerIdList[lsIdx][rLsLayerIdx];
3217        if( m_recursiveRefLayerFlag[currNuhLayerId][refNuhLayerId] )
3218        {
3219          m_necessaryLayerFlag[olsIdx][rLsLayerIdx] = true;
3220        }
3221      }
3222    }
3223  }
3224  m_numNecessaryLayers.push_back(std::accumulate(m_necessaryLayerFlag[olsIdx].begin(), m_necessaryLayerFlag[olsIdx].end(), 0));
3225}
3226
3227Void TComVPS::checkNecessaryLayerFlagCondition()
3228{
3229  /* It is a requirement of bitstream conformance that for each layer index layerIdx in the range of
3230  ( vps_base_layer_internal_flag ? 0 : 1 ) to MaxLayersMinus1, inclusive, there shall be at least one OLS with index olsIdx such that
3231  NecessaryLayerFlag[ olsIdx ][ lsLayerIdx ] is equal to 1 for the value of lsLayerIdx
3232  for which LayerSetLayerIdList[ OlsIdxToLsIdx[ olsIdx ] ][ lsLayerIdx ] is equal to layer_id_in_nuh[ layerIdx ]. */
3233  for(Int layerIdx = m_baseLayerInternalFlag ? 0 : 1; layerIdx < m_uiMaxLayers; layerIdx++)
3234  {
3235    Bool layerFoundNecessaryLayerFlag = false;
3236    for(Int olsIdx = 0; olsIdx < m_numOutputLayerSets; olsIdx++)
3237    {
3238      Int lsIdx = m_outputLayerSetIdx[olsIdx];
3239      Int currNuhLayerId = m_layerIdInNuh[layerIdx];
3240      std::vector<Int>::iterator iter = std::find( m_layerSetLayerIdList[lsIdx].begin(), m_layerSetLayerIdList[lsIdx].end(), currNuhLayerId );
3241      if( iter != m_layerSetLayerIdList[lsIdx].end() ) // Layer present in layer set
3242      {
3243        size_t positionLayer = iter - m_layerSetLayerIdList[lsIdx].begin();
3244        if( *(m_necessaryLayerFlag[olsIdx].begin() + positionLayer) == true )
3245        {
3246          layerFoundNecessaryLayerFlag = true;
3247          break;
3248        }
3249      }
3250    }
3251    assert( layerFoundNecessaryLayerFlag );
3252  }
3253}
3254
3255Int TComVPS::calculateLenOfSyntaxElement( const Int numVal ) const
3256{
3257  Int numBits = 1;
3258  while((1 << numBits) < numVal)
3259  {
3260    numBits++;
3261  }
3262  return numBits;
3263}
3264
3265Void TComVPS::calculateMaxSLInLayerSets()
3266{
3267  for(Int lsIdx = 0; lsIdx < getNumLayerSets(); lsIdx++)
3268  {
3269    UChar maxSLMinus1 = 0;
3270    for(Int k = 0; k < getNumLayersInIdList(lsIdx); k++ ) {
3271      Int  lId = getLayerSetLayerIdList(lsIdx, k);
3272      maxSLMinus1 = std::max(maxSLMinus1, getMaxTSLayersMinus1(getLayerIdxInVps(lId)));
3273    }
3274    setMaxSLayersInLayerSetMinus1(lsIdx,maxSLMinus1);
3275  }
3276}
3277
3278RepFormat::RepFormat()
3279#if AUXILIARY_PICTURES
3280: m_chromaFormatVpsIdc          (CHROMA_420)
3281#else
3282: m_chromaFormatVpsIdc          (0)
3283#endif
3284, m_separateColourPlaneVpsFlag  (false)
3285, m_picWidthVpsInLumaSamples    (0)
3286, m_picHeightVpsInLumaSamples   (0)
3287, m_bitDepthVpsLuma             (0)
3288, m_bitDepthVpsChroma           (0)
3289{}
3290
3291Void TComPTL::copyProfileInfo(TComPTL *ptl)
3292{
3293  // Copy all information related to general profile
3294  this->getGeneralPTL()->copyProfileInfo(ptl->getGeneralPTL());
3295}
3296
3297Bool TComSlice::setBaseColPic(  TComList<TComPic*>& rcListPic, UInt refLayerIdc )
3298{ 
3299  if(m_layerId == 0)
3300  {
3301    memset( m_pcBaseColPic, 0, sizeof( m_pcBaseColPic ) );
3302    return false;
3303  }       
3304
3305  TComPic* pic = xGetRefPic( rcListPic, getPOC() );
3306
3307  if( pic )
3308  {
3309    setBaseColPic(refLayerIdc, pic );
3310  }
3311  else
3312  {
3313    return false;
3314  }
3315 
3316  return true;
3317}
3318
3319TComPic* TComSlice::getBaseColPic(  TComList<TComPic*>& rcListPic )
3320{
3321  return xGetRefPic( rcListPic, m_iPOC );
3322}
3323
3324Void TComSlice::setILRPic(TComPic **pcIlpPic)
3325{
3326  for( Int i = 0; i < m_activeNumILRRefIdx; i++ )
3327  {
3328    Int refLayerIdc = m_interLayerPredLayerIdc[i];
3329
3330    if( pcIlpPic[refLayerIdc] )
3331    {
3332      TComPic* pcRefPicBL = m_pcBaseColPic[refLayerIdc];
3333
3334      // copy scalability ratio, it is needed to get the correct location for the motion field of the corresponding reference layer block
3335      pcIlpPic[refLayerIdc]->setSpatialEnhLayerFlag( refLayerIdc, m_pcPic->isSpatialEnhLayer(refLayerIdc) );
3336
3337      pcIlpPic[refLayerIdc]->copyUpsampledPictureYuv( m_pcPic->getFullPelBaseRec( refLayerIdc ), pcIlpPic[refLayerIdc]->getPicYuvRec() );     
3338      pcIlpPic[refLayerIdc]->getSlice(0)->setBaseColPic( refLayerIdc, pcRefPicBL );
3339
3340      //set reference picture POC of each ILP reference
3341      pcIlpPic[refLayerIdc]->getSlice(0)->setPOC( m_iPOC );
3342
3343      //set temporal Id
3344      pcIlpPic[refLayerIdc]->getSlice(0)->setTLayer( m_uiTLayer );
3345
3346      //copy layer id from the reference layer
3347      pcIlpPic[refLayerIdc]->setLayerId( pcRefPicBL->getLayerId() );
3348      pcIlpPic[refLayerIdc]->getSlice(0)->setLayerId(pcRefPicBL->getLayerId());
3349
3350      pcIlpPic[refLayerIdc]->getPicYuvRec()->setBorderExtension( false );
3351      pcIlpPic[refLayerIdc]->getPicYuvRec()->extendPicBorder();
3352      pcIlpPic[refLayerIdc]->setIsLongTerm(true);
3353
3354      // assign PPS to ILRP to be used for reference location offsets
3355      pcIlpPic[refLayerIdc]->getSlice(0)->setPPS( m_pcPic->getSlice(0)->getPPS() );
3356
3357      // assign SPS to ILRP to be used for obtaining bit depth
3358      pcIlpPic[refLayerIdc]->getSlice(0)->setSPS( m_pcPic->getSlice(0)->getSPS() );
3359
3360      // assing VPS to ILRP to be used for deriving layerIdx
3361      pcIlpPic[refLayerIdc]->getSlice(0)->setVPS( m_pcPic->getSlice(0)->getVPS() );
3362
3363      if( m_bMFMEnabledFlag && !(m_eNalUnitType >= NAL_UNIT_CODED_SLICE_BLA_W_LP && m_eNalUnitType <= NAL_UNIT_CODED_SLICE_CRA) )
3364      {
3365        //set reference picture POC of each ILP reference
3366        assert( pcIlpPic[refLayerIdc]->getPOC() == pcRefPicBL->getPOC() );
3367
3368        //copy slice type from the reference layer
3369        pcIlpPic[refLayerIdc]->getSlice(0)->setSliceType( pcRefPicBL->getSlice(0)->getSliceType() );
3370
3371        //copy "used for reference"
3372        pcIlpPic[refLayerIdc]->getSlice(0)->setReferenced( pcRefPicBL->getSlice(0)->isReferenced() );
3373
3374        for( Int refList = 0; refList < 2; refList++ )
3375        {
3376          RefPicList refPicList = RefPicList( refList );
3377
3378          //set reference POC of ILP
3379          pcIlpPic[refLayerIdc]->getSlice(0)->setNumRefIdx(refPicList, pcRefPicBL->getSlice(0)->getNumRefIdx(refPicList));
3380          assert(pcIlpPic[refLayerIdc]->getSlice(0)->getNumRefIdx(refPicList) >= 0);
3381          assert(pcIlpPic[refLayerIdc]->getSlice(0)->getNumRefIdx(refPicList) <= MAX_NUM_REF);
3382
3383          //initialize reference POC of ILP
3384          for(Int refIdx = 0; refIdx < pcRefPicBL->getSlice(0)->getNumRefIdx(refPicList); refIdx++)
3385          {
3386            pcIlpPic[refLayerIdc]->getSlice(0)->setRefPOC(pcRefPicBL->getSlice(0)->getRefPOC(refPicList, refIdx), refPicList, refIdx);
3387            pcIlpPic[refLayerIdc]->getSlice(0)->setRefPic(pcRefPicBL->getSlice(0)->getRefPic(refPicList, refIdx), refPicList, refIdx);
3388          }
3389
3390          for(Int refIdx = pcRefPicBL->getSlice(0)->getNumRefIdx(refPicList); refIdx < MAX_NUM_REF; refIdx++) 
3391          { 
3392            pcIlpPic[refLayerIdc]->getSlice(0)->setRefPOC(0, refPicList, refIdx); 
3393            pcIlpPic[refLayerIdc]->getSlice(0)->setRefPic(NULL, refPicList, refIdx); 
3394          }
3395
3396          //copy reference pictures' marking from the reference layer
3397          for(Int j = 0; j < MAX_NUM_REF + 1; j++)
3398          {
3399            pcIlpPic[refLayerIdc]->getSlice(0)->setIsUsedAsLongTerm(refList, j, pcRefPicBL->getSlice(0)->getIsUsedAsLongTerm(refList, j));
3400          }
3401        }
3402
3403        pcIlpPic[refLayerIdc]->copyUpsampledMvField( refLayerIdc, m_pcPic->getMvScalingFactor(), m_pcPic->getPosScalingFactor() );
3404      }
3405      else
3406      {
3407        pcIlpPic[refLayerIdc]->initUpsampledMvField();
3408      }
3409
3410      Int maxTidIlRefPicsPlus1 = m_pcVPS->getMaxTidIlRefPicsPlus1( pcIlpPic[refLayerIdc]->getSlice(0)->getLayerIdx(), getLayerIdx() );
3411      assert( (Int)pcIlpPic[refLayerIdc]->getSlice(0)->getTLayer() < maxTidIlRefPicsPlus1 || ( !maxTidIlRefPicsPlus1 && pcIlpPic[refLayerIdc]->getSlice(0)->getRapPicFlag() ) );
3412
3413    }
3414  }
3415}
3416
3417Int TComSlice::getReferenceLayerIdc( UInt refLayerId )
3418{ 
3419  for( Int i = 0; i < m_activeNumILRRefIdx; i++ )
3420  {
3421    if( m_pcVPS->getRefLayerId(m_layerId, m_interLayerPredLayerIdc[i]) == refLayerId )
3422    {
3423      return m_interLayerPredLayerIdc[i];
3424    }
3425  }
3426
3427  return -1;
3428}
3429
3430Bool TComSlice::getBlaPicFlag()
3431{
3432    return  getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
3433    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
3434    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP;
3435}
3436
3437Bool TComSlice::getCraPicFlag()
3438{
3439    return getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA;
3440}
3441
3442Bool TComSlice::getRaslPicFlag()
3443{
3444  return  getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R
3445  || getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N;
3446}
3447
3448Bool TComSlice::getRadlPicFlag()
3449{
3450  return  getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_R
3451  || getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N;
3452}
3453
3454Void TComSlice::decrementRefPocValues(Int const decrementValue)
3455{
3456  for(Int listNum = 0; listNum < 2; listNum++)
3457  {
3458    RefPicList dpbPicSliceList = (listNum == 1) ? REF_PIC_LIST_1 : REF_PIC_LIST_0;
3459    for(Int listIdx = 0; listIdx < getNumRefIdx( dpbPicSliceList ); listIdx++)
3460    {
3461      setRefPOC( getRefPOC(dpbPicSliceList, listIdx) - decrementValue, 
3462                  dpbPicSliceList,
3463                  listIdx
3464                  );
3465    }
3466  }
3467}
3468
3469Int TComSlice::getCurrMsb( Int currLsb, Int prevLsb, Int prevMsb, Int maxLsbVal )
3470{
3471  if( prevLsb - currLsb >= (maxLsbVal >> 1) )
3472  {
3473    return prevMsb + maxLsbVal;
3474  }
3475  else if( currLsb - prevLsb > (maxLsbVal >> 1) )
3476  {
3477    return prevMsb - maxLsbVal;
3478  }
3479  else
3480  {
3481    return prevMsb;
3482  }
3483}
3484
3485Void TComSlice::setRefPicListModificationSvc()
3486{
3487  if( !m_pcPPS->getListsModificationPresentFlag()) 
3488  {
3489    return;
3490  }
3491
3492  if(m_eNalUnitType >= NAL_UNIT_CODED_SLICE_BLA_W_LP && m_eNalUnitType <= NAL_UNIT_CODED_SLICE_CRA)
3493  {
3494    return;
3495  }
3496
3497  TComRefPicListModification* refPicListModification = &m_RefPicListModification;
3498  Int numberOfRpsCurrTempList = this->getNumRpsCurrTempList();  // total number of ref pics in listTemp0 including inter-layer ref pics
3499#if SVC_EXTENSION
3500  Int numberOfPocBeforeCurr = this->getNumNegativeRpsCurrTempList();  // number of negative temporal ref pics
3501#endif
3502
3503  assert(m_aiNumRefIdx[REF_PIC_LIST_0] > 0);
3504  assert(m_aiNumRefIdx[REF_PIC_LIST_1] > 0);
3505
3506  //set L0 inter-layer reference picture modification
3507#if SVC_EXTENSION
3508  Bool hasModification = (m_aiNumRefIdx[REF_PIC_LIST_0] == (numberOfPocBeforeCurr + m_activeNumILRRefIdx)) ? false : true;
3509
3510  if( m_activeNumILRRefIdx > 1 )
3511  {
3512    hasModification = (m_aiNumRefIdx[REF_PIC_LIST_0] >= (numberOfPocBeforeCurr + m_activeNumILRRefIdx)) ? false : true;
3513  }
3514#else
3515  Bool hasModification = (m_aiNumRefIdx[REF_PIC_LIST_0] == numberOfRpsCurrTempList) ? false : true;
3516#endif
3517  hasModification = hasModification && ( m_aiNumRefIdx[REF_PIC_LIST_0] > 1 );
3518  refPicListModification->setRefPicListModificationFlagL0(hasModification);
3519  if(hasModification)
3520  { 
3521    for(Int i = 0; i < min(m_aiNumRefIdx[REF_PIC_LIST_0], numberOfRpsCurrTempList); i++)
3522    {
3523      refPicListModification->setRefPicSetIdxL0(i, i);
3524    }
3525
3526    if(m_aiNumRefIdx[REF_PIC_LIST_0] > numberOfRpsCurrTempList)
3527    {
3528      // repeat last ref pic when the number of active ref idx are more than RPS entries
3529      for (Int i = numberOfRpsCurrTempList; i < m_aiNumRefIdx[REF_PIC_LIST_0]; i ++)
3530      {
3531        refPicListModification->setRefPicSetIdxL0(i, numberOfRpsCurrTempList - 1);
3532      }
3533    }
3534    else
3535    {
3536      // number of ILRPs included into the reference picture list with the list modification
3537      Int includeNumILRP = min( max(1, m_aiNumRefIdx[REF_PIC_LIST_0]-numberOfPocBeforeCurr), m_activeNumILRRefIdx);
3538
3539      for(Int i = includeNumILRP; i > 0; i-- )
3540      {
3541#if SVC_EXTENSION
3542        if( numberOfPocBeforeCurr >= m_aiNumRefIdx[REF_PIC_LIST_0] )
3543        {
3544          refPicListModification->setRefPicSetIdxL0(m_aiNumRefIdx[REF_PIC_LIST_0] - i, numberOfPocBeforeCurr + includeNumILRP - i);
3545        }
3546        else
3547        {
3548          refPicListModification->setRefPicSetIdxL0(m_aiNumRefIdx[REF_PIC_LIST_0] - i, numberOfPocBeforeCurr + includeNumILRP - i);
3549          for( Int j = numberOfPocBeforeCurr; j < (m_aiNumRefIdx[REF_PIC_LIST_0] - i); j++ )
3550          {
3551            assert( j + includeNumILRP < numberOfRpsCurrTempList );
3552            refPicListModification->setRefPicSetIdxL0(j, j + includeNumILRP);
3553          }
3554        }
3555#else
3556        refPicListModification->setRefPicSetIdxL0(m_aiNumRefIdx[REF_PIC_LIST_0] - i, numberOfRpsCurrTempList - i);
3557#endif
3558      }
3559    }
3560  }
3561
3562  //set L1 inter-layer reference picture modification
3563  hasModification = (m_aiNumRefIdx[REF_PIC_LIST_1] >= numberOfRpsCurrTempList) ? false : true;
3564  hasModification = hasModification && ( m_aiNumRefIdx[REF_PIC_LIST_1] > 1 );
3565
3566  refPicListModification->setRefPicListModificationFlagL1(hasModification);
3567  if(hasModification)
3568  { 
3569    for(Int i = 0; i < min(m_aiNumRefIdx[REF_PIC_LIST_1], numberOfRpsCurrTempList); i++)
3570    {
3571      refPicListModification->setRefPicSetIdxL1(i, i);
3572    }
3573    if(m_aiNumRefIdx[REF_PIC_LIST_1] > numberOfRpsCurrTempList)
3574    {
3575      for (Int i = numberOfRpsCurrTempList; i < m_aiNumRefIdx[REF_PIC_LIST_1]; i ++)
3576      {
3577        // repeat last ref pic when the number of active ref idx are more than RPS entries
3578        refPicListModification->setRefPicSetIdxL1(i, numberOfRpsCurrTempList - 1); 
3579      }
3580    }
3581    else
3582    {
3583      Int includeNumILRP = min(m_aiNumRefIdx[REF_PIC_LIST_1], m_activeNumILRRefIdx);
3584
3585      for(Int i = includeNumILRP; i > 0; i-- )
3586      {
3587        refPicListModification->setRefPicSetIdxL1(m_aiNumRefIdx[REF_PIC_LIST_1] - i, numberOfRpsCurrTempList - i);
3588      }
3589    }
3590  }
3591  return;
3592}
3593
3594Int TComSlice::getNumNegativeRpsCurrTempList()
3595{
3596  if( m_eSliceType == I_SLICE ) 
3597  {
3598    return 0;
3599  }
3600
3601  Int numPocBeforeCurr = 0;
3602
3603  for( UInt i = 0; i < m_pRPS->getNumberOfNegativePictures(); i++ )
3604  {
3605    if( m_pRPS->getUsed(i) )
3606    {
3607      numPocBeforeCurr++;
3608    }
3609  }
3610
3611  return numPocBeforeCurr;
3612}
3613
3614Void TComSPS::inferSPS( const UInt layerId, TComVPS* vps )
3615{
3616  RepFormat* repFormat = NULL;
3617
3618  if( layerId == 0 || m_bV1CompatibleSPSFlag == 1 )
3619  {
3620    if( layerId == 0 && vps->getNonHEVCBaseLayerFlag() )
3621    {
3622      repFormat = vps->getVpsRepFormat(layerId);
3623    }
3624  }
3625  else
3626  {
3627    repFormat = vps->getVpsRepFormat(m_updateRepFormatFlag ? m_updateRepFormatIndex : vps->getVpsRepFormatIdx(vps->getLayerIdxInVps(layerId)));
3628  }
3629
3630  if( repFormat )
3631  {
3632    m_chromaFormatIdc = repFormat->getChromaFormatVpsIdc();
3633    m_picWidthInLumaSamples = repFormat->getPicWidthVpsInLumaSamples();
3634    m_picHeightInLumaSamples = repFormat->getPicHeightVpsInLumaSamples();
3635
3636    m_bitDepths.recon[CHANNEL_TYPE_LUMA] = repFormat->getBitDepthVps(CHANNEL_TYPE_LUMA);
3637    m_bitDepths.recon[CHANNEL_TYPE_CHROMA] = repFormat->getBitDepthVps(CHANNEL_TYPE_CHROMA);
3638
3639    m_qpBDOffset[CHANNEL_TYPE_LUMA] = (m_bitDepths.recon[CHANNEL_TYPE_LUMA] - 8) * 6;
3640    m_qpBDOffset[CHANNEL_TYPE_CHROMA] = (m_bitDepths.recon[CHANNEL_TYPE_CHROMA] - 8) * 6;
3641
3642    m_conformanceWindow = repFormat->getConformanceWindowVps();
3643  }
3644}
3645#endif //SVC_EXTENSION
3646
3647//! \}
Note: See TracBrowser for help on using the repository browser.