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

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

fix target layer Id assignment, ticket #97

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