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

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

copy list modification information from the precious slice at encoder

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