source: 3DVCSoftware/trunk/source/Lib/TLibCommon/TComSlice.cpp

Last change on this file was 1413, checked in by tech, 6 years ago

Merged HTM-16.2-dev@1412

  • Property svn:eol-style set to native
File size: 179.9 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-2017, ITU/ISO/IEC
7 * All rights reserved.
8
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions are met:
12 *
13 *  * Redistributions of source code must retain the above copyright notice,
14 *    this list of conditions and the following disclaimer.
15 *  * Redistributions in binary form must reproduce the above copyright notice,
16 *    this list of conditions and the following disclaimer in the documentation
17 *    and/or other materials provided with the distribution.
18 *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
19 *    be used to endorse or promote products derived from this software without
20 *    specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
23 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
26 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
32 * THE POSSIBILITY OF SUCH DAMAGE.
33 */
34
35/** \file     TComSlice.cpp
36    \brief    slice header and SPS class
37*/
38
39#include "CommonDef.h"
40#include "TComSlice.h"
41#include "TComPic.h"
42#include "TLibEncoder/TEncSbac.h"
43#include "TLibDecoder/TDecSbac.h"
44#if NH_MV
45#include <set>
46#endif
47
48//! \ingroup TLibCommon
49//! \{
50
51TComSlice::TComSlice()
52: m_iPPSId                        ( -1 )
53, m_PicOutputFlag                 ( true )
54#if NH_MV
55, m_slicePicOrderCntLsb           ( 0 )
56#endif
57, m_iPOC                          ( 0 )
58, m_iLastIDR                      ( 0 )
59, m_iAssociatedIRAP               ( 0 )
60, m_iAssociatedIRAPType           ( NAL_UNIT_INVALID )
61, m_pRPS                          ( 0 )
62, m_localRPS                      ( )
63, m_rpsIdx                        ( 0 )
64, m_RefPicListModification        ( )
65, m_eNalUnitType                  ( NAL_UNIT_CODED_SLICE_IDR_W_RADL )
66, m_eSliceType                    ( I_SLICE )
67, m_iSliceQp                      ( 0 )
68, m_dependentSliceSegmentFlag     ( false )
69#if ADAPTIVE_QP_SELECTION
70, m_iSliceQpBase                  ( 0 )
71#endif
72, m_ChromaQpAdjEnabled            ( false )
73, m_deblockingFilterDisable       ( false )
74, m_deblockingFilterOverrideFlag  ( false )
75, m_deblockingFilterBetaOffsetDiv2( 0 )
76, m_deblockingFilterTcOffsetDiv2  ( 0 )
77, m_bCheckLDC                     ( false )
78, m_iSliceQpDelta                 ( 0 )
79, m_iDepth                        ( 0 )
80, m_bRefenced                     ( false )
81, m_pcVPS                         ( NULL )
82, m_pcSPS                         ( NULL )
83, m_pcPPS                         ( NULL )
84, m_pcPic                         ( NULL )
85, m_colFromL0Flag                 ( true )
86, m_noOutputPriorPicsFlag         ( false )
87, m_noRaslOutputFlag              ( false )
88, m_handleCraAsBlaFlag            ( false )
89, m_colRefIdx                     ( 0 )
90, m_maxNumMergeCand               ( 0 )
91, m_uiTLayer                      ( 0 )
92, m_bTLayerSwitchingFlag          ( false )
93, m_sliceMode                     ( NO_SLICES )
94, m_sliceArgument                 ( 0 )
95, m_sliceCurStartCtuTsAddr        ( 0 )
96, m_sliceCurEndCtuTsAddr          ( 0 )
97, m_sliceIdx                      ( 0 )
98, m_sliceSegmentMode              ( NO_SLICES )
99, m_sliceSegmentArgument          ( 0 )
100, m_sliceSegmentCurStartCtuTsAddr ( 0 )
101, m_sliceSegmentCurEndCtuTsAddr   ( 0 )
102, m_nextSlice                     ( false )
103, m_nextSliceSegment              ( false )
104, m_sliceBits                     ( 0 )
105, m_sliceSegmentBits              ( 0 )
106, m_bFinalized                    ( false )
107, m_bTestWeightPred               ( false )
108, m_bTestWeightBiPred             ( false )
109, m_substreamSizes                ( )
110, m_cabacInitFlag                 ( false )
111, m_bLMvdL1Zero                   ( false )
112, m_temporalLayerNonReferenceFlag ( false )
113, m_LFCrossSliceBoundaryFlag      ( false )
114, m_enableTMVPFlag                ( true )
115, m_encCABACTableIdx              (I_SLICE)
116#if NH_MV
117, m_refPicSetInterLayer0          ( NULL )
118, m_refPicSetInterLayer1          ( NULL )
119, m_layerId                       (0)
120, m_viewId                        (0)
121, m_viewIndex                     (0)
122#if NH_3D_VSO || NH_3D
123, m_isDepth                       (false)
124#endif
125#if NH_MV
126, m_pocResetFlag                  (false)
127, m_crossLayerBlaFlag             (false)
128#endif
129, m_discardableFlag               (false)
130, m_interLayerPredEnabledFlag     (false)
131, m_numInterLayerRefPicsMinus1    (0)
132#if NH_MV
133, m_sliceSegmentHeaderExtensionLength (0)
134, m_pocResetIdc                   (0)
135, m_pocResetPeriodId              (0)
136, m_hasPocResetPeriodIdPresent    (false)
137, m_fullPocResetFlag              (false)
138, m_pocLsbVal                     (0)
139, m_pocMsbCycleValPresentFlag     (false)
140, m_pocMsbCycleVal                (0)
141, m_pocMsbValRequiredFlag         (false)
142#endif
143#if NH_3D
144, m_bApplyIC                      (false)
145, m_icSkipParseFlag               (false)
146, m_inCmpPredFlag                 (false)
147, m_numViews                      (0)
148, m_depthToDisparityB             (NULL)
149, m_depthToDisparityF             (NULL)
150, m_bApplyDIS                     (false)
151#endif
152#endif
153{
154
155#if NH_MV
156  m_shortTermRefPicSetIdx = 0; 
157  m_numLongTermSps        = 0; 
158  m_numLongTermPics       = 0; 
159  for (Int i = 0; i < MAX_NUM_PICS_RPS; i++)
160  {
161    m_ltIdxSps          [i] = 0; 
162    m_deltaPocMsbCycleLt[i] = 0;
163  }
164  setSliceTemporalMvpEnabledFlag( false ); 
165#endif
166  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
167  {
168    m_aiNumRefIdx[i] = 0;
169  }
170
171  for (UInt component = 0; component < MAX_NUM_COMPONENT; component++)
172  {
173    m_lambdas            [component] = 0.0;
174    m_iSliceChromaQpDelta[component] = 0;
175  }
176
177  initEqualRef();
178
179  for ( Int idx = 0; idx < MAX_NUM_REF; idx++ )
180  {
181    m_list1IdxToList0Idx[idx] = -1;
182  }
183
184  for(Int iNumCount = 0; iNumCount < MAX_NUM_REF; iNumCount++)
185  {
186    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
187    {
188      m_apcRefPicList [i][iNumCount] = NULL;
189      m_aiRefPOCList  [i][iNumCount] = 0;
190    }
191#if NH_MV
192    m_aiRefLayerIdList[0][iNumCount] = 0;
193    m_aiRefLayerIdList[1][iNumCount] = 0;
194#endif
195  }
196
197  resetWpScaling();
198  initWpAcDcParam();
199
200  for(Int ch=0; ch < MAX_NUM_CHANNEL_TYPE; ch++)
201  {
202    m_saoEnabledFlag[ch] = false;
203  }
204#if NH_MV
205  for (Int i = 0; i < MAX_NUM_LAYERS; i++ )
206  {
207    m_interLayerPredLayerIdc[ i ] = -1;
208  }
209#endif
210#if NH_3D
211  m_iDefaultRefViewIdx = -1;
212  m_bDefaultRefViewIdxAvailableFlag = false;
213  m_ivMvPredFlag           = false;
214  m_ivMvScalingFlag        = false;
215  m_ivResPredFlag          = false; 
216  m_depthRefinementFlag    = false;
217  m_viewSynthesisPredFlag  = false;
218  m_depthBasedBlkPartFlag  = false;
219  m_mpiFlag                = false;
220  m_intraContourFlag       = false;
221  m_intraSdcWedgeFlag      = false;
222  m_qtPredFlag             = false;
223  m_interSdcFlag           = false;
224  m_depthIntraSkipFlag     = false;
225  m_subPbSize              =  1 << 6;
226  m_mpiSubPbSize           =  1 << 6;
227
228  m_aaiCodedOffset.resize(2);
229  m_aaiCodedScale .resize(2);
230  for (Int i = 0; i < 2; i++)
231  {
232    m_aaiCodedOffset[i].resize(MAX_NUM_LAYERS);
233    m_aaiCodedScale [i].resize(MAX_NUM_LAYERS);
234  }
235 
236#endif
237
238}
239
240TComSlice::~TComSlice()
241{
242#if NH_3D
243  for( UInt i = 0; i < m_numViews; i++ )
244  {
245    if ( m_depthToDisparityB && m_depthToDisparityB[ i ] )
246    {
247      delete[] m_depthToDisparityB [ i ];
248    }
249
250    if ( m_depthToDisparityF && m_depthToDisparityF[ i ] ) 
251    {
252      delete[] m_depthToDisparityF [ i ];
253    }
254  }
255
256  if ( m_depthToDisparityF )
257  {
258    delete[] m_depthToDisparityF; 
259  }
260
261  m_depthToDisparityF = NULL;
262
263  if ( m_depthToDisparityB )
264    delete[] m_depthToDisparityB; 
265
266  m_depthToDisparityB = NULL;
267#endif
268
269}
270
271
272Void TComSlice::initSlice()
273{
274  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
275  {
276    m_aiNumRefIdx[i]      = 0;
277  }
278  m_colFromL0Flag = true;
279
280  m_colRefIdx = 0;
281  initEqualRef();
282
283  m_bCheckLDC = false;
284
285  for (UInt component = 0; component < MAX_NUM_COMPONENT; component++)
286  {
287    m_iSliceChromaQpDelta[component] = 0;
288  }
289#if NH_3D
290  m_maxNumMergeCand = MRG_MAX_NUM_CANDS_MEM;
291#else
292  m_maxNumMergeCand = MRG_MAX_NUM_CANDS;
293#endif
294
295  m_bFinalized=false;
296
297  m_substreamSizes.clear();
298  m_cabacInitFlag        = false;
299  m_enableTMVPFlag = true;
300#if NH_3D
301  m_aiAlterRefIdx[0]                  = -1;
302  m_aiAlterRefIdx[1]                  = -1;
303#endif
304}
305
306Bool TComSlice::getRapPicFlag() const
307{
308  return getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
309      || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
310      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
311      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
312      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
313      || getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA;
314}
315
316
317Void  TComSlice::sortPicList        (TComList<TComPic*>& rcListPic)
318{
319  TComPic*    pcPicExtract;
320  TComPic*    pcPicInsert;
321
322  TComList<TComPic*>::iterator    iterPicExtract;
323  TComList<TComPic*>::iterator    iterPicExtract_1;
324  TComList<TComPic*>::iterator    iterPicInsert;
325
326  for (Int i = 1; i < (Int)(rcListPic.size()); i++)
327  {
328    iterPicExtract = rcListPic.begin();
329    for (Int j = 0; j < i; j++)
330    {
331      iterPicExtract++;
332    }
333    pcPicExtract = *(iterPicExtract);
334    pcPicExtract->setCurrSliceIdx(0);
335
336    iterPicInsert = rcListPic.begin();
337    while (iterPicInsert != iterPicExtract)
338    {
339      pcPicInsert = *(iterPicInsert);
340      pcPicInsert->setCurrSliceIdx(0);
341      if (pcPicInsert->getPOC() >= pcPicExtract->getPOC())
342      {
343        break;
344      }
345
346      iterPicInsert++;
347    }
348
349    iterPicExtract_1 = iterPicExtract;    iterPicExtract_1++;
350
351    //  swap iterPicExtract and iterPicInsert, iterPicExtract = curr. / iterPicInsert = insertion position
352    rcListPic.insert (iterPicInsert, iterPicExtract, iterPicExtract_1);
353    rcListPic.erase  (iterPicExtract);
354  }
355}
356
357TComPic* TComSlice::xGetRefPic (TComList<TComPic*>& rcListPic, Int poc)
358{
359  TComList<TComPic*>::iterator  iterPic = rcListPic.begin();
360  TComPic*                      pcPic = *(iterPic);
361  while ( iterPic != rcListPic.end() )
362  {
363    if(pcPic->getPOC() == poc)
364    {
365      break;
366    }
367    iterPic++;
368    pcPic = *(iterPic);
369  }
370  return  pcPic;
371}
372
373
374TComPic* TComSlice::xGetLongTermRefPic(TComList<TComPic*>& rcListPic, Int poc, Bool pocHasMsb)
375{
376  TComList<TComPic*>::iterator  iterPic = rcListPic.begin();
377  TComPic*                      pcPic = *(iterPic);
378  TComPic*                      pcStPic = pcPic;
379
380  Int pocCycle = 1 << getSPS()->getBitsForPOC();
381  if (!pocHasMsb)
382  {
383    poc = poc & (pocCycle - 1);
384  }
385
386  while ( iterPic != rcListPic.end() )
387  {
388    pcPic = *(iterPic);
389    if (pcPic && pcPic->getPOC()!=this->getPOC() && pcPic->getSlice( 0 )->isReferenced())
390    {
391      Int picPoc = pcPic->getPOC();
392      if (!pocHasMsb)
393      {
394        picPoc = picPoc & (pocCycle - 1);
395      }
396
397      if (poc == picPoc)
398      {
399        if(pcPic->getIsLongTerm())
400        {
401          return pcPic;
402        }
403        else
404        {
405          pcStPic = pcPic;
406        }
407        break;
408      }
409    }
410
411    iterPic++;
412  }
413
414  return  pcStPic;
415}
416
417Void TComSlice::setRefPOCList       ()
418{
419  for (Int iDir = 0; iDir < NUM_REF_PIC_LIST_01; iDir++)
420  {
421    for (Int iNumRefIdx = 0; iNumRefIdx < m_aiNumRefIdx[iDir]; iNumRefIdx++)
422    {
423      m_aiRefPOCList[iDir][iNumRefIdx] = m_apcRefPicList[iDir][iNumRefIdx]->getPOC();
424#if NH_MV
425      m_aiRefLayerIdList[iDir][iNumRefIdx] = m_apcRefPicList[iDir][iNumRefIdx]->getLayerId();
426#endif
427    }
428  }
429
430}
431
432Void TComSlice::setList1IdxToList0Idx()
433{
434  Int idxL0, idxL1;
435  for ( idxL1 = 0; idxL1 < getNumRefIdx( REF_PIC_LIST_1 ); idxL1++ )
436  {
437    m_list1IdxToList0Idx[idxL1] = -1;
438    for ( idxL0 = 0; idxL0 < getNumRefIdx( REF_PIC_LIST_0 ); idxL0++ )
439    {
440      if ( m_apcRefPicList[REF_PIC_LIST_0][idxL0]->getPOC() == m_apcRefPicList[REF_PIC_LIST_1][idxL1]->getPOC() )
441      {
442        m_list1IdxToList0Idx[idxL1] = idxL0;
443        break;
444      }
445    }
446  }
447}
448
449#if !NH_MV
450Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr )
451{
452    if (m_eSliceType == I_SLICE)
453    {
454      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
455      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
456
457    if (!checkNumPocTotalCurr)
458    {
459      return;
460    }
461  }
462
463  TComPic*  pcRefPic= NULL;
464  static const UInt MAX_NUM_NEGATIVE_PICTURES=16;
465  TComPic*  RefPicSetStCurr0[MAX_NUM_NEGATIVE_PICTURES];
466  TComPic*  RefPicSetStCurr1[MAX_NUM_NEGATIVE_PICTURES];
467  TComPic*  RefPicSetLtCurr[MAX_NUM_NEGATIVE_PICTURES];
468  UInt NumPicStCurr0 = 0;
469  UInt NumPicStCurr1 = 0;
470  UInt NumPicLtCurr = 0;
471  Int i;
472
473  for(i=0; i < m_pRPS->getNumberOfNegativePictures(); i++)
474  {
475    if(m_pRPS->getUsed(i))
476    {
477      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pRPS->getDeltaPOC(i));
478      pcRefPic->setIsLongTerm(0);
479      pcRefPic->getPicYuvRec()->extendPicBorder();
480      RefPicSetStCurr0[NumPicStCurr0] = pcRefPic;
481      NumPicStCurr0++;
482      pcRefPic->setCheckLTMSBPresent(false);
483    }
484  }
485
486  for(; i < m_pRPS->getNumberOfNegativePictures()+m_pRPS->getNumberOfPositivePictures(); i++)
487  {
488    if(m_pRPS->getUsed(i))
489    {
490      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pRPS->getDeltaPOC(i));
491      pcRefPic->setIsLongTerm(0);
492      pcRefPic->getPicYuvRec()->extendPicBorder();
493      RefPicSetStCurr1[NumPicStCurr1] = pcRefPic;
494      NumPicStCurr1++;
495      pcRefPic->setCheckLTMSBPresent(false);
496    }
497  }
498
499  for(i = m_pRPS->getNumberOfNegativePictures()+m_pRPS->getNumberOfPositivePictures()+m_pRPS->getNumberOfLongtermPictures()-1; i > m_pRPS->getNumberOfNegativePictures()+m_pRPS->getNumberOfPositivePictures()-1 ; i--)
500  {
501    if(m_pRPS->getUsed(i))
502    {
503      pcRefPic = xGetLongTermRefPic(rcListPic, m_pRPS->getPOC(i), m_pRPS->getCheckLTMSBPresent(i));
504      pcRefPic->setIsLongTerm(1);
505      pcRefPic->getPicYuvRec()->extendPicBorder();
506      RefPicSetLtCurr[NumPicLtCurr] = pcRefPic;
507      NumPicLtCurr++;
508    }
509    if(pcRefPic==NULL)
510    {
511      pcRefPic = xGetLongTermRefPic(rcListPic, m_pRPS->getPOC(i), m_pRPS->getCheckLTMSBPresent(i));
512    }
513    pcRefPic->setCheckLTMSBPresent(m_pRPS->getCheckLTMSBPresent(i));
514  }
515
516  // ref_pic_list_init
517  TComPic*  rpsCurrList0[MAX_NUM_REF+1];
518  TComPic*  rpsCurrList1[MAX_NUM_REF+1];
519  Int numPicTotalCurr = NumPicStCurr0 + NumPicStCurr1 + NumPicLtCurr;
520
521  if (checkNumPocTotalCurr)
522  {
523    // 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:
524    // - If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
525    // - Otherwise, when the current picture contains a P or B slice, the value of NumPocTotalCurr shall not be equal to 0.
526    if (getRapPicFlag())
527    {
528      assert(numPicTotalCurr == 0);
529    }
530
531    if (m_eSliceType == I_SLICE)
532    {
533      return;
534    }
535
536    assert(numPicTotalCurr > 0);
537    // general tier and level limit:
538    assert(numPicTotalCurr <= 8);
539  }
540
541  Int cIdx = 0;
542  for ( i=0; i<NumPicStCurr0; i++, cIdx++)
543  {
544    rpsCurrList0[cIdx] = RefPicSetStCurr0[i];
545  }
546  for ( i=0; i<NumPicStCurr1; i++, cIdx++)
547  {
548    rpsCurrList0[cIdx] = RefPicSetStCurr1[i];
549  }
550  for ( i=0; i<NumPicLtCurr;  i++, cIdx++)
551  {
552    rpsCurrList0[cIdx] = RefPicSetLtCurr[i];
553  }
554  assert(cIdx == numPicTotalCurr);
555
556  if (m_eSliceType==B_SLICE)
557  {
558    cIdx = 0;
559    for ( i=0; i<NumPicStCurr1; i++, cIdx++)
560    {
561      rpsCurrList1[cIdx] = RefPicSetStCurr1[i];
562    }
563    for ( i=0; i<NumPicStCurr0; i++, cIdx++)
564    {
565      rpsCurrList1[cIdx] = RefPicSetStCurr0[i];
566    }
567    for ( i=0; i<NumPicLtCurr;  i++, cIdx++)
568    {
569      rpsCurrList1[cIdx] = RefPicSetLtCurr[i];
570    }
571    assert(cIdx == numPicTotalCurr);
572  }
573
574  ::memset(m_bIsUsedAsLongTerm, 0, sizeof(m_bIsUsedAsLongTerm));
575
576  for (Int rIdx = 0; rIdx < m_aiNumRefIdx[REF_PIC_LIST_0]; rIdx ++)
577  {
578    cIdx = m_RefPicListModification.getRefPicListModificationFlagL0() ? m_RefPicListModification.getRefPicSetIdxL0(rIdx) : rIdx % numPicTotalCurr;
579    assert(cIdx >= 0 && cIdx < numPicTotalCurr);
580    m_apcRefPicList[REF_PIC_LIST_0][rIdx] = rpsCurrList0[ cIdx ];
581    m_bIsUsedAsLongTerm[REF_PIC_LIST_0][rIdx] = ( cIdx >= NumPicStCurr0 + NumPicStCurr1 );
582  }
583  if ( m_eSliceType != B_SLICE )
584  {
585    m_aiNumRefIdx[REF_PIC_LIST_1] = 0;
586    ::memset( m_apcRefPicList[REF_PIC_LIST_1], 0, sizeof(m_apcRefPicList[REF_PIC_LIST_1]));
587  }
588  else
589  {
590    for (Int rIdx = 0; rIdx < m_aiNumRefIdx[REF_PIC_LIST_1]; rIdx ++)
591    {
592      cIdx = m_RefPicListModification.getRefPicListModificationFlagL1() ? m_RefPicListModification.getRefPicSetIdxL1(rIdx) : rIdx % numPicTotalCurr;
593      assert(cIdx >= 0 && cIdx < numPicTotalCurr);
594      m_apcRefPicList[REF_PIC_LIST_1][rIdx] = rpsCurrList1[ cIdx ];
595      m_bIsUsedAsLongTerm[REF_PIC_LIST_1][rIdx] = ( cIdx >= NumPicStCurr0 + NumPicStCurr1 );
596    }
597  }
598}
599#else
600Void TComSlice::getTempRefPicLists( TComList<TComPic*>& rcListPic, std::vector<TComPic*>& refPicSetInterLayer0, std::vector<TComPic*>& refPicSetInterLayer1,                                     
601                                   std::vector<TComPic*> rpsCurrList[2], std::vector<Bool> usedAsLongTerm[2], Int& numPocTotalCurr, Bool checkNumPocTotalCurr )
602{
603  if (!checkNumPocTotalCurr)
604  {
605    if (m_eSliceType == I_SLICE)
606    {     
607      return;
608    }   
609  }
610
611  TComPic*  pcRefPic= NULL;
612  TComPic*  RefPicSetStCurr0[16];
613  TComPic*  RefPicSetStCurr1[16];
614  TComPic*  RefPicSetLtCurr[16];
615  UInt NumPocStCurr0 = 0;
616  UInt NumPocStCurr1 = 0;
617  UInt NumPocLtCurr = 0;
618  Int i;
619#if NH_3D
620  m_pocsInCurrRPSs.clear();
621#endif
622  for(i=0; i < m_pRPS->getNumberOfNegativePictures(); i++)
623  {
624    if(m_pRPS->getUsed(i))
625    {
626      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pRPS->getDeltaPOC(i));
627      pcRefPic->setIsLongTerm(0);
628      pcRefPic->getPicYuvRec()->extendPicBorder();
629      RefPicSetStCurr0[NumPocStCurr0] = pcRefPic;
630      NumPocStCurr0++;
631      pcRefPic->setCheckLTMSBPresent(false); 
632#if NH_3D
633      m_pocsInCurrRPSs.push_back( pcRefPic->getPOC() ); 
634#endif
635    }
636  }
637 
638  for(; i < m_pRPS->getNumberOfNegativePictures()+m_pRPS->getNumberOfPositivePictures(); i++)
639  {
640    if(m_pRPS->getUsed(i))
641    {
642      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pRPS->getDeltaPOC(i));
643      pcRefPic->setIsLongTerm(0);
644      pcRefPic->getPicYuvRec()->extendPicBorder();
645      RefPicSetStCurr1[NumPocStCurr1] = pcRefPic;
646      NumPocStCurr1++;
647      pcRefPic->setCheckLTMSBPresent(false); 
648#if NH_3D
649      m_pocsInCurrRPSs.push_back( pcRefPic->getPOC() ); 
650#endif
651    }
652  }
653 
654  for(i = m_pRPS->getNumberOfNegativePictures()+m_pRPS->getNumberOfPositivePictures()+m_pRPS->getNumberOfLongtermPictures()-1; i > m_pRPS->getNumberOfNegativePictures()+m_pRPS->getNumberOfPositivePictures()-1 ; i--)
655  {
656    if(m_pRPS->getUsed(i))
657    {
658      pcRefPic = xGetLongTermRefPic(rcListPic, m_pRPS->getPOC(i), m_pRPS->getCheckLTMSBPresent(i));
659      pcRefPic->setIsLongTerm(1);
660      pcRefPic->getPicYuvRec()->extendPicBorder();
661      RefPicSetLtCurr[NumPocLtCurr] = pcRefPic;
662      NumPocLtCurr++;
663#if NH_3D
664      m_pocsInCurrRPSs.push_back( pcRefPic->getPOC() ); 
665#endif
666    }
667    if(pcRefPic==NULL) 
668    {
669      pcRefPic = xGetLongTermRefPic(rcListPic, m_pRPS->getPOC(i), m_pRPS->getCheckLTMSBPresent(i));
670    }
671    pcRefPic->setCheckLTMSBPresent(m_pRPS->getCheckLTMSBPresent(i)); 
672  }
673
674  Int numPocInterCurr = NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr; 
675#if NH_3D
676  assert( numPocInterCurr == (Int) m_pocsInCurrRPSs.size() ); 
677#endif
678  numPocTotalCurr = numPocInterCurr + getNumActiveRefLayerPics( );
679  assert( numPocTotalCurr == getNumRpsCurrTempList() );
680
681  if (checkNumPocTotalCurr)
682  {
683    // 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:
684    // - If nuh_layer_id is equal to 0 and the current picture is a BLA picture or a CRA picture, the value of NumPocTotalCurr shall be equal to 0.
685    // - Otherwise, when the current picture contains a P or B slice, the value of NumPocTotalCurr shall not be equal to 0.
686    if ( getRapPicFlag() && m_layerId == 0 )
687    {
688      assert(numPocTotalCurr == 0);
689    }
690
691    if (m_eSliceType == I_SLICE)
692    {
693      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
694      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
695     
696      return;
697    }
698   
699    assert(numPocTotalCurr > 0);
700   
701    m_aiNumRefIdx[0] = getNumRefIdx(REF_PIC_LIST_0);
702    m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
703  }
704
705  std::vector<TComPic*>* refPicSetInterLayer[2] = { &refPicSetInterLayer0, &refPicSetInterLayer1}; 
706  Int numPocInterLayer[2] = { getNumActiveRefLayerPics0( ), getNumActiveRefLayerPics1( ) }; 
707 
708  TComPic**             refPicSetStCurr    [2] = { RefPicSetStCurr0, RefPicSetStCurr1 };
709  Int numPocStCurr[2] = { (Int)NumPocStCurr0, (Int)NumPocStCurr1 }; 
710
711  for (Int li = 0; li < ((m_eSliceType==B_SLICE) ? 2 : 1); li++)
712  { 
713    rpsCurrList   [li].resize(MAX_NUM_REF+1,NULL ); 
714    usedAsLongTerm[li].resize(MAX_NUM_REF+1,false); 
715
716    Int cIdx = 0;
717    for ( i=0; i < numPocStCurr[li]; i++, cIdx++)
718    {
719      rpsCurrList[li][cIdx] = refPicSetStCurr[li][i];
720      usedAsLongTerm [li][cIdx] = false; 
721    }
722
723    for ( i=0; i < numPocInterLayer[li];  i++, cIdx++)
724    {   
725      rpsCurrList[li][cIdx] = (*refPicSetInterLayer[li])[i];
726      usedAsLongTerm [li][cIdx] = true; 
727    }
728
729    for ( i=0; i < numPocStCurr[1-li]; i++, cIdx++)
730    {
731      rpsCurrList[li][cIdx] = refPicSetStCurr[1-li][i];
732      usedAsLongTerm [li][cIdx] = false; 
733    }
734
735    for ( i=0; i<NumPocLtCurr;  i++, cIdx++)
736    {
737      rpsCurrList[li][cIdx] = RefPicSetLtCurr[i];
738      usedAsLongTerm [li][cIdx] = true; 
739    }
740
741    for ( i=0; i < numPocInterLayer[1-li];  i++, cIdx++)
742    {   
743      assert( cIdx < MAX_NUM_REF );   
744      rpsCurrList[li][cIdx] = (*refPicSetInterLayer[1-li])[i];
745      usedAsLongTerm [li][cIdx] = true; 
746    }
747
748    assert(cIdx == numPocTotalCurr);
749  }
750}
751
752Void TComSlice::setRefPicList( std::vector<TComPic*> rpsCurrList[2], std::vector<Bool> usedAsLongTerm[2], Int numPocTotalCurr, Bool checkNumPocTotalCurr )
753
754{
755  if (!checkNumPocTotalCurr)
756  {
757    if (m_eSliceType == I_SLICE)
758    {
759      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
760      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
761
762      return;
763    }   
764  }
765
766  ::memset(m_bIsUsedAsLongTerm, 0, sizeof(m_bIsUsedAsLongTerm));
767
768  for (Int li = 0; li < 2; li++)
769  {
770    if ( m_eSliceType == P_SLICE && li == 1 )
771    {
772      m_aiNumRefIdx[1] = 0;
773      ::memset( m_apcRefPicList[1], 0, sizeof(m_apcRefPicList[1]));
774    } 
775    else
776    {
777      for (Int rIdx = 0; rIdx <= (m_aiNumRefIdx[ li ] - 1 ); rIdx ++)
778      { 
779        Bool listModified             =                m_RefPicListModification.getRefPicListModificationFlagL( li ); 
780        Int orgIdx                    = listModified ? m_RefPicListModification.getRefPicSetIdxL(li, rIdx) : (rIdx % numPocTotalCurr); 
781
782        assert( rpsCurrList[li][ orgIdx ] != NULL ); 
783        assert( rpsCurrList[li][ orgIdx ]->getSlice(0)->getDiscardableFlag() == 0 );    // Inter-layer RPS shall not contain picture with discardable_flag = 1.
784        m_apcRefPicList    [li][rIdx] = rpsCurrList    [li][ orgIdx ];
785        m_bIsUsedAsLongTerm[li][rIdx] = usedAsLongTerm [li][ orgIdx ] ; 
786      }
787    }
788  }
789}
790#endif
791
792
793Int TComSlice::getNumRpsCurrTempList() const
794{
795  Int numRpsCurrTempList = 0;
796
797  if (m_eSliceType == I_SLICE)
798  {
799    return 0;
800  }
801  for(UInt i=0; i < m_pRPS->getNumberOfNegativePictures()+ m_pRPS->getNumberOfPositivePictures() + m_pRPS->getNumberOfLongtermPictures(); i++)
802  {
803    if(m_pRPS->getUsed(i))
804    {
805      numRpsCurrTempList++;
806    }
807  }
808#if NH_MV
809    numRpsCurrTempList = numRpsCurrTempList + getNumActiveRefLayerPics();
810#endif
811  return numRpsCurrTempList;
812}
813
814Void TComSlice::initEqualRef()
815{
816  for (Int iDir = 0; iDir < NUM_REF_PIC_LIST_01; iDir++)
817  {
818    for (Int iRefIdx1 = 0; iRefIdx1 < MAX_NUM_REF; iRefIdx1++)
819    {
820      for (Int iRefIdx2 = iRefIdx1; iRefIdx2 < MAX_NUM_REF; iRefIdx2++)
821      {
822        m_abEqualRef[iDir][iRefIdx1][iRefIdx2] = m_abEqualRef[iDir][iRefIdx2][iRefIdx1] = (iRefIdx1 == iRefIdx2? true : false);
823      }
824    }
825  }
826}
827#if NH_3D
828Void TComSlice::generateAlterRefforTMVP()
829{
830  for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
831  {       
832    if ( this->getNumRefIdx( RefPicList( uiRefListIdx ) ) == 0)
833    {
834        continue;
835    }
836    Bool bZeroIdxLtFlag = this->getRefPic(RefPicList(uiRefListIdx), 0)->getIsLongTerm();
837    for(Int i = 1; i < this->getNumRefIdx(RefPicList(uiRefListIdx)); i++ )
838    {
839      if ( ( bZeroIdxLtFlag && !this->getRefPic(RefPicList(uiRefListIdx), i)->getIsLongTerm() ) ||
840           (!bZeroIdxLtFlag &&  this->getRefPic(RefPicList(uiRefListIdx), i)->getIsLongTerm() ) )
841      {
842        this->setAlterRefIdx(RefPicList(uiRefListIdx),i);
843        break;
844      }
845    }
846  }
847}
848#endif
849
850#if NH_3D
851Void TComSlice::setCamparaSlice( Int** aaiScale, Int** aaiOffset )
852{ 
853  Int voiInVps      = m_pcVPS->getVoiInVps(getViewIndex() ); 
854  if( m_pcVPS->getNumCp( voiInVps ) > 0 )
855  {   
856    if( m_pcVPS->getCpInSliceSegmentHeaderFlag( voiInVps ) )
857    {
858      for( Int m = 0; m < m_pcVPS->getNumCp( voiInVps ); m++ )
859      {     
860        Int j      = m_pcVPS->getCpRefVoi( voiInVps, m );
861        Int jInVps = m_pcVPS->getVoiInVps( j ); 
862
863        setCpScale   ( jInVps , aaiScale [ jInVps   ][ voiInVps ]);
864        setCpInvScale( jInVps , aaiScale [ voiInVps ][ jInVps   ]);
865        setCpOff     ( jInVps , aaiOffset[ jInVps   ][ voiInVps ]);
866        setCpInvOff  ( jInVps , aaiOffset[ voiInVps ][ jInVps   ]);
867      }
868    }
869  } 
870}
871#endif
872
873Void TComSlice::checkColRefIdx(UInt curSliceIdx, TComPic* pic)
874{
875  Int i;
876  TComSlice* curSlice = pic->getSlice(curSliceIdx);
877  Int currColRefPOC =  curSlice->getRefPOC( RefPicList(1 - curSlice->getColFromL0Flag()), curSlice->getColRefIdx());
878  TComSlice* preSlice;
879  Int preColRefPOC;
880  for(i=curSliceIdx-1; i>=0; i--)
881  {
882    preSlice = pic->getSlice(i);
883    if(preSlice->getSliceType() != I_SLICE)
884    {
885      preColRefPOC  = preSlice->getRefPOC( RefPicList(1 - preSlice->getColFromL0Flag()), preSlice->getColRefIdx());
886      if(currColRefPOC != preColRefPOC)
887      {
888        printf("Collocated_ref_idx shall always be the same for all slices of a coded picture!\n");
889        exit(EXIT_FAILURE);
890      }
891      else
892      {
893        break;
894      }
895    }
896  }
897}
898
899Void TComSlice::checkCRA(const TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, NalUnitType& associatedIRAPType, TComList<TComPic *>& rcListPic)
900{
901  for(Int i = 0; i < pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i++)
902  {
903    if(pocCRA < MAX_UINT && getPOC() > pocCRA)
904    {
905      assert(getPOC()+pReferencePictureSet->getDeltaPOC(i) >= pocCRA);
906    }
907  }
908  for(Int i = pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i < pReferencePictureSet->getNumberOfPictures(); i++)
909  {
910    if(pocCRA < MAX_UINT && getPOC() > pocCRA)
911    {
912      if (!pReferencePictureSet->getCheckLTMSBPresent(i))
913      {
914        assert(xGetLongTermRefPic(rcListPic, pReferencePictureSet->getPOC(i), false)->getPOC() >= pocCRA);
915      }
916      else
917      {
918        assert(pReferencePictureSet->getPOC(i) >= pocCRA);
919      }
920    }
921  }
922  if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP ) // IDR picture found
923  {
924    pocCRA = getPOC();
925    associatedIRAPType = getNalUnitType();
926  }
927  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
928  {
929    pocCRA = getPOC();
930    associatedIRAPType = getNalUnitType();
931  }
932  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
933         || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
934         || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP ) // BLA picture found
935  {
936    pocCRA = getPOC();
937    associatedIRAPType = getNalUnitType();
938  }
939}
940
941/** Function for marking the reference pictures when an IDR/CRA/CRANT/BLA/BLANT is encountered.
942 * \param pocCRA POC of the CRA/CRANT/BLA/BLANT picture
943 * \param bRefreshPending flag indicating if a deferred decoding refresh is pending
944 * \param rcListPic reference to the reference picture list
945 * This function marks the reference pictures as "unused for reference" in the following conditions.
946 * If the nal_unit_type is IDR/BLA/BLANT, all pictures in the reference picture list
947 * are marked as "unused for reference"
948 *    If the nal_unit_type is BLA/BLANT, set the pocCRA to the temporal reference of the current picture.
949 * Otherwise
950 *    If the bRefreshPending flag is true (a deferred decoding refresh is pending) and the current
951 *    temporal reference is greater than the temporal reference of the latest CRA/CRANT/BLA/BLANT picture (pocCRA),
952 *    mark all reference pictures except the latest CRA/CRANT/BLA/BLANT picture as "unused for reference" and set
953 *    the bRefreshPending flag to false.
954 *    If the nal_unit_type is CRA/CRANT, set the bRefreshPending flag to true and pocCRA to the temporal
955 *    reference of the current picture.
956 * Note that the current picture is already placed in the reference list and its marking is not changed.
957 * If the current picture has a nal_ref_idc that is not 0, it will remain marked as "used for reference".
958 */
959Void TComSlice::decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic, const bool bEfficientFieldIRAPEnabled)
960{
961  TComPic* rpcPic;
962  Int      pocCurr = getPOC();
963
964  if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
965    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
966    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
967    || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
968    || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )  // IDR or BLA picture
969  {
970    // mark all pictures as not used for reference
971    TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
972    while (iterPic != rcListPic.end())
973    {
974      rpcPic = *(iterPic);
975      rpcPic->setCurrSliceIdx(0);
976      if (rpcPic->getPOC() != pocCurr)
977      {
978        rpcPic->getSlice(0)->setReferenced(false);
979      }
980      iterPic++;
981    }
982    if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
983      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
984      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
985    {
986      pocCRA = pocCurr;
987    }
988    if (bEfficientFieldIRAPEnabled)
989    {
990    bRefreshPending = true;
991    }
992  }
993  else // CRA or No DR
994  {
995    if(bEfficientFieldIRAPEnabled && (getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_IDR_N_LP || getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL))
996    {
997      if (bRefreshPending==true && pocCurr > m_iLastIDR) // IDR reference marking pending
998      {
999        TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
1000        while (iterPic != rcListPic.end())
1001        {
1002          rpcPic = *(iterPic);
1003          if (rpcPic->getPOC() != pocCurr && rpcPic->getPOC() != m_iLastIDR)
1004          {
1005            rpcPic->getSlice(0)->setReferenced(false);
1006          }
1007          iterPic++;
1008        }
1009        bRefreshPending = false; 
1010      }
1011    }
1012    else
1013    {
1014      if (bRefreshPending==true && pocCurr > pocCRA) // CRA reference marking pending
1015      {
1016        TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1017        while (iterPic != rcListPic.end())
1018        {
1019          rpcPic = *(iterPic);
1020          if (rpcPic->getPOC() != pocCurr && rpcPic->getPOC() != pocCRA)
1021          {
1022            rpcPic->getSlice(0)->setReferenced(false);
1023          }
1024          iterPic++;
1025        }
1026        bRefreshPending = false;
1027      }
1028    }
1029    if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
1030    {
1031      bRefreshPending = true;
1032      pocCRA = pocCurr;
1033    }
1034  }
1035}
1036
1037Void TComSlice::copySliceInfo(TComSlice *pSrc)
1038{
1039  assert( pSrc != NULL );
1040
1041  Int i, j, k;
1042
1043  m_iPOC                 = pSrc->m_iPOC;
1044  m_eNalUnitType         = pSrc->m_eNalUnitType;
1045#if NH_MV
1046  m_layerId              = pSrc->m_layerId;
1047  // GT: Copying of several other values might be be missing here, or is above not necessary?
1048#endif
1049  m_eSliceType           = pSrc->m_eSliceType;
1050  m_iSliceQp             = pSrc->m_iSliceQp;
1051#if ADAPTIVE_QP_SELECTION
1052  m_iSliceQpBase         = pSrc->m_iSliceQpBase;
1053#endif
1054  m_ChromaQpAdjEnabled = pSrc->m_ChromaQpAdjEnabled;
1055  m_deblockingFilterDisable   = pSrc->m_deblockingFilterDisable;
1056  m_deblockingFilterOverrideFlag = pSrc->m_deblockingFilterOverrideFlag;
1057  m_deblockingFilterBetaOffsetDiv2 = pSrc->m_deblockingFilterBetaOffsetDiv2;
1058  m_deblockingFilterTcOffsetDiv2 = pSrc->m_deblockingFilterTcOffsetDiv2;
1059
1060  for (i = 0; i < NUM_REF_PIC_LIST_01; i++)
1061  {
1062    m_aiNumRefIdx[i]     = pSrc->m_aiNumRefIdx[i];
1063  }
1064
1065  for (i = 0; i < MAX_NUM_REF; i++)
1066  {
1067    m_list1IdxToList0Idx[i] = pSrc->m_list1IdxToList0Idx[i];
1068  }
1069
1070  m_bCheckLDC             = pSrc->m_bCheckLDC;
1071  m_iSliceQpDelta        = pSrc->m_iSliceQpDelta;
1072  for (UInt component = 0; component < MAX_NUM_COMPONENT; component++)
1073  {
1074    m_iSliceChromaQpDelta[component] = pSrc->m_iSliceChromaQpDelta[component];
1075  }
1076  for (i = 0; i < NUM_REF_PIC_LIST_01; i++)
1077  {
1078    for (j = 0; j < MAX_NUM_REF; j++)
1079    {
1080      m_apcRefPicList[i][j]  = pSrc->m_apcRefPicList[i][j];
1081      m_aiRefPOCList[i][j]   = pSrc->m_aiRefPOCList[i][j];
1082      m_bIsUsedAsLongTerm[i][j] = pSrc->m_bIsUsedAsLongTerm[i][j];
1083#if NH_MV
1084      m_aiRefLayerIdList[i][j] = pSrc->m_aiRefLayerIdList[i][j];
1085#endif
1086    }
1087    m_bIsUsedAsLongTerm[i][MAX_NUM_REF] = pSrc->m_bIsUsedAsLongTerm[i][MAX_NUM_REF];
1088  }
1089  m_iDepth               = pSrc->m_iDepth;
1090
1091  // referenced slice
1092  m_bRefenced            = pSrc->m_bRefenced;
1093
1094  // access channel
1095#if NH_MV
1096  m_pcVPS                = pSrc->m_pcVPS;
1097#endif
1098  m_pRPS                = pSrc->m_pRPS;
1099  m_iLastIDR             = pSrc->m_iLastIDR;
1100
1101  m_pcPic                = pSrc->m_pcPic;
1102
1103  m_colFromL0Flag        = pSrc->m_colFromL0Flag;
1104  m_colRefIdx            = pSrc->m_colRefIdx;
1105
1106  setLambdas(pSrc->getLambdas());
1107
1108  for (i = 0; i < NUM_REF_PIC_LIST_01; i++)
1109  {
1110    for (j = 0; j < MAX_NUM_REF; j++)
1111    {
1112      for (k =0; k < MAX_NUM_REF; k++)
1113      {
1114        m_abEqualRef[i][j][k] = pSrc->m_abEqualRef[i][j][k];
1115      }
1116    }
1117  }
1118
1119  m_uiTLayer                      = pSrc->m_uiTLayer;
1120  m_bTLayerSwitchingFlag          = pSrc->m_bTLayerSwitchingFlag;
1121
1122  m_sliceMode                     = pSrc->m_sliceMode;
1123  m_sliceArgument                 = pSrc->m_sliceArgument;
1124  m_sliceCurStartCtuTsAddr        = pSrc->m_sliceCurStartCtuTsAddr;
1125  m_sliceCurEndCtuTsAddr          = pSrc->m_sliceCurEndCtuTsAddr;
1126  m_sliceIdx                      = pSrc->m_sliceIdx;
1127  m_sliceSegmentMode              = pSrc->m_sliceSegmentMode;
1128  m_sliceSegmentArgument          = pSrc->m_sliceSegmentArgument;
1129  m_sliceSegmentCurStartCtuTsAddr = pSrc->m_sliceSegmentCurStartCtuTsAddr;
1130  m_sliceSegmentCurEndCtuTsAddr   = pSrc->m_sliceSegmentCurEndCtuTsAddr;
1131  m_nextSlice                     = pSrc->m_nextSlice;
1132  m_nextSliceSegment              = pSrc->m_nextSliceSegment;
1133
1134  for ( UInt e=0 ; e<NUM_REF_PIC_LIST_01 ; e++ )
1135  {
1136    for ( UInt n=0 ; n<MAX_NUM_REF ; n++ )
1137    {
1138      memcpy(m_weightPredTable[e][n], pSrc->m_weightPredTable[e][n], sizeof(WPScalingParam)*MAX_NUM_COMPONENT );
1139    }
1140  }
1141
1142  for( UInt ch = 0 ; ch < MAX_NUM_CHANNEL_TYPE; ch++)
1143  {
1144    m_saoEnabledFlag[ch] = pSrc->m_saoEnabledFlag[ch];
1145  }
1146
1147  m_cabacInitFlag                 = pSrc->m_cabacInitFlag;
1148
1149  m_bLMvdL1Zero                   = pSrc->m_bLMvdL1Zero;
1150  m_LFCrossSliceBoundaryFlag      = pSrc->m_LFCrossSliceBoundaryFlag;
1151  m_enableTMVPFlag                = pSrc->m_enableTMVPFlag;
1152  m_maxNumMergeCand               = pSrc->m_maxNumMergeCand;
1153  m_encCABACTableIdx              = pSrc->m_encCABACTableIdx;
1154
1155#if NH_MV
1156  // Additional slice header syntax elements
1157  m_pocResetFlag               = pSrc->m_pocResetFlag; 
1158  m_discardableFlag            = pSrc->m_discardableFlag; 
1159  m_interLayerPredEnabledFlag  = pSrc->m_interLayerPredEnabledFlag; 
1160  m_numInterLayerRefPicsMinus1 = pSrc->m_numInterLayerRefPicsMinus1;
1161
1162  for (Int layer = 0; layer < MAX_NUM_LAYERS; layer++ )
1163  {
1164    m_interLayerPredLayerIdc[ layer ] = pSrc->m_interLayerPredLayerIdc[ layer ]; 
1165  }
1166#endif
1167#if NH_3D
1168  m_bApplyDIS = pSrc->m_bApplyDIS;
1169  m_bApplyIC = pSrc->m_bApplyIC;
1170  m_icSkipParseFlag = pSrc->m_icSkipParseFlag;
1171#endif
1172
1173}
1174
1175
1176/** Function for setting the slice's temporal layer ID and corresponding temporal_layer_switching_point_flag.
1177 * \param uiTLayer Temporal layer ID of the current slice
1178 * The decoder calls this function to set temporal_layer_switching_point_flag for each temporal layer based on
1179 * the SPS's temporal_id_nesting_flag and the parsed PPS.  Then, current slice's temporal layer ID and
1180 * temporal_layer_switching_point_flag is set accordingly.
1181 */
1182Void TComSlice::setTLayerInfo( UInt uiTLayer )
1183{
1184  m_uiTLayer = uiTLayer;
1185}
1186
1187/** Function for checking if this is a switching-point
1188*/
1189Bool TComSlice::isTemporalLayerSwitchingPoint(TComList<TComPic*>& rcListPic)
1190{
1191  TComPic* rpcPic;
1192  // loop through all pictures in the reference picture buffer
1193  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1194  while ( iterPic != rcListPic.end())
1195  {
1196    rpcPic = *(iterPic++);
1197    if(rpcPic->getSlice(0)->isReferenced() && rpcPic->getPOC() != getPOC())
1198    {
1199      if(rpcPic->getTLayer() >= getTLayer())
1200      {
1201        return false;
1202      }
1203    }
1204  }
1205  return true;
1206}
1207
1208/** Function for checking if this is a STSA candidate
1209 */
1210Bool TComSlice::isStepwiseTemporalLayerSwitchingPointCandidate(TComList<TComPic*>& rcListPic)
1211{
1212  TComPic* rpcPic;
1213
1214  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1215  while ( iterPic != rcListPic.end())
1216  {
1217    rpcPic = *(iterPic++);
1218    if(rpcPic->getSlice(0)->isReferenced() &&  (rpcPic->getUsedByCurr()==true) && rpcPic->getPOC() != getPOC())
1219    {
1220      if(rpcPic->getTLayer() >= getTLayer())
1221      {
1222        return false;
1223      }
1224    }
1225  }
1226  return true;
1227}
1228
1229
1230Void TComSlice::checkLeadingPictureRestrictions(TComList<TComPic*>& rcListPic)
1231{
1232  TComPic* rpcPic;
1233
1234  Int nalUnitType = this->getNalUnitType();
1235
1236  // When a picture is a leading picture, it shall be a RADL or RASL picture.
1237  if(this->getAssociatedIRAPPOC() > this->getPOC())
1238  {
1239    // Do not check IRAP pictures since they may get a POC lower than their associated IRAP
1240    if(nalUnitType < NAL_UNIT_CODED_SLICE_BLA_W_LP ||
1241       nalUnitType > NAL_UNIT_RESERVED_IRAP_VCL23)
1242    {
1243      assert(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1244             nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R ||
1245             nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
1246             nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R);
1247    }
1248  }
1249
1250  // When a picture is a trailing picture, it shall not be a RADL or RASL picture.
1251  if(this->getAssociatedIRAPPOC() < this->getPOC())
1252  {
1253    assert(nalUnitType != NAL_UNIT_CODED_SLICE_RASL_N &&
1254           nalUnitType != NAL_UNIT_CODED_SLICE_RASL_R &&
1255           nalUnitType != NAL_UNIT_CODED_SLICE_RADL_N &&
1256           nalUnitType != NAL_UNIT_CODED_SLICE_RADL_R);
1257  }
1258
1259  // No RASL pictures shall be present in the bitstream that are associated
1260  // with a BLA picture having nal_unit_type equal to BLA_W_RADL or BLA_N_LP.
1261  if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1262     nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
1263  {
1264    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_W_RADL &&
1265           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_N_LP);
1266  }
1267
1268  // No RASL pictures shall be present in the bitstream that are associated with
1269  // an IDR picture.
1270  if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1271     nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
1272  {
1273    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_N_LP   &&
1274           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_W_RADL);
1275  }
1276
1277  // No RADL pictures shall be present in the bitstream that are associated with
1278  // a BLA picture having nal_unit_type equal to BLA_N_LP or that are associated
1279  // with an IDR picture having nal_unit_type equal to IDR_N_LP.
1280  if(nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
1281     nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R)
1282  {
1283    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_N_LP   &&
1284           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_N_LP);
1285  }
1286
1287  // loop through all pictures in the reference picture buffer
1288  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1289  while ( iterPic != rcListPic.end())
1290  {
1291    rpcPic = *(iterPic++);
1292    if(!rpcPic->getReconMark())
1293    {
1294      continue;
1295    }
1296    if (rpcPic->getPOC() == this->getPOC())
1297    {
1298      continue;
1299    }
1300
1301    // Any picture that has PicOutputFlag equal to 1 that precedes an IRAP picture
1302    // in decoding order shall precede the IRAP picture in output order.
1303    // (Note that any picture following in output order would be present in the DPB)
1304    if(rpcPic->getSlice(0)->getPicOutputFlag() == 1 && !this->getNoOutputPriorPicsFlag())
1305    {
1306      if(nalUnitType == NAL_UNIT_CODED_SLICE_BLA_N_LP    ||
1307         nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_LP    ||
1308         nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_RADL  ||
1309         nalUnitType == NAL_UNIT_CODED_SLICE_CRA         ||
1310         nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP    ||
1311         nalUnitType == NAL_UNIT_CODED_SLICE_IDR_W_RADL)
1312      {
1313        assert(rpcPic->getPOC() < this->getPOC());
1314      }
1315    }
1316
1317    // Any picture that has PicOutputFlag equal to 1 that precedes an IRAP picture
1318    // in decoding order shall precede any RADL picture associated with the IRAP
1319    // picture in output order.
1320    if(rpcPic->getSlice(0)->getPicOutputFlag() == 1)
1321    {
1322      if((nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
1323          nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R))
1324      {
1325        // rpcPic precedes the IRAP in decoding order
1326        if(this->getAssociatedIRAPPOC() > rpcPic->getSlice(0)->getAssociatedIRAPPOC())
1327        {
1328          // rpcPic must not be the IRAP picture
1329          if(this->getAssociatedIRAPPOC() != rpcPic->getPOC())
1330          {
1331            assert(rpcPic->getPOC() < this->getPOC());
1332          }
1333        }
1334      }
1335    }
1336
1337    // When a picture is a leading picture, it shall precede, in decoding order,
1338    // all trailing pictures that are associated with the same IRAP picture.
1339      if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1340         nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R ||
1341         nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
1342         nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R)
1343      {
1344        if(rpcPic->getSlice(0)->getAssociatedIRAPPOC() == this->getAssociatedIRAPPOC())
1345        {
1346          // rpcPic is a picture that preceded the leading in decoding order since it exist in the DPB
1347          // rpcPic would violate the constraint if it was a trailing picture
1348          assert(rpcPic->getPOC() <= this->getAssociatedIRAPPOC());
1349        }
1350      }
1351
1352    // Any RASL picture associated with a CRA or BLA picture shall precede any
1353    // RADL picture associated with the CRA or BLA picture in output order
1354    if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1355       nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
1356    {
1357      if((this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_N_LP   ||
1358          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_W_LP   ||
1359          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL ||
1360          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_CRA)       &&
1361          this->getAssociatedIRAPPOC() == rpcPic->getSlice(0)->getAssociatedIRAPPOC())
1362      {
1363        if(rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N ||
1364           rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_R)
1365        {
1366          assert(rpcPic->getPOC() > this->getPOC());
1367        }
1368      }
1369    }
1370
1371    // Any RASL picture associated with a CRA picture shall follow, in output
1372    // order, any IRAP picture that precedes the CRA picture in decoding order.
1373    if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1374       nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
1375    {
1376      if(this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_CRA)
1377      {
1378        if(rpcPic->getSlice(0)->getPOC() < this->getAssociatedIRAPPOC() &&
1379           (rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP   ||
1380            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP   ||
1381            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL ||
1382            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP   ||
1383            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL ||
1384            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA))
1385        {
1386          assert(this->getPOC() > rpcPic->getSlice(0)->getPOC());
1387        }
1388      }
1389    }
1390  }
1391}
1392
1393
1394
1395/** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
1396*/
1397Void TComSlice::applyReferencePictureSet( TComList<TComPic*>& rcListPic, const TComReferencePictureSet *pReferencePictureSet)
1398{
1399  TComPic* rpcPic;
1400  Int i, isReference;
1401
1402  checkLeadingPictureRestrictions(rcListPic);
1403
1404  // loop through all pictures in the reference picture buffer
1405  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1406  while ( iterPic != rcListPic.end())
1407  {
1408    rpcPic = *(iterPic++);
1409
1410    if(!rpcPic->getSlice( 0 )->isReferenced())
1411    {
1412      continue;
1413    }
1414
1415    isReference = 0;
1416    // loop through all pictures in the Reference Picture Set
1417    // to see if the picture should be kept as reference picture
1418    for(i=0;i<pReferencePictureSet->getNumberOfPositivePictures()+pReferencePictureSet->getNumberOfNegativePictures();i++)
1419    {
1420      if(!rpcPic->getIsLongTerm() && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i))
1421      {
1422        isReference = 1;
1423        rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
1424        rpcPic->setIsLongTerm(0);
1425      }
1426    }
1427    for(;i<pReferencePictureSet->getNumberOfPictures();i++)
1428    {
1429      if(pReferencePictureSet->getCheckLTMSBPresent(i)==true)
1430      {
1431        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()) == pReferencePictureSet->getPOC(i))
1432        {
1433          isReference = 1;
1434          rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
1435        }
1436      }
1437      else
1438      {
1439        Int pocCycle = 1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
1440        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC() & (pocCycle-1);
1441        Int refPoc = pReferencePictureSet->getPOC(i) & (pocCycle-1);
1442        if(rpcPic->getIsLongTerm() && curPoc == refPoc)
1443        {
1444          isReference = 1;
1445          rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
1446        }
1447      }
1448
1449    }
1450#if NH_MV
1451    if( isReference ) // Current picture is in the temporal RPS
1452    {
1453      assert( rpcPic->getSlice(0)->getDiscardableFlag() == 0 ); // Temporal RPS shall not contain picture with discardable_flag equal to 1
1454    }
1455#endif
1456    // mark the picture as "unused for reference" if it is not in
1457    // the Reference Picture Set
1458    if(rpcPic->getPicSym()->getSlice(0)->getPOC() != this->getPOC() && isReference == 0)
1459    {
1460      rpcPic->getSlice( 0 )->setReferenced( false );
1461      rpcPic->setUsedByCurr(0);
1462      rpcPic->setIsLongTerm(0);
1463    }
1464    //check that pictures of higher temporal layers are not used
1465    assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getUsedByCurr()==0||rpcPic->getTLayer()<=this->getTLayer());
1466    //check that pictures of higher or equal temporal layer are not in the RPS if the current picture is a TSA picture
1467    if(this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R || this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N)
1468    {
1469      assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getTLayer()<this->getTLayer());
1470    }
1471    //check that pictures marked as temporal layer non-reference pictures are not used for reference
1472    if(rpcPic->getPicSym()->getSlice(0)->getPOC() != this->getPOC() && rpcPic->getTLayer()==this->getTLayer())
1473    {
1474      assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getUsedByCurr()==0||rpcPic->getSlice( 0 )->getTemporalLayerNonReferenceFlag()==false);
1475    }
1476  }
1477}
1478
1479/** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
1480*/
1481Int TComSlice::checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, const TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess, Bool bUseRecoveryPoint)
1482{
1483  Int atLeastOneUnabledByRecoveryPoint = 0;
1484  Int atLeastOneFlushedByPreviousIDR = 0;
1485  TComPic* rpcPic;
1486  Int i, isAvailable;
1487  Int atLeastOneLost = 0;
1488  Int atLeastOneRemoved = 0;
1489  Int iPocLost = 0;
1490
1491  // loop through all long-term pictures in the Reference Picture Set
1492  // to see if the picture should be kept as reference picture
1493  for(i=pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures();i<pReferencePictureSet->getNumberOfPictures();i++)
1494  {
1495    isAvailable = 0;
1496    // loop through all pictures in the reference picture buffer
1497    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1498    while ( iterPic != rcListPic.end())
1499    {
1500      rpcPic = *(iterPic++);
1501      if(pReferencePictureSet->getCheckLTMSBPresent(i)==true)
1502      {
1503        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()) == pReferencePictureSet->getPOC(i) && rpcPic->getSlice(0)->isReferenced())
1504        {
1505          if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
1506          {
1507            isAvailable = 0;
1508          }
1509          else
1510          {
1511            isAvailable = 1;
1512          }
1513        }
1514      }
1515      else
1516      {
1517        Int pocCycle = 1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
1518        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC() & (pocCycle-1);
1519        Int refPoc = pReferencePictureSet->getPOC(i) & (pocCycle-1);
1520        if(rpcPic->getIsLongTerm() && curPoc == refPoc && rpcPic->getSlice(0)->isReferenced())
1521        {
1522          if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
1523          {
1524            isAvailable = 0;
1525          }
1526          else
1527          {
1528            isAvailable = 1;
1529          }
1530        }
1531      }
1532    }
1533    // if there was no such long-term check the short terms
1534    if(!isAvailable)
1535    {
1536      iterPic = rcListPic.begin();
1537      while ( iterPic != rcListPic.end())
1538      {
1539        rpcPic = *(iterPic++);
1540
1541        Int pocCycle = 1 << rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
1542        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC();
1543        Int refPoc = pReferencePictureSet->getPOC(i);
1544        if (!pReferencePictureSet->getCheckLTMSBPresent(i))
1545        {
1546          curPoc = curPoc & (pocCycle - 1);
1547          refPoc = refPoc & (pocCycle - 1);
1548        }
1549
1550        if (rpcPic->getSlice(0)->isReferenced() && curPoc == refPoc)
1551        {
1552          if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
1553          {
1554            isAvailable = 0;
1555          }
1556          else
1557          {
1558            isAvailable = 1;
1559            rpcPic->setIsLongTerm(1);
1560            break;
1561          }
1562        }
1563      }
1564    }
1565    // report that a picture is lost if it is in the Reference Picture Set
1566    // but not available as reference picture
1567    if(isAvailable == 0)
1568    {
1569      if (this->getPOC() + pReferencePictureSet->getDeltaPOC(i) >= pocRandomAccess)
1570      {
1571        if(!pReferencePictureSet->getUsed(i) )
1572        {
1573          if(printErrors)
1574          {
1575            printf("\nLong-term reference picture with POC = %3d seems to have been removed or not correctly decoded.", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
1576          }
1577          atLeastOneRemoved = 1;
1578        }
1579        else
1580        {
1581          if(printErrors)
1582          {
1583            printf("\nLong-term reference picture with POC = %3d is lost or not correctly decoded!", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
1584          }
1585          atLeastOneLost = 1;
1586          iPocLost=this->getPOC() + pReferencePictureSet->getDeltaPOC(i);
1587        }
1588      }
1589      else if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess)
1590      {
1591        atLeastOneUnabledByRecoveryPoint = 1;
1592      }
1593      else if(bUseRecoveryPoint && (this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_N_LP || this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_W_RADL))
1594      {
1595        atLeastOneFlushedByPreviousIDR = 1;
1596      }
1597    }
1598  }
1599  // loop through all short-term pictures in the Reference Picture Set
1600  // to see if the picture should be kept as reference picture
1601  for(i=0;i<pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures();i++)
1602  {
1603    isAvailable = 0;
1604    // loop through all pictures in the reference picture buffer
1605    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1606    while ( iterPic != rcListPic.end())
1607    {
1608      rpcPic = *(iterPic++);
1609
1610      if(!rpcPic->getIsLongTerm() && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i) && rpcPic->getSlice(0)->isReferenced())
1611      {
1612        if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
1613        {
1614          isAvailable = 0;
1615        }
1616        else
1617        {
1618          isAvailable = 1;
1619        }
1620      }
1621    }
1622    // report that a picture is lost if it is in the Reference Picture Set
1623    // but not available as reference picture
1624    if(isAvailable == 0)
1625    {
1626      if (this->getPOC() + pReferencePictureSet->getDeltaPOC(i) >= pocRandomAccess)
1627      {
1628        if(!pReferencePictureSet->getUsed(i) )
1629        {
1630          if(printErrors)
1631          {
1632            printf("\nShort-term reference picture with POC = %3d seems to have been removed or not correctly decoded.", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
1633          }
1634          atLeastOneRemoved = 1;
1635        }
1636        else
1637        {
1638          if(printErrors)
1639          {
1640            printf("\nShort-term reference picture with POC = %3d is lost or not correctly decoded!", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
1641          }
1642          atLeastOneLost = 1;
1643          iPocLost=this->getPOC() + pReferencePictureSet->getDeltaPOC(i);
1644        }
1645      }
1646      else if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess)
1647      {
1648        atLeastOneUnabledByRecoveryPoint = 1;
1649      }
1650      else if(bUseRecoveryPoint && (this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_N_LP || this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_W_RADL))
1651      {
1652        atLeastOneFlushedByPreviousIDR = 1;
1653      }
1654    }
1655  }
1656
1657  if(atLeastOneUnabledByRecoveryPoint || atLeastOneFlushedByPreviousIDR)
1658  {
1659    return -1;
1660  }   
1661  if(atLeastOneLost)
1662  {
1663    return iPocLost+1;
1664  }
1665  if(atLeastOneRemoved)
1666  {
1667    return -2;
1668  }
1669  else
1670  {
1671    return 0;
1672  }
1673}
1674
1675/** Function for constructing an explicit Reference Picture Set out of the available pictures in a referenced Reference Picture Set
1676*/
1677Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, const TComReferencePictureSet *pReferencePictureSet, Bool isRAP, Int pocRandomAccess, Bool bUseRecoveryPoint, const Bool bEfficientFieldIRAPEnabled)
1678{
1679  TComPic* rpcPic;
1680  Int i, j;
1681  Int k = 0;
1682  Int nrOfNegativePictures = 0;
1683  Int nrOfPositivePictures = 0;
1684  TComReferencePictureSet* pLocalRPS = this->getLocalRPS();
1685  (*pLocalRPS)=TComReferencePictureSet();
1686
1687  Bool irapIsInRPS = false; // Used when bEfficientFieldIRAPEnabled==true
1688
1689  // loop through all pictures in the Reference Picture Set
1690  for(i=0;i<pReferencePictureSet->getNumberOfPictures();i++)
1691  {
1692    j = 0;
1693    // loop through all pictures in the reference picture buffer
1694    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1695    while ( iterPic != rcListPic.end())
1696    {
1697      j++;
1698      rpcPic = *(iterPic++);
1699
1700      if(rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i) && rpcPic->getSlice(0)->isReferenced())
1701      {
1702        // This picture exists as a reference picture
1703        // and should be added to the explicit Reference Picture Set
1704        pLocalRPS->setDeltaPOC(k, pReferencePictureSet->getDeltaPOC(i));
1705        pLocalRPS->setUsed(k, pReferencePictureSet->getUsed(i) && (!isRAP));
1706        if (bEfficientFieldIRAPEnabled)
1707        {
1708          pLocalRPS->setUsed(k, pLocalRPS->getUsed(k) && !(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess) );
1709        }
1710
1711        if(pLocalRPS->getDeltaPOC(k) < 0)
1712        {
1713          nrOfNegativePictures++;
1714        }
1715        else
1716        {
1717          if(bEfficientFieldIRAPEnabled && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getAssociatedIRAPPOC() && this->getAssociatedIRAPPOC() == this->getPOC()+1)
1718          {
1719            irapIsInRPS = true;
1720          }
1721          nrOfPositivePictures++;
1722        }
1723        k++;
1724      }
1725    }
1726  }
1727
1728  Bool useNewRPS = false;
1729  // if current picture is complimentary field associated to IRAP, add the IRAP to its RPS.
1730  if(bEfficientFieldIRAPEnabled && m_pcPic->isField() && !irapIsInRPS)
1731  {
1732    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1733    while ( iterPic != rcListPic.end())
1734    {
1735      rpcPic = *(iterPic++);
1736      if(rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getAssociatedIRAPPOC() && this->getAssociatedIRAPPOC() == this->getPOC()+1)
1737      {
1738        pLocalRPS->setDeltaPOC(k, 1);
1739        pLocalRPS->setUsed(k, true);
1740        nrOfPositivePictures++;
1741        k ++;
1742        useNewRPS = true;
1743      }
1744    }
1745  }
1746  pLocalRPS->setNumberOfNegativePictures(nrOfNegativePictures);
1747  pLocalRPS->setNumberOfPositivePictures(nrOfPositivePictures);
1748  pLocalRPS->setNumberOfPictures(nrOfNegativePictures+nrOfPositivePictures);
1749  // This is a simplistic inter rps example. A smarter encoder will look for a better reference RPS to do the
1750  // inter RPS prediction with.  Here we just use the reference used by pReferencePictureSet.
1751  // If pReferencePictureSet is not inter_RPS_predicted, then inter_RPS_prediction is for the current RPS also disabled.
1752  if (!pReferencePictureSet->getInterRPSPrediction() || useNewRPS )
1753  {
1754    pLocalRPS->setInterRPSPrediction(false);
1755    pLocalRPS->setNumRefIdc(0);
1756  }
1757  else
1758  {
1759    Int rIdx =  this->getRPSidx() - pReferencePictureSet->getDeltaRIdxMinus1() - 1;
1760    Int deltaRPS = pReferencePictureSet->getDeltaRPS();
1761    const TComReferencePictureSet* pcRefRPS = this->getSPS()->getRPSList()->getReferencePictureSet(rIdx);
1762    Int iRefPics = pcRefRPS->getNumberOfPictures();
1763    Int iNewIdc=0;
1764    for(i=0; i<= iRefPics; i++)
1765    {
1766      Int deltaPOC = ((i != iRefPics)? pcRefRPS->getDeltaPOC(i) : 0);  // check if the reference abs POC is >= 0
1767      Int iRefIdc = 0;
1768      for (j=0; j < pLocalRPS->getNumberOfPictures(); j++) // loop through the  pictures in the new RPS
1769      {
1770        if ( (deltaPOC + deltaRPS) == pLocalRPS->getDeltaPOC(j))
1771        {
1772          if (pLocalRPS->getUsed(j))
1773          {
1774            iRefIdc = 1;
1775          }
1776          else
1777          {
1778            iRefIdc = 2;
1779          }
1780        }
1781      }
1782      pLocalRPS->setRefIdc(i, iRefIdc);
1783      iNewIdc++;
1784    }
1785    pLocalRPS->setInterRPSPrediction(true);
1786    pLocalRPS->setNumRefIdc(iNewIdc);
1787    pLocalRPS->setDeltaRPS(deltaRPS);
1788    pLocalRPS->setDeltaRIdxMinus1(pReferencePictureSet->getDeltaRIdxMinus1() + this->getSPS()->getRPSList()->getNumberOfReferencePictureSets() - this->getRPSidx());
1789  }
1790
1791  this->setRPS(pLocalRPS);
1792  this->setRPSidx(-1);
1793}
1794
1795//! get AC and DC values for weighted pred
1796Void  TComSlice::getWpAcDcParam(WPACDCParam *&wp)
1797{
1798  wp = m_weightACDCParam;
1799}
1800
1801//! init AC and DC values for weighted pred
1802Void  TComSlice::initWpAcDcParam()
1803{
1804  for(Int iComp = 0; iComp < MAX_NUM_COMPONENT; iComp++ )
1805  {
1806    m_weightACDCParam[iComp].iAC = 0;
1807    m_weightACDCParam[iComp].iDC = 0;
1808  }
1809}
1810
1811//! get tables for weighted prediction
1812Void  TComSlice::getWpScaling( RefPicList e, Int iRefIdx, WPScalingParam *&wp )
1813{
1814  assert (e<NUM_REF_PIC_LIST_01);
1815  wp = m_weightPredTable[e][iRefIdx];
1816}
1817
1818//! reset Default WP tables settings : no weight.
1819Void  TComSlice::resetWpScaling()
1820{
1821  for ( Int e=0 ; e<NUM_REF_PIC_LIST_01 ; e++ )
1822  {
1823    for ( Int i=0 ; i<MAX_NUM_REF ; i++ )
1824    {
1825      for ( Int yuv=0 ; yuv<MAX_NUM_COMPONENT ; yuv++ )
1826      {
1827        WPScalingParam  *pwp = &(m_weightPredTable[e][i][yuv]);
1828        pwp->bPresentFlag      = false;
1829        pwp->uiLog2WeightDenom = 0;
1830        pwp->uiLog2WeightDenom = 0;
1831        pwp->iWeight           = 1;
1832        pwp->iOffset           = 0;
1833      }
1834    }
1835  }
1836}
1837
1838//! init WP table
1839Void  TComSlice::initWpScaling(const TComSPS *sps)
1840{
1841  const Bool bUseHighPrecisionPredictionWeighting = sps->getSpsRangeExtension().getHighPrecisionOffsetsEnabledFlag();
1842  for ( Int e=0 ; e<NUM_REF_PIC_LIST_01 ; e++ )
1843  {
1844    for ( Int i=0 ; i<MAX_NUM_REF ; i++ )
1845    {
1846      for ( Int yuv=0 ; yuv<MAX_NUM_COMPONENT ; yuv++ )
1847      {
1848        WPScalingParam  *pwp = &(m_weightPredTable[e][i][yuv]);
1849        if ( !pwp->bPresentFlag )
1850        {
1851          // Inferring values not present :
1852          pwp->iWeight = (1 << pwp->uiLog2WeightDenom);
1853          pwp->iOffset = 0;
1854        }
1855
1856        const Int offsetScalingFactor = bUseHighPrecisionPredictionWeighting ? 1 : (1 << (sps->getBitDepth(toChannelType(ComponentID(yuv)))-8));
1857
1858        pwp->w      = pwp->iWeight;
1859        pwp->o      = pwp->iOffset * offsetScalingFactor; //NOTE: This value of the ".o" variable is never used - .o is set immediately before it gets used
1860        pwp->shift  = pwp->uiLog2WeightDenom;
1861        pwp->round  = (pwp->uiLog2WeightDenom>=1) ? (1 << (pwp->uiLog2WeightDenom-1)) : (0);
1862      }
1863    }
1864  }
1865}
1866
1867// ------------------------------------------------------------------------------------------------
1868// Video parameter set (VPS)
1869// ------------------------------------------------------------------------------------------------
1870TComVPS::TComVPS()
1871: m_VPSId                     (  0)
1872, m_uiMaxTLayers              (  1)
1873#if NH_MV
1874, m_uiMaxLayersMinus1         (  0)
1875#else
1876, m_uiMaxLayers               (  1)
1877#endif
1878, m_bTemporalIdNestingFlag    (false)
1879, m_numHrdParameters          (  0)
1880#if NH_MV
1881, m_maxLayerId             (  0)
1882#else
1883, m_maxNuhReservedZeroLayerId (  0)
1884#endif
1885, m_hrdParameters             ()
1886, m_hrdOpSetIdx               ()
1887, m_cprmsPresentFlag          ()
1888{
1889#if NH_MV
1890  m_vpsBaseLayerInternalFlag = true; 
1891  m_vpsBaseLayerAvailableFlag = true; 
1892
1893  m_numViews = 0; 
1894
1895#endif
1896
1897  for( Int i = 0; i < MAX_TLAYER; i++)
1898  {
1899    m_numReorderPics[i] = 0;
1900    m_uiMaxDecPicBuffering[i] = 1;
1901    m_uiMaxLatencyIncrease[i] = 0;
1902  }
1903#if NH_MV
1904  for (Int lsIdx = 0; lsIdx < MAX_VPS_OP_SETS_PLUS1; lsIdx++ )
1905  { 
1906    for( Int layerId = 0; layerId < MAX_VPS_NUH_LAYER_ID_PLUS1; layerId++ )
1907    {
1908      m_layerIdIncludedFlag[lsIdx][layerId] = (( lsIdx == 0 ) && ( layerId == 0 )) ; 
1909    }
1910  } 
1911  m_vpsNumProfileTierLevelMinus1 = -1; 
1912   
1913  m_numAddLayerSets              = 0;   
1914  m_numAddOlss                   = 0; 
1915  m_defaultOutputLayerIdc     = 0; 
1916 
1917  for ( Int i = 0; i < MAX_VPS_OUTPUTLAYER_SETS; i++)
1918  {
1919    for ( Int j = 0; j < MAX_VPS_NUH_LAYER_ID_PLUS1; j++)
1920    {
1921      m_profileTierLevelIdx[i][j] = -1; 
1922      m_outputLayerFlag[i][j] = false; 
1923    }
1924    m_altOutputLayerFlag[ i ]       = false; 
1925  }
1926
1927  m_repFormatIdxPresentFlag = false; 
1928  m_maxOneActiveRefLayerFlag = false; 
1929  m_vpsPocLsbAlignedFlag  = false; 
1930  m_directDepTypeLenMinus2   = 0;         
1931 
1932
1933  m_vpsExtensionFlag = true; 
1934  m_vpsNonVuiExtensionLength = 0;
1935  m_splittingFlag    = false;
1936
1937 
1938  for( Int i = 0; i < MAX_NUM_SCALABILITY_TYPES; i++ )
1939  {
1940    m_scalabilityMaskFlag[i] = false;
1941    m_dimensionIdLen [i]  = -1; 
1942  }
1943
1944  m_vpsNuhLayerIdPresentFlag = false;
1945
1946  for( Int i = 0; i < MAX_VPS_OP_SETS_PLUS1; i++ )
1947  {
1948    m_vpsProfilePresentFlag   [i] = false;
1949    m_layerSetIdxForOlsMinus1       [i] = 0;
1950    for( Int j = 0; j < MAX_VPS_NUH_LAYER_ID_PLUS1; j++ )
1951    {
1952      m_outputLayerFlag[i][j] = false;
1953    }
1954  }
1955
1956  for( Int i = 0; i < MAX_NUM_LAYER_IDS; i++ )
1957  {
1958    m_layerIdInVps[i] =  (i == 0 ) ? 0 : -1;         
1959  }
1960
1961  for( Int i = 0; i < MAX_NUM_LAYERS; i++ )
1962  {
1963    m_layerIdInNuh        [i] = ( i == 0 ) ? 0 : -1; 
1964    m_numDirectRefLayers  [i] = 0; 
1965#if NH_3D
1966    m_numRefListLayers    [i] = 0; 
1967#endif
1968    m_vpsRepFormatIdx     [i] = 0; 
1969    m_pocLsbNotPresentFlag[i] = 0;   
1970    m_viewIdVal           [i] = 0; 
1971
1972#if NH_3D
1973    m_viewIndex           [i] = -1; 
1974#endif
1975
1976    for( Int j = 0; j < MAX_NUM_LAYERS; j++ )
1977    {
1978      m_directDependencyFlag[i][j] = false;
1979      m_directDependencyType[i][j] = -1; 
1980      m_dependencyFlag  [i][j]    = false; 
1981      m_idDirectRefLayer[i][j]    = -1; 
1982#if NH_3D
1983      m_idRefListLayer[i][j]    = -1; 
1984#endif
1985      m_idPredictedLayer[i][j]    = -1; 
1986      m_idRefLayer      [i][j]    = -1; 
1987      m_maxTidIlRefPicsPlus1[i][j]  = 7;
1988    }
1989
1990    for( Int j = 0; j < MAX_NUM_SCALABILITY_TYPES; j++ )
1991    {
1992      m_dimensionId[i][j] = 0;
1993    }
1994  } 
1995#endif
1996}
1997
1998TComVPS::~TComVPS()
1999{
2000}
2001
2002#if NH_MV
2003
2004Bool TComVPS::checkVPSExtensionSyntax()
2005{
2006  for( Int layer = 1; layer <= getMaxLayersMinus1(); layer++ )
2007  {
2008    // check layer_id_in_nuh constraint
2009    assert( getLayerIdInNuh( layer ) > getLayerIdInNuh( layer -1 ) );
2010  }
2011
2012  //The value of vps_num_rep_formats_minus1 shall be in the range of 0 to 255, inclusive.
2013  assert( getVpsNumRepFormatsMinus1() >= 0 ); 
2014  assert( getVpsNumRepFormatsMinus1() <= 255 ); 
2015
2016  // The value of num_add_layer_sets shall be in the range of 0 to 1023, inclusive.
2017  assert( getNumAddLayerSets() >= 0 && getNumAddLayerSets() <= 1023 ); 
2018  return true; 
2019}
2020
2021Int TComVPS::getNumScalabilityTypes() const
2022{
2023  return scalTypeToScalIdx( ScalabilityType(MAX_NUM_SCALABILITY_TYPES) );
2024}
2025
2026Int TComVPS::scalTypeToScalIdx( ScalabilityType scalType ) const
2027{
2028  assert( (Int)scalType >= 0 && (Int)scalType <= MAX_NUM_SCALABILITY_TYPES );
2029  assert( (Int)scalType == MAX_NUM_SCALABILITY_TYPES || getScalabilityMaskFlag( scalType ) );
2030  Int scalIdx = 0; 
2031  for( Int curScalType = 0; curScalType < scalType; curScalType++ )
2032  {
2033    scalIdx += ( getScalabilityMaskFlag( curScalType ) ? 1 : 0 );
2034
2035  }
2036
2037  return scalIdx; 
2038}
2039Void TComVPS::setScalabilityMaskFlag( UInt val )
2040{
2041  for ( Int scalType = 0; scalType < MAX_NUM_SCALABILITY_TYPES; scalType++ ) 
2042  {
2043    setScalabilityMaskFlag( scalType, ( val & (1 << scalType ) ) != 0 );
2044  }
2045}
2046
2047Void TComVPS::setRefLayers()
2048{
2049
2050  for( Int i = 0; i  <=  getMaxLayersMinus1(); i++ )
2051  {
2052    for( Int j = 0; j  <=  getMaxLayersMinus1(); j++ )
2053    {
2054      m_dependencyFlag[ i ][ j ] = getDirectDependencyFlag( i , j );
2055      for( Int k = 0; k < i; k++ )
2056      {
2057        if( getDirectDependencyFlag(i , k )  &&  m_dependencyFlag[k][j] )
2058        {
2059          m_dependencyFlag[ i ][ j ] = true;
2060        }
2061      }
2062    }
2063  }
2064
2065  for( Int i = 0; i  <=  getMaxLayersMinus1(); i++ )
2066  {
2067    Int iNuhLId = getLayerIdInNuh( i );
2068    Int d = 0;
2069#if NH_3D
2070    Int l = 0; 
2071#endif
2072    Int r = 0;
2073    Int p = 0;
2074
2075    for( Int j = 0; j  <=  getMaxLayersMinus1(); j++ )
2076    {
2077      Int jNuhLid = getLayerIdInNuh( j );
2078      if( getDirectDependencyFlag( i , j ) )
2079      {
2080        m_idDirectRefLayer[iNuhLId][d++] = jNuhLid;
2081      }
2082#if NH_3D
2083      if( getDirectDependencyFlag( i , j ) && ( getDepthId( iNuhLId ) == getDepthId( jNuhLid ) ))
2084      {
2085        m_idRefListLayer [iNuhLId][l++] = jNuhLid;
2086      }
2087#endif
2088
2089      if( getDependencyFlag( i , j ) )
2090      {
2091        m_idRefLayer      [iNuhLId][r++] = jNuhLid;
2092      }
2093      if( getDependencyFlag( j , i ) )
2094      {
2095        m_idPredictedLayer[iNuhLId][p++] = jNuhLid;
2096      }
2097    }
2098    m_numDirectRefLayers[ iNuhLId ] = d;
2099#if NH_3D
2100    m_numRefListLayers[ iNuhLId ] = l; 
2101#endif
2102
2103    m_numRefLayers      [ iNuhLId ] = r;
2104    m_numPredictedLayers[ iNuhLId ] = p;
2105  }
2106 
2107  Bool layerIdInListFlag[ 64 ]; 
2108  for( Int i = 0; i  <=  63; i++ )
2109  {
2110    layerIdInListFlag[ i ] = 0;
2111  }
2112
2113  Int k = 0; 
2114  for( Int i = 0; i  <=  getMaxLayersMinus1(); i++ )
2115  {
2116    Int iNuhLId = getLayerIdInNuh( i );
2117    if( getNumDirectRefLayers( iNuhLId )  ==  0 )
2118    {
2119      m_treePartitionLayerIdList[ k ][ 0 ] = iNuhLId;
2120      Int h = 1; 
2121      for( Int j = 0; j < getNumPredictedLayers( iNuhLId ); j++ ) 
2122      {
2123        Int predLId = getIdPredictedLayer( iNuhLId, j );
2124        if ( !layerIdInListFlag[ predLId ] )
2125        {
2126          m_treePartitionLayerIdList[ k ][ h++ ] = predLId;
2127          layerIdInListFlag[ predLId ] = 1; 
2128        }         
2129      }
2130      m_numLayersInTreePartition[ k++ ] = h;
2131    }
2132  }
2133  m_numIndependentLayers = k;
2134}
2135
2136
2137Void     TComVPS::initNumViews( )
2138{
2139  m_numViews = 1; 
2140#if NH_3D
2141  AOF( m_viewOIdxList.size() == 0 );   
2142  m_viewOIdxList.push_back( 0 );       
2143#endif
2144
2145  for( Int i = 0; i <=  getMaxLayersMinus1(); i++ )
2146  {
2147    Int lId = getLayerIdInNuh( i ); 
2148    if( i > 0 )
2149    {
2150      Bool newViewFlag = true; 
2151      for( Int j = 0; j < i; j++ )
2152      {
2153        if( getViewOrderIdx( lId )  ==  getViewOrderIdx( getLayerIdInNuh( j ) )  )
2154        {
2155          newViewFlag = false;
2156        }
2157      }
2158      if( newViewFlag )
2159      {
2160        m_numViews++;
2161#if NH_3D
2162        m_viewOIdxList.push_back( getViewOrderIdx( lId ) );       
2163#endif
2164      }
2165    }
2166  }
2167}
2168
2169
2170Int TComVPS::getScalabilityId( Int layerIdInVps, ScalabilityType scalType ) const
2171{
2172  return getScalabilityMaskFlag( scalType ) ? getDimensionId( layerIdInVps, scalTypeToScalIdx( scalType ) ) : 0;
2173}
2174
2175#if NH_3D_VSO || NH_3D
2176Int TComVPS::getLayerIdInNuh( Int viewIndex, Bool depthFlag, Int auxId ) const
2177{
2178  Int foundLayerIdinNuh = -1; 
2179
2180  for (Int layerIdInVps = 0 ; layerIdInVps <= getMaxLayersMinus1(); layerIdInVps++ )
2181  {
2182    Int layerIdInNuh = getLayerIdInNuh( layerIdInVps ); 
2183#if !NH_3D
2184    if( ( getViewIndex( layerIdInNuh ) == viewIndex ) && ( getAuxId( layerIdInNuh ) == ( depthFlag ? 2 : 0 ) )  )
2185#else
2186    if( ( getViewIndex( layerIdInNuh ) == viewIndex ) && ( getDepthId( layerIdInNuh ) == ( depthFlag ? 1 : 0 ) )  )
2187#endif
2188    {
2189      foundLayerIdinNuh = layerIdInNuh; 
2190      break; 
2191    }
2192  }
2193  return foundLayerIdinNuh;
2194}
2195#endif
2196#if NH_3D
2197Void TComVPS::createCamPars(Int iNumViews)
2198{
2199  m_numCp                     .resize( iNumViews );
2200  m_cpRefVoi                  .resize( iNumViews );
2201  m_cpInSliceSegmentHeaderFlag.resize( iNumViews );
2202  m_cpPresentFlag             .resize( iNumViews ); 
2203  m_aaaiCodedScale            .resize( iNumViews ); 
2204  m_aaaiCodedOffset           .resize( iNumViews ); 
2205
2206  for ( Int i = 0; i < iNumViews ; i++ )
2207  {
2208    m_numCp                     [i] = 0; 
2209    m_cpRefVoi                  [i].resize( iNumViews );
2210    m_cpInSliceSegmentHeaderFlag[i] = false;         
2211    m_aaaiCodedScale            [i].resize( 2 );
2212    m_aaaiCodedOffset           [i].resize( 2 );       
2213    m_cpPresentFlag             [i].resize( iNumViews ); 
2214
2215    for ( Int j = 0; j < iNumViews; j++)
2216    {
2217      m_cpRefVoi             [i][j] = 0; 
2218      m_cpPresentFlag        [i][j] = false; 
2219    }
2220
2221    for ( Int j = 0; j < 2; j++ )
2222    {
2223      m_aaaiCodedScale       [i][j].resize( MAX_NUM_LAYERS );
2224      m_aaaiCodedOffset      [i][j].resize( MAX_NUM_LAYERS );
2225
2226      for ( Int k = 0; k < MAX_NUM_LAYERS; k++ )
2227      {
2228        m_aaaiCodedScale [i][j][k] = 0;
2229        m_aaaiCodedOffset[i][j][k] = 0;
2230      }
2231    }
2232  }
2233}
2234#endif // NH_3D
2235
2236
2237Int TComVPS::xGetDimBitOffset( Int j ) const
2238{
2239  Int dimBitOffset = 0; 
2240  if ( getSplittingFlag() && j == getNumScalabilityTypes() )
2241  {
2242     dimBitOffset = 6; 
2243  }
2244  else
2245  {
2246    for (Int dimIdx = 0; dimIdx <= j-1; dimIdx++)
2247    {
2248      dimBitOffset += getDimensionIdLen( dimIdx ); 
2249    }
2250  }
2251  return dimBitOffset; 
2252}
2253
2254Int TComVPS::inferDimensionId( Int i, Int j ) const
2255{
2256    return ( ( getLayerIdInNuh( i ) & ( (1 << xGetDimBitOffset( j + 1 ) ) - 1) ) >> xGetDimBitOffset( j ) ); 
2257}
2258
2259Int TComVPS::inferLastDimsionIdLenMinus1() const
2260{
2261  return ( 5 - xGetDimBitOffset( getNumScalabilityTypes() - 1 ) ); 
2262}
2263
2264Int TComVPS::getNumLayersInIdList( Int lsIdx ) const
2265{
2266  assert( lsIdx >= 0 ); 
2267  assert( lsIdx <= getNumLayerSets() ); 
2268  return (Int) m_layerSetLayerIdList[ lsIdx ].size(); 
2269}
2270
2271Int    TComVPS::getNumOutputLayerSets() const
2272{
2273  return getNumAddOlss() + getNumLayerSets(); 
2274}
2275
2276
2277#if NH_3D
2278Bool TComVPS::isFirstDepthLayer(Int layerIdInNuh) const
2279{
2280  Bool firstDepthLayer = false;
2281  for(Int i = 0; i <= getMaxLayersMinus1(); i++  )
2282  {
2283    Int curLayerIdInNuh = getLayerIdInNuh( i );
2284    if ( getVpsDepthFlag( curLayerIdInNuh ) )
2285    {
2286      firstDepthLayer =  ( curLayerIdInNuh == layerIdInNuh);
2287      break;
2288    }
2289  }
2290  return firstDepthLayer;
2291}
2292#endif
2293
2294Void TComVPS::deriveLayerSetLayerIdList()
2295{
2296  m_layerSetLayerIdList.resize( getVpsNumLayerSetsMinus1() + 1 ); 
2297  for (Int i = 0; i <= getVpsNumLayerSetsMinus1(); i++ )
2298  {
2299    for( Int m = 0; m  <= getVpsMaxLayerId(); m++ )
2300    {
2301      if( getLayerIdIncludedFlag( i, m) ) 
2302      {
2303        m_layerSetLayerIdList[ i ].push_back( m );       
2304      }
2305    }
2306  }
2307}
2308
2309Void TComVPS::initTargetLayerIdLists()
2310{
2311  m_targetDecLayerIdLists.resize( getNumOutputLayerSets() ); 
2312  m_targetOptLayerIdLists.resize( getNumOutputLayerSets() ); 
2313}
2314
2315Void TComVPS::deriveTargetLayerIdList( Int i )
2316{ 
2317  Int lsIdx = olsIdxToLsIdx( i );     
2318
2319  for( Int j = 0; j < getNumLayersInIdList( lsIdx ); j++ )
2320  {
2321    if ( getNecessaryLayerFlag( i , j ))
2322    {
2323      m_targetDecLayerIdLists[i].push_back( m_layerSetLayerIdList[ lsIdx ][ j ] ); 
2324    }
2325
2326    if( getOutputLayerFlag( i, j  ))
2327    {
2328      m_targetOptLayerIdLists[i].push_back( m_layerSetLayerIdList[ lsIdx ][ j ] );
2329    }
2330  } 
2331  assert( getNumOutputLayersInOutputLayerSet( i ) > 0 ); 
2332}
2333
2334Bool TComVPS::inferOutputLayerFlag( Int i, Int j ) const
2335{
2336  Bool outputLayerFlag; 
2337  switch ( getDefaultOutputLayerIdc( ) )
2338  {
2339  case 0:
2340    outputLayerFlag = true; 
2341    break; 
2342  case 1:
2343    outputLayerFlag = ( j == m_layerSetLayerIdList[ olsIdxToLsIdx( i ) ].size() - 1 ); 
2344    break;
2345  case 2:
2346    if ( i == 0 && j == 0)
2347    {     
2348      outputLayerFlag = true;  // This is a software only fix for a bug in the spec. In spec outputLayerFlag is neither present nor inferred.
2349    }
2350    else
2351    {
2352      assert( 0 ); 
2353    }
2354    break; 
2355  default:     
2356    assert( 0 );
2357    break; 
2358  }
2359  return outputLayerFlag;
2360}
2361
2362Int TComVPS::getMaxSubLayersInLayerSetMinus1( Int i ) const
2363{
2364  Int maxSLMinus1 = 0; 
2365  for( Int k = 0; k < getNumLayersInIdList( i ); k++ )
2366  {
2367    Int lId = m_layerSetLayerIdList[i][k];
2368    maxSLMinus1 = std::max( maxSLMinus1, getSubLayersVpsMaxMinus1( getLayerIdInVps( lId ) ));
2369  }
2370  return maxSLMinus1;
2371}
2372
2373Bool TComVPS::getAltOutputLayerFlagVar( Int i ) const
2374{
2375  // Semantics variable not syntax element !
2376
2377  Bool altOptLayerFlag = false;     
2378  if ( i > 0 && getNumOutputLayersInOutputLayerSet( i ) == 1 && 
2379    getNumDirectRefLayers( getOlsHighestOutputLayerId( i ) ) > 0 )
2380  {
2381    altOptLayerFlag = getAltOutputLayerFlag( i ); 
2382  }
2383  return altOptLayerFlag;
2384}
2385
2386
2387
2388Int TComVPS::inferProfileTierLevelIdx(Int i, Int j) const
2389{
2390  Bool inferZero        = ( i == 0 && j == 0 &&  getVpsBaseLayerInternalFlag() );
2391  Bool inferGreaterZero = getNecessaryLayerFlag(i,j) && ( getVpsNumProfileTierLevelMinus1() == 0 ); 
2392  assert( inferZero || inferGreaterZero );
2393
2394  Bool ptlIdx = 0; // inference for greaterZero
2395  if ( inferZero )
2396  {
2397    ptlIdx = getMaxLayersMinus1() > 0 ? 1 : 0; 
2398    if ( inferGreaterZero )
2399    {
2400      assert( ptlIdx == 0 ); 
2401      // This should never happen since :
2402      // When vps_max_layers_minus1 is greater than 0, the value of vps_num_profile_tier_level_minus1 shall be greater than or equal to 1.
2403    }
2404  }
2405  return ptlIdx;
2406}
2407
2408Void TComVPS::deriveAddLayerSetLayerIdList(Int i)
2409{
2410  assert( m_layerSetLayerIdList.size() ==  ( getVpsNumLayerSetsMinus1() + 1 + i ) ); 
2411  std::vector<Int> layerSetLayerIdList;
2412
2413  for( Int treeIdx = 1; treeIdx < getNumIndependentLayers(); treeIdx++ )
2414  { 
2415    // The value of highest_layer_idx_plus1[ i ][ j ] shall be in the range of 0 to NumLayersInTreePartition[ j ], inclusive.
2416    assert( getHighestLayerIdxPlus1( i, treeIdx ) >= 0 && getHighestLayerIdxPlus1( i, treeIdx ) <= getNumLayersInTreePartition( treeIdx ) );
2417
2418    for( Int layerCnt = 0; layerCnt < getHighestLayerIdxPlus1( i, treeIdx ); layerCnt++ )
2419    {
2420      layerSetLayerIdList.push_back( getTreePartitionLayerIdList( treeIdx, layerCnt ) );
2421    }
2422  }
2423  m_layerSetLayerIdList.push_back( layerSetLayerIdList ); 
2424
2425  //It is a requirement of bitstream conformance that
2426  //NumLayersInIdList[ vps_num_layer_sets_minus1 + 1 + i ] shall be greater than 0.
2427  assert( getNumLayersInIdList( getVpsNumLayerSetsMinus1() + 1 + i ) > 0 );
2428}
2429
2430
2431Void TComVPS::deriveNecessaryLayerFlags(Int olsIdx)
2432{
2433  AOF( olsIdx >= 0 && olsIdx < getNumOutputLayerSets() ); 
2434  Int lsIdx = olsIdxToLsIdx( olsIdx );
2435  for( Int lsLayerIdx = 0; lsLayerIdx < getNumLayersInIdList( lsIdx) ; lsLayerIdx++ )
2436  {
2437    m_necessaryLayerFlag[ olsIdx ][ lsLayerIdx ] = 0;
2438  }
2439  for( Int lsLayerIdx = 0; lsLayerIdx < getNumLayersInIdList( lsIdx ); lsLayerIdx++ )
2440  {
2441    if( getOutputLayerFlag( olsIdx, lsLayerIdx  ))
2442    {
2443      m_necessaryLayerFlag[ olsIdx ][ lsLayerIdx ] = 1;
2444      Int currLayerId = getLayerSetLayerIdList( lsIdx, lsLayerIdx );
2445      for( Int rLsLayerIdx = 0; rLsLayerIdx < lsLayerIdx; rLsLayerIdx++ )
2446      {
2447        Int refLayerId = getLayerSetLayerIdList( lsIdx, rLsLayerIdx );
2448        if( getDependencyFlag( getLayerIdInVps( currLayerId ), getLayerIdInVps( refLayerId ) ) )
2449        {
2450          m_necessaryLayerFlag[ olsIdx ][ rLsLayerIdx ] = 1;
2451        }
2452      }
2453    }
2454  }
2455  m_numNecessaryLayers[ olsIdx ] = 0;
2456  for( Int lsLayerIdx = 0; lsLayerIdx < getNumLayersInIdList( lsIdx ); lsLayerIdx++ ) 
2457  {
2458    m_numNecessaryLayers[ olsIdx ]  +=  m_necessaryLayerFlag[ olsIdx ][ lsLayerIdx ];
2459  }
2460}
2461
2462Void TComVPS::printPTL() const
2463{
2464  std::vector<Int> idx; 
2465  std::vector<Int> num; 
2466  IntAry2d ptlInfo; 
2467
2468  std::cout << std::right << std::setw(60) << std::setfill('-') << " " << std::setfill(' ') << std::endl << "PTLI" << std::endl; 
2469
2470  for ( Int i = 0; i <= getVpsNumProfileTierLevelMinus1(); i++ )
2471  {
2472    std::vector<Int> curPtlInfo;
2473    const ProfileTierLevel* ptl = getPTL( i )->getGeneralPTL(); 
2474    curPtlInfo.push_back( (Int) ptl->getProfileIdc()  );
2475    curPtlInfo.push_back( (Int) ptl->getTierFlag()    );
2476    curPtlInfo.push_back( (Int) ptl->getLevelIdc()    );
2477    curPtlInfo.push_back( (Int) ptl->getInbldFlag()   );
2478
2479    idx.push_back ( i );
2480    num.push_back ( 4 ); 
2481    ptlInfo.push_back( curPtlInfo );
2482  } 
2483
2484  xPrintArray( "VpsProfileTierLevel", getVpsNumProfileTierLevelMinus1() + 1, idx, num, ptlInfo, false  ); 
2485
2486  num.clear(); 
2487  idx.clear(); 
2488  for (Int i = 0; i < getNumOutputLayerSets(); i++)
2489  {
2490    num.push_back ( getNumLayersInIdList( olsIdxToLsIdx( i ))  ); 
2491    idx.push_back( i ); 
2492  }
2493
2494  xPrintArray( "profile_tier_level_idx", getNumOutputLayerSets(), idx, num, m_profileTierLevelIdx, true );
2495  std::cout << std::endl;
2496}
2497
2498
2499Void TComVPS::printRepFormat() const
2500{
2501
2502  vector<Int> idc;
2503  vector<Int> width;
2504  vector<Int> height; 
2505  vector<Int> chromaAndBitDepthPresent;
2506  vector<Int> chormaFormat;   
2507  vector<Int> bitDepthLuma; 
2508  vector<Int> bitDepthChroma;
2509  vector<Int> conformanceWindowPresent; 
2510  vector<Int> confLeftOff;
2511  vector<Int> confRightOff;
2512  vector<Int> confTopOff;
2513  vector<Int> confBottomOff;
2514
2515  for (Int i = 0; i <= getVpsNumRepFormatsMinus1(); i++ )
2516  {
2517    const TComRepFormat* repFormat = getRepFormat( i );
2518
2519    idc                             .push_back(        i             );
2520    width                           .push_back(  repFormat->getPicWidthVpsInLumaSamples()  );
2521    height                          .push_back(  repFormat->getPicHeightVpsInLumaSamples() );
2522    chromaAndBitDepthPresent        .push_back(  repFormat->getChromaAndBitDepthVpsPresentFlag() ? 1 : 0    );
2523    chormaFormat                    .push_back(  repFormat->getChromaFormatVpsIdc()        );
2524    bitDepthLuma                    .push_back(  repFormat->getBitDepthVpsLumaMinus8()     );
2525    bitDepthChroma                  .push_back(  repFormat->getBitDepthVpsChromaMinus8()   );
2526    conformanceWindowPresent        .push_back(  repFormat->getConformanceWindowVpsFlag()  );
2527    confLeftOff                     .push_back(  repFormat->getConfWinVpsLeftOffset()      );
2528    confRightOff                    .push_back(  repFormat->getConfWinVpsRightOffset()     );
2529    confTopOff                      .push_back(  repFormat->getConfWinVpsTopOffset()       );
2530    confBottomOff                   .push_back(  repFormat->getConfWinVpsBottomOffset()    );
2531  }
2532
2533  std::cout << std::right << std::setw(60) << std::setfill('-') << " " << std::setfill(' ') << std::endl << "Rep Format" << std::endl; 
2534 
2535  std::vector<Int> repFormatIdx;
2536
2537  for (Int i = 0; i <= getMaxLayersMinus1(); i++ )
2538  {
2539    repFormatIdx.push_back( getVpsRepFormatIdx(i ) );
2540  }
2541
2542  xPrintArray( "rep_format_idx", getMaxLayersMinus1()+1, repFormatIdx, false  );
2543
2544  std::cout << std::endl;
2545
2546  xPrintArray( "i"                                      , getVpsNumRepFormatsMinus1()+1, idc                                    , false, 6 );
2547  xPrintArray( "pic_width_vps_in_luma_samples"          , getVpsNumRepFormatsMinus1()+1, width                                  , false, 6 );
2548  xPrintArray( "pic_height_vps_in_luma_samples"         , getVpsNumRepFormatsMinus1()+1, height                                 , false, 6 );       
2549  xPrintArray( "chroma_and_bit_depth_vps_present_flag"  , getVpsNumRepFormatsMinus1()+1, chromaAndBitDepthPresent               , false, 6 );     
2550  xPrintArray( "chroma_format_vps_idc"                  , getVpsNumRepFormatsMinus1()+1, chormaFormat                           , false, 6 );     
2551  xPrintArray( "bit_depth_vps_luma_minus8"              , getVpsNumRepFormatsMinus1()+1, bitDepthLuma                           , false, 6 );     
2552  xPrintArray( "bit_depth_vps_chroma_minus8"            , getVpsNumRepFormatsMinus1()+1, bitDepthChroma                         , false, 6 );     
2553  xPrintArray( "conformance_window_vps_flag"            , getVpsNumRepFormatsMinus1()+1, conformanceWindowPresent               , false, 6 );     
2554  xPrintArray( "conf_win_vps_left_offset"               , getVpsNumRepFormatsMinus1()+1, confLeftOff                            , false, 6 );     
2555  xPrintArray( "conf_win_vps_right_offset"              , getVpsNumRepFormatsMinus1()+1, confRightOff                           , false, 6 );     
2556  xPrintArray( "conf_win_vps_top_offset"                , getVpsNumRepFormatsMinus1()+1, confTopOff                             , false, 6 );     
2557  xPrintArray( "conf_win_vps_bottom_offset"             , getVpsNumRepFormatsMinus1()+1, confBottomOff                          , false, 6 );     
2558
2559  std::cout << std::endl;
2560}
2561
2562
2563Void TComVPS::printLayerDependencies() const
2564{
2565  vector<Int> fullArray;
2566  vector<Int> range; 
2567
2568#if NH_3D
2569  vector<Int> depthId; 
2570#endif
2571
2572  vector<Int> viewOrderIndex;
2573  vector<Int> auxId;
2574  vector<Int> dependencyId; 
2575  vector<Int> viewId; 
2576  for (Int i = 0; i <= getMaxLayersMinus1(); i++ )
2577  {
2578    fullArray.push_back( getMaxLayersMinus1() + 1 ); 
2579    range.push_back( i ); 
2580    viewOrderIndex.push_back( getViewIndex   ( i ) );
2581    dependencyId  .push_back( getDependencyId( i ) );
2582    auxId         .push_back( getAuxId       ( i ) );     
2583    viewId        .push_back( getViewId      ( getLayerIdInNuh( i ) ) );
2584#if NH_3D 
2585    depthId.push_back( getDepthId( i ) );
2586#endif
2587  }
2588  std::cout << std::right << std::setw(60) << std::setfill('-') << " " << std::setfill(' ') << std::endl << "Layer Dependencies" << std::endl; 
2589  xPrintArray( "direct_dependency_flag", getMaxLayersMinus1()+1, range, fullArray, m_directDependencyFlag, false ); 
2590  xPrintArray( "DependencyFlag", getMaxLayersMinus1()+1, range, fullArray, m_dependencyFlag, false ); 
2591  xPrintArray( "layer_id_in_nuh", getMaxLayersMinus1()+1, m_layerIdInNuh, true  );     
2592  xPrintArray( "IdPredictedLayer", getMaxLayersMinus1() + 1, m_layerIdInNuh, m_numPredictedLayers, m_idPredictedLayer, true );
2593  xPrintArray( "IdRefLayer"      , getMaxLayersMinus1() + 1, m_layerIdInNuh, m_numRefLayers, m_idRefLayer, true );
2594  xPrintArray( "IdDirectRefLayer", getMaxLayersMinus1() + 1, m_layerIdInNuh, m_numDirectRefLayers, m_idDirectRefLayer, true );
2595#if NH_3D
2596  xPrintArray( "IdRefListLayer", getMaxLayersMinus1() + 1, m_layerIdInNuh, m_numRefListLayers, m_idRefListLayer, true );
2597#endif
2598
2599  std::cout << std::endl;
2600}
2601
2602Void TComVPS::printScalabilityId() const
2603{
2604  vector<Int> layerIdxInVps; 
2605
2606
2607  vector<Int> depthId; 
2608  vector<Int> viewOrderIndex;
2609  vector<Int> auxId;
2610  vector<Int> dependencyId; 
2611  vector<Int> viewId; 
2612
2613  for (Int i = 0; i <= getMaxLayersMinus1(); i++ )
2614  {
2615    Int layerIdInNuh = getLayerIdInNuh( i );
2616    layerIdxInVps  .push_back( i ); 
2617    depthId       .push_back( getDepthId     ( layerIdInNuh ) );
2618    viewOrderIndex.push_back( getViewIndex   ( layerIdInNuh ) );
2619    dependencyId  .push_back( getDependencyId( layerIdInNuh ) );
2620    auxId         .push_back( getAuxId       ( layerIdInNuh ) );     
2621    viewId        .push_back( getViewId      ( layerIdInNuh ) );
2622
2623  }
2624
2625  std::cout << std::right << std::setw(60) << std::setfill('-') << " " << std::setfill(' ') << std::endl << "Scalability Ids" << std::endl; 
2626  xPrintArray( "layerIdxInVps"  , getMaxLayersMinus1()+1, layerIdxInVps,          false );
2627  xPrintArray( "layer_id_in_nuh", getMaxLayersMinus1()+1, m_layerIdInNuh, false );     
2628
2629  xPrintArray( "DepthLayerFlag", getMaxLayersMinus1()+1, depthId       , false );     
2630  xPrintArray( "ViewOrderIdx"  , getMaxLayersMinus1()+1, viewOrderIndex, false );     
2631  xPrintArray( "DependencyId"  , getMaxLayersMinus1()+1, dependencyId  , false );     
2632  xPrintArray( "AuxId"         , getMaxLayersMinus1()+1, auxId         , false );     
2633  xPrintArray( "ViewIdVal"     , getMaxLayersMinus1()+1, viewId        , false );     
2634
2635  std::cout << std::endl;
2636}
2637
2638Void TComVPS::printLayerSets() const
2639{
2640  vector<Int> fullArray;
2641  vector<Int> numLayersInIdList; 
2642  vector<Int> rangeLayerSets; 
2643
2644
2645  for (Int i = 0; i < getNumLayerSets(); i++ )
2646  {
2647    numLayersInIdList.push_back( getNumLayersInIdList( i ) );       
2648    rangeLayerSets.push_back( i ); 
2649  }
2650
2651  vector<Int> rangeOutputLayerSets; 
2652  vector<Int> numOutputLayersInOutputLayerSet; 
2653  vector<Int> numDecLayer; 
2654  vector<Int> numLayersInLayerSetForOutputLayerSet; 
2655  vector<Int> vOlsIdxToLsIdx;
2656  for (Int i = 0; i < getNumOutputLayerSets(); i++ )
2657  {
2658    vOlsIdxToLsIdx.push_back( olsIdxToLsIdx(i));
2659    numOutputLayersInOutputLayerSet.push_back( getNumOutputLayersInOutputLayerSet( i ) );       
2660    numDecLayer.push_back( (Int) m_targetDecLayerIdLists[ i ].size() );
2661    rangeOutputLayerSets.push_back( i ); 
2662    numLayersInLayerSetForOutputLayerSet.push_back( getNumLayersInIdList( olsIdxToLsIdx( i ) ) );
2663  }
2664
2665  vector<Int> rangeIndependentLayers;
2666  for(Int i = 0; i < getNumIndependentLayers(); i++ )
2667  {
2668    rangeIndependentLayers.push_back( i );   
2669  }
2670
2671  vector<Int> rangeAddLayerSets;
2672  vector<Int> numHighestLayerIdxPlus1; 
2673  for(Int i = 0; i < getNumAddLayerSets(); i++ )
2674  {
2675    rangeAddLayerSets.push_back( i );   
2676    numHighestLayerIdxPlus1.push_back( getNumIndependentLayers() );
2677  }
2678
2679  std::cout << std::right << std::setw(60) << std::setfill('-') << " " << std::setfill(' ') << std::endl << "Layer Sets" << std::endl;     
2680  xPrintArray( "TreePartitionLayerIdList", getNumIndependentLayers(), rangeIndependentLayers, m_numLayersInTreePartition, m_treePartitionLayerIdList, true );
2681  xPrintArray( "highest_layer_idx_plus1", getNumAddLayerSets(), rangeAddLayerSets, numHighestLayerIdxPlus1, m_highestLayerIdxPlus1, true ); 
2682  xPrintArray( "LayerSetLayerIdList" , (Int) getNumLayerSets()      , rangeLayerSets      , numLayersInIdList, m_layerSetLayerIdList, true );
2683  xPrintArray( "OlsIdxToLsIdx", (Int) vOlsIdxToLsIdx.size(), vOlsIdxToLsIdx, true ); 
2684  xPrintArray( "OutputLayerFlag"     , getNumOutputLayerSets(), rangeOutputLayerSets, numLayersInLayerSetForOutputLayerSet, m_outputLayerFlag, true );
2685  xPrintArray( "TargetOptLayerIdList", getNumOutputLayerSets(), rangeOutputLayerSets, numOutputLayersInOutputLayerSet, m_targetOptLayerIdLists, true );
2686  xPrintArray( "NecessaryLayerFlag"  , getNumOutputLayerSets(), rangeOutputLayerSets, numLayersInLayerSetForOutputLayerSet, m_necessaryLayerFlag   , true );
2687  xPrintArray( "TargetDecLayerIdList", getNumOutputLayerSets(), rangeOutputLayerSets, numDecLayer,                     m_targetDecLayerIdLists, true );
2688  std::cout << endl;
2689}
2690
2691IntAry1d TComVPS::getLayersOfVpsPtl(Int idxOfVpsPtl) const
2692{
2693  std::set<Int> applicableLayerIdsInVps;
2694  // Get max chroma format and max bit depth of layers to which ptl is applicable to.
2695
2696  if ( idxOfVpsPtl == 0 || idxOfVpsPtl == 1 )
2697  {
2698    // If the profile_tier_level( ) syntax structure is included in an active SPS for the base layer or is the profile_tier_level( ) syntax structure
2699    // VpsProfileTierLevel[ 0 ], it applies to the OLS containing all layers in the bitstream but with only the base layer being the output layer.
2700
2701    // the value of profile_tier_level_idx[ 0 ][ 0 ] is inferred to be equal to 1, such that
2702    // VpsProfileTierLevel[ 1 ] applies to the 0-th OLS, which contains only the base layer that is the only output layer.
2703
2704    // Consider only the base layer
2705    applicableLayerIdsInVps.insert( 0 );
2706  }
2707  else
2708  {
2709    // Otherwise, the profile_tier_level( ) syntax structure provides profile, tier and level to which a layer in an OLS conforms
2710    // and the profile_tier_level_idx[ i ][ j ] syntax element specifies that the profile_tier_level( ) syntax structure
2711    // VpsProfileTierLevel[ profile_tier_level_idx[ i ][ j ] ] applies to the j-th layer of the i-th OLS.
2712
2713    for (Int j = 0; j < getNumOutputLayerSets(); j++ )
2714    {
2715      for (Int k = 0; k < getNumOutputLayersInOutputLayerSet( j );  k++)
2716      {
2717        if ( getProfileTierLevelIdx(j,k)  == idxOfVpsPtl )
2718        {
2719          applicableLayerIdsInVps.insert( getLayerIdInVps( getTargetOptLayerIdList( j )[ k ]  ) );
2720        }
2721      }
2722    }
2723  }
2724
2725  IntAry1d layers;
2726  for(std::set<Int>::iterator it = applicableLayerIdsInVps.begin(); it != applicableLayerIdsInVps.end(); ++it  )
2727  {
2728    layers.push_back( *it ); 
2729  }
2730  return layers;
2731}
2732
2733#if NH_3D
2734Void TComVPS::initViewCompLayer()
2735{
2736  assert( m_viewCompLayerId.size() == 0 && m_viewCompLayerPresentFlag.size() == 0  );
2737  for( Int i = 0; i < getNumViews(); i++ )
2738  {
2739    m_viewCompLayerId         .push_back( std::vector<Int>(0)  );
2740    m_viewCompLayerPresentFlag.push_back( std::vector<Bool>(0) );     
2741
2742    for( Int depFlag = 0; depFlag  <=  1; depFlag++ )
2743    {
2744      Int iViewOIdx = getViewOIdxList( i );
2745      Int layerId = -1;
2746      for( Int j = 0; j  <=  getMaxLayersMinus1(); j++ ) 
2747      {
2748        Int jNuhLId = getLayerIdInNuh( j );
2749        if( getVpsDepthFlag( jNuhLId ) == ( (Bool) depFlag )  &&  getViewOrderIdx( jNuhLId )  ==  iViewOIdx 
2750          &&  getDependencyId( jNuhLId )  ==  0  &&  getAuxId( jNuhLId )  ==  0 )
2751        {
2752          layerId = jNuhLId;
2753        }
2754      }
2755      m_viewCompLayerPresentFlag[ i ].push_back( layerId  !=  -1 );
2756      m_viewCompLayerId         [ i ].push_back( layerId );       
2757    }
2758  }
2759}
2760
2761Int TComVPS::getVoiInVps(Int viewOIdx) const
2762{
2763  for ( Int i = 0; i < m_viewOIdxList.size(); i++ )
2764  {
2765    if  ( m_viewOIdxList[ i ] == viewOIdx )
2766    {
2767      return i; 
2768    }
2769  }
2770  assert( 0 );   
2771  return -1;
2772}
2773
2774Void TComVPS::deriveCpPresentFlag()
2775{
2776  for( Int nInVps = 0; nInVps < getNumViews(); nInVps++  )
2777  {
2778    for( Int mInVps = 0; mInVps < getNumViews(); mInVps++ )
2779    {
2780      m_cpPresentFlag[nInVps][mInVps] = 0; 
2781    }
2782  }
2783
2784  for( Int n = 1; n < getNumViews(); n++ )
2785  {
2786    Int iInVps = getVoiInVps(  getViewOIdxList( n ) );     
2787    for( Int m = 0; m < getNumCp( iInVps ); m++ )
2788    {
2789      m_cpPresentFlag[ iInVps ][ getVoiInVps( getCpRefVoi( iInVps, m ) ) ] = 1;
2790    }
2791  }
2792}
2793
2794#endif
2795#endif // NH_MV
2796
2797// ------------------------------------------------------------------------------------------------
2798// Sequence parameter set (SPS)
2799// ------------------------------------------------------------------------------------------------
2800
2801TComSPSRExt::TComSPSRExt()
2802 : m_transformSkipRotationEnabledFlag   (false)
2803 , m_transformSkipContextEnabledFlag    (false)
2804// m_rdpcmEnabledFlag initialized below
2805 , m_extendedPrecisionProcessingFlag    (false)
2806 , m_intraSmoothingDisabledFlag         (false)
2807 , m_highPrecisionOffsetsEnabledFlag    (false)
2808 , m_persistentRiceAdaptationEnabledFlag(false)
2809 , m_cabacBypassAlignmentEnabledFlag    (false)
2810{
2811  for (UInt signallingModeIndex = 0; signallingModeIndex < NUMBER_OF_RDPCM_SIGNALLING_MODES; signallingModeIndex++)
2812  {
2813    m_rdpcmEnabledFlag[signallingModeIndex] = false;
2814  }
2815}
2816
2817TComSPS::TComSPS()
2818: m_SPSId                     (  0)
2819, m_VPSId                     (  0)
2820, m_chromaFormatIdc           (CHROMA_420)
2821, m_uiMaxTLayers              (  1)
2822// Structure
2823, m_picWidthInLumaSamples     (352)
2824, m_picHeightInLumaSamples    (288)
2825, m_log2MinCodingBlockSize    (  0)
2826, m_log2DiffMaxMinCodingBlockSize(0)
2827, m_uiMaxCUWidth              ( 32)
2828, m_uiMaxCUHeight             ( 32)
2829, m_uiMaxTotalCUDepth         (  3)
2830, m_bLongTermRefsPresent      (false)
2831, m_uiQuadtreeTULog2MaxSize   (  0)
2832, m_uiQuadtreeTULog2MinSize   (  0)
2833, m_uiQuadtreeTUMaxDepthInter (  0)
2834, m_uiQuadtreeTUMaxDepthIntra (  0)
2835// Tool list
2836, m_usePCM                    (false)
2837, m_pcmLog2MaxSize            (  5)
2838, m_uiPCMLog2MinSize          (  7)
2839, m_bPCMFilterDisableFlag     (false)
2840, m_uiBitsForPOC              (  8)
2841, m_numLongTermRefPicSPS      (  0)
2842#if NH_MV
2843, m_numShortTermRefPicSets    (   0)
2844#endif
2845, m_uiMaxTrSize               ( 32)
2846, m_bUseSAO                   (false)
2847, m_bTemporalIdNestingFlag    (false)
2848, m_scalingListEnabledFlag    (false)
2849, m_useStrongIntraSmoothing   (false)
2850, m_vuiParametersPresentFlag  (false)
2851, m_vuiParameters             ()
2852#if NH_MV
2853, m_pcVPS                     ( NULL )
2854, m_spsInferScalingListFlag   ( false )
2855, m_spsScalingListRefLayerId  ( 0 )
2856
2857, m_updateRepFormatFlag       ( false ) 
2858, m_spsRepFormatIdx           ( 0 )
2859, m_interViewMvVertConstraintFlag (false)
2860#endif
2861
2862{
2863  for(Int ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
2864  {
2865    m_bitDepths.recon[ch] = 8;
2866#if O0043_BEST_EFFORT_DECODING
2867    m_bitDepths.stream[ch] = 8;
2868#endif
2869    m_pcmBitDepths[ch] = 8;
2870    m_qpBDOffset   [ch] = 0;
2871  }
2872
2873
2874  for ( Int i = 0; i < MAX_TLAYER; i++ )
2875  {
2876#if NH_MV
2877    m_uiSpsMaxLatencyIncreasePlus1[i] = 0;
2878#else
2879    m_uiMaxLatencyIncreasePlus1[i] = 0;
2880#endif
2881    m_uiMaxDecPicBuffering[i] = 1;
2882    m_numReorderPics[i]       = 0;
2883  }
2884
2885  ::memset(m_ltRefPicPocLsbSps, 0, sizeof(m_ltRefPicPocLsbSps));
2886  ::memset(m_usedByCurrPicLtSPSFlag, 0, sizeof(m_usedByCurrPicLtSPSFlag));
2887#if NH_MV
2888  m_spsRangeExtensionsFlag     = false;
2889  m_spsMultilayerExtensionFlag = false;
2890  m_spsExtension5bits          = 0;
2891  m_sps3dExtensionFlag         = false;   
2892  m_layerId                    = -1; 
2893  m_inferredRepFormat          = NULL;
2894#endif
2895
2896}
2897
2898TComSPS::~TComSPS()
2899{
2900  m_RPSList.destroy();
2901}
2902
2903Void  TComSPS::createRPSList( Int numRPS )
2904{
2905  m_RPSList.destroy();
2906  m_RPSList.create(numRPS);
2907}
2908
2909const Int TComSPS::m_winUnitX[]={1,2,2,1};
2910const Int TComSPS::m_winUnitY[]={1,2,1,1};
2911
2912TComPPSRExt::TComPPSRExt()
2913: m_log2MaxTransformSkipBlockSize      (2)
2914, m_crossComponentPredictionEnabledFlag(false)
2915, m_diffCuChromaQpOffsetDepth          (0)
2916, m_chromaQpOffsetListLen              (0)
2917// m_ChromaQpAdjTableIncludingNullEntry initialized below
2918// m_log2SaoOffsetScale initialized below
2919{
2920  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.
2921  m_ChromaQpAdjTableIncludingNullEntry[0].u.comp.CrOffset = 0;
2922  for(Int ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
2923  {
2924    m_log2SaoOffsetScale[ch] = 0;
2925  }
2926}
2927
2928TComPPS::TComPPS()
2929: m_PPSId                            (0)
2930, m_SPSId                            (0)
2931, m_picInitQPMinus26                 (0)
2932, m_useDQP                           (false)
2933, m_bConstrainedIntraPred            (false)
2934, m_bSliceChromaQpFlag               (false)
2935, m_uiMaxCuDQPDepth                  (0)
2936, m_chromaCbQpOffset                 (0)
2937, m_chromaCrQpOffset                 (0)
2938, m_numRefIdxL0DefaultActive         (1)
2939, m_numRefIdxL1DefaultActive         (1)
2940, m_TransquantBypassEnabledFlag      (false)
2941, m_useTransformSkip                 (false)
2942, m_dependentSliceSegmentsEnabledFlag(false)
2943, m_tilesEnabledFlag                 (false)
2944, m_entropyCodingSyncEnabledFlag     (false)
2945, m_loopFilterAcrossTilesEnabledFlag (true)
2946, m_uniformSpacingFlag               (false)
2947, m_numTileColumnsMinus1             (0)
2948, m_numTileRowsMinus1                (0)
2949, m_signDataHidingEnabledFlag        (false)
2950, m_cabacInitPresentFlag             (false)
2951, m_sliceHeaderExtensionPresentFlag  (false)
2952, m_loopFilterAcrossSlicesEnabledFlag(false)
2953, m_listsModificationPresentFlag     (0)
2954, m_numExtraSliceHeaderBits          (0)
2955#if NH_MV
2956, m_ppsInferScalingListFlag          (false)
2957, m_ppsScalingListRefLayerId         (0)
2958, m_pocResetInfoPresentFlag          (false)
2959#endif
2960#if NH_3D
2961, m_cDLT                             ()
2962#endif
2963{
2964#if NH_MV
2965  m_ppsRangeExtensionsFlag     = false;
2966  m_ppsMultilayerExtensionFlag = false;
2967  m_pps3dExtensionFlag         = false;
2968  m_ppsExtension5bits          = 0;
2969#endif
2970
2971}
2972
2973TComPPS::~TComPPS()
2974{
2975}
2976
2977#if NH_3D
2978TComDLT::TComDLT( )
2979: m_bDltPresentFlag(false)
2980, m_iNumDepthViews(0)
2981, m_uiDepthViewBitDepth(8)
2982{
2983  for( Int i = 0; i < MAX_NUM_LAYERS; i++ )
2984  {
2985    m_bUseDLTFlag                 [i] = false;
2986    m_bInterViewDltPredEnableFlag [i] = false;
2987    m_bDltBitMapRepFlag           [i] = false;
2988
2989    // allocate some memory and initialize with default mapping
2990    m_iNumDepthmapValues[i] = ((1 << m_uiDepthViewBitDepth)-1)+1;
2991    m_iDepthValue2Idx[i]    = std::vector<Int>(m_iNumDepthmapValues[i]);
2992    m_iIdx2DepthValue[i]    = std::vector<Int>(m_iNumDepthmapValues[i]);
2993   
2994    m_iDepthIdxToLayerId[i] = i;
2995
2996    //default mapping
2997    for (Int d=0; d<m_iNumDepthmapValues[i]; d++)
2998    {
2999      m_iDepthValue2Idx[i][d] = d;
3000      m_iIdx2DepthValue[i][d] = d;
3001    }
3002  }
3003}
3004
3005TComDLT::~TComDLT()
3006{
3007 
3008}
3009
3010Void TComDLT::setDepthLUTs(Int layerIdInVps, std::vector<Int> idxToDepthValueTable, Int iNumDepthValues)
3011{
3012  if( iNumDepthValues == 0 ) // default mapping only
3013    return;
3014
3015  // copy idx2DepthValue to internal array
3016  m_iIdx2DepthValue[layerIdInVps] = idxToDepthValueTable;
3017
3018  UInt uiMaxDepthValue = ((1 << m_uiDepthViewBitDepth)-1);
3019  for(Int p=0; p<=uiMaxDepthValue; p++)
3020  {
3021    Int iIdxDown    = 0;
3022    Int iIdxUp      = iNumDepthValues-1;
3023    Bool bFound     = false;
3024
3025    // iterate over indices to find lower closest depth
3026    Int i = 1;
3027    while(!bFound && i<iNumDepthValues)
3028    {
3029      if( m_iIdx2DepthValue[layerIdInVps][i] > p )
3030      {
3031        iIdxDown  = i-1;
3032        bFound    = true;
3033      }
3034
3035      i++;
3036    }
3037    iIdxUp = bFound ?  iIdxDown + 1 : iNumDepthValues-1;
3038
3039    // assign closer depth value/idx
3040    if( abs(p-m_iIdx2DepthValue[layerIdInVps][iIdxDown]) < abs(p-m_iIdx2DepthValue[layerIdInVps][iIdxUp]) )
3041    {
3042      m_iDepthValue2Idx[layerIdInVps][p] = iIdxDown;
3043    }
3044    else
3045    {
3046      m_iDepthValue2Idx[layerIdInVps][p] = iIdxUp;
3047    }
3048
3049  }
3050
3051  // update DLT variables
3052  m_iNumDepthmapValues[layerIdInVps] = iNumDepthValues;
3053}
3054
3055Void TComDLT::getDeltaDLT( Int layerIdInVps, std::vector<Int> piDLTInRef, UInt uiDLTInRefNum, std::vector<Int>& riDeltaDLTOut, UInt&ruiDeltaDLTOutNum ) const
3056{
3057  Bool abBM0[ 256 ];
3058  Bool abBM1[ 256 ];
3059 
3060  memset( abBM0, 0, sizeof( abBM0 ));
3061  memset( abBM1, 0, sizeof( abBM1 ));
3062 
3063  // convert reference DLT to bit string
3064  for( Int i = 0; i < uiDLTInRefNum; i++ )
3065  {
3066    abBM0[ piDLTInRef[ i ] ] = true;
3067  }
3068  // convert internal DLT to bit string
3069  for( Int i = 0; i < m_iNumDepthmapValues[ layerIdInVps ]; i++ )
3070  {
3071    abBM1[ m_iIdx2DepthValue[ layerIdInVps ][ i ] ] = true;
3072  }
3073 
3074  ruiDeltaDLTOutNum = 0;
3075  for( Int i = 0; i < 256; i++ )
3076  {
3077    if( abBM0[ i ] ^ abBM1[ i ] )
3078    {
3079      riDeltaDLTOut[ ruiDeltaDLTOutNum++ ] = i;
3080    }
3081  }
3082}
3083
3084Void TComDLT::setDeltaDLT( Int layerIdInVps, std::vector<Int> piDLTInRef, UInt uiDLTInRefNum, std::vector<Int> piDeltaDLTIn, UInt uiDeltaDLTInNum )
3085{
3086  Bool abBM0[ 256 ];
3087  Bool abBM1[ 256 ];
3088 
3089  memset( abBM0, 0, sizeof( abBM0 ));
3090  memset( abBM1, 0, sizeof( abBM1 ));
3091 
3092  // convert reference DLT to bit string
3093  for( Int i = 0; i < uiDLTInRefNum; i++ )
3094  {
3095    abBM0[ piDLTInRef[ i ] ] = true;
3096  }
3097  // convert delta DLT to bit string
3098  for( Int i = 0; i < uiDeltaDLTInNum; i++ )
3099  {
3100    abBM1[ piDeltaDLTIn[ i ] ] = true;
3101  }
3102 
3103  std::vector<Int> aiIdx2DepthValue(256, 0);
3104  UInt uiNumDepthValues = 0;
3105  std::fill(aiIdx2DepthValue.begin(), aiIdx2DepthValue.end(), 0);
3106 
3107  for( Int i = 0; i < 256; i++ )
3108  {
3109    if( abBM0[ i ] ^ abBM1[ i ] )
3110    {
3111      aiIdx2DepthValue[ uiNumDepthValues++ ] = i;
3112    }
3113  }
3114 
3115  // update internal tables
3116  setDepthLUTs(layerIdInVps, aiIdx2DepthValue, uiNumDepthValues);
3117}
3118
3119#endif
3120
3121#if NH_MV
3122Void TComSPS::inferRepFormat( TComVPS* vps, Int layerIdCurr, Bool alreadySet )
3123{ 
3124  // Parameters are present in the SPS
3125  // - base layer or muliLayerExpSpsFlag equal to zero
3126
3127  // It is a requirement of bitstream conformance that, when present, the value of chroma_format_idc,
3128  // separate_colour_plane_flag, pic_width_in_luma_samples, pic_height_in_luma_samples, bit_depth_luma_minus8 or
3129  // bit_depth_chroma_minus8 shall be less than or equal to chroma_format_vps_idc, separate_colour_plane_vps_flag,
3130  // pic_width_vps_in_luma_samples, pic_height_vps_in_luma_samples, bit_depth_vps_luma_minus8, or bit_depth_vps_chroma_minus8,
3131  // respectively, of the vps_rep_format_idx[ j ]-th rep_format( ) syntax structure
3132  // in the active VPS, where j is equal to LayerIdxInVps[ layerIdCurr ].
3133
3134  Bool baseLayer               = ( layerIdCurr == 0 );
3135  Bool independentNonBaseLayer = vps->isIndependendNonBaseLayer( layerIdCurr );
3136  Bool multiLayerExtSpsFlag    = getMultiLayerExtSpsFlag(); 
3137
3138  Int            repFormatIdx = getUpdateRepFormatFlag() ?  getSpsRepFormatIdx() : vps->getVpsRepFormatIdx( vps->getLayerIdInVps( layerIdCurr ) ) ;
3139  const TComRepFormat* repFormat    = vps->getRepFormat( repFormatIdx ); 
3140
3141  assert( !( multiLayerExtSpsFlag && ( independentNonBaseLayer || baseLayer )) ); 
3142
3143  Bool presentInSps = !multiLayerExtSpsFlag;
3144  if ( presentInSps )
3145  {
3146    // Values have been set before in xInitSps
3147
3148    assert( getChromaFormatIdc()      <=  repFormat->getChromaFormatVpsIdc()         ); 
3149    //// ToDo: add when supported:
3150    ///  assert( getSeperateColourPlaneFlag() <=  repFormat->getSeparateColourPlaneVpsFlag() ) ;
3151
3152    assert( getPicWidthInLumaSamples()  <= repFormat->getPicWidthVpsInLumaSamples()    ); 
3153    assert( getPicHeightInLumaSamples() <= repFormat->getPicHeightVpsInLumaSamples()   ); 
3154
3155    assert( getBitDepth( CHANNEL_TYPE_LUMA   )  <= repFormat->getBitDepthVpsLumaMinus8()   + 8 );         
3156    assert( getBitDepth( CHANNEL_TYPE_CHROMA )  <= repFormat->getBitDepthVpsChromaMinus8() + 8 ); 
3157  }
3158
3159  if ( !independentNonBaseLayer )
3160  {
3161
3162    Window &spsConf    = getConformanceWindow();   
3163
3164    // Inference when not already done at the encoder.
3165    if ( alreadySet )
3166    {
3167      assert( getChromaFormatIdc() ==  (ChromaFormat) repFormat->getChromaFormatVpsIdc() );         
3168      //// ToDo: add when supported:
3169      // assert( getSeperateColourPlaneFlag( repFormat->getSeparateColourPlaneVpsFlag() ) ;
3170
3171      assert( getPicWidthInLumaSamples()  ==  repFormat->getPicWidthVpsInLumaSamples()  ); 
3172      assert( getPicHeightInLumaSamples() == repFormat->getPicHeightVpsInLumaSamples() ); 
3173
3174      assert( getBitDepth              ( CHANNEL_TYPE_LUMA ) == repFormat->getBitDepthVpsLumaMinus8()   + 8 ); 
3175      assert( getQpBDOffset            ( CHANNEL_TYPE_LUMA ) == (Int) (6*( getBitDepth( CHANNEL_TYPE_LUMA ) - 8 )) );
3176
3177      assert( getBitDepth              ( CHANNEL_TYPE_CHROMA ) == repFormat->getBitDepthVpsChromaMinus8() + 8 ); 
3178      assert( getQpBDOffset            ( CHANNEL_TYPE_CHROMA ) == (Int) (6* ( getBitDepth( CHANNEL_TYPE_CHROMA ) -8 ) ) );
3179
3180     
3181      assert( spsConf.getWindowLeftOffset  () == repFormat->getConfWinVpsLeftOffset()    );
3182      assert( spsConf.getWindowRightOffset () == repFormat->getConfWinVpsRightOffset()   );
3183      assert( spsConf.getWindowTopOffset   () == repFormat->getConfWinVpsTopOffset()     );
3184      assert( spsConf.getWindowBottomOffset() == repFormat->getConfWinVpsBottomOffset()  );           
3185
3186    }
3187    else
3188    {
3189      setChromaFormatIdc( (ChromaFormat) repFormat->getChromaFormatVpsIdc() );         
3190      //// ToDo: add when supported:
3191      // setSeperateColourPlaneFlag( repFormat->getSeparateColourPlaneVpsFlag() ) ;
3192
3193      setPicWidthInLumaSamples ( repFormat->getPicWidthVpsInLumaSamples()  ); 
3194      setPicHeightInLumaSamples( repFormat->getPicHeightVpsInLumaSamples() ); 
3195
3196      setBitDepth              ( CHANNEL_TYPE_LUMA, repFormat->getBitDepthVpsLumaMinus8()   + 8 ); 
3197      setQpBDOffset            ( CHANNEL_TYPE_LUMA, (Int) (6*( getBitDepth( CHANNEL_TYPE_LUMA ) - 8 )) );
3198
3199      setBitDepth              ( CHANNEL_TYPE_CHROMA, repFormat->getBitDepthVpsChromaMinus8() + 8 ); 
3200      setQpBDOffset            ( CHANNEL_TYPE_CHROMA, (Int) (6* ( getBitDepth( CHANNEL_TYPE_CHROMA ) -8 ) ) );
3201     
3202      // Scaled later
3203      spsConf.setScaledFlag( false ); 
3204      spsConf.setWindowLeftOffset  ( repFormat->getConfWinVpsLeftOffset()    );
3205      spsConf.setWindowRightOffset ( repFormat->getConfWinVpsRightOffset()   );
3206      spsConf.setWindowTopOffset   ( repFormat->getConfWinVpsTopOffset()     );
3207      spsConf.setWindowBottomOffset( repFormat->getConfWinVpsBottomOffset()  );           
3208    }
3209  }
3210 
3211
3212  // Set conformance window
3213  Int scal = TComSPS::getWinUnitX( getChromaFormatIdc() ) ;
3214  getConformanceWindow().scaleOffsets( scal );
3215  getVuiParameters()->getDefaultDisplayWindow().scaleOffsets( scal );
3216}
3217
3218Void TComSPS::inferScalingList( const TComSPS* spsSrc )
3219{
3220  if ( getSpsInferScalingListFlag() ) 
3221  {
3222    assert( spsSrc != NULL ); 
3223    assert( !spsSrc->getSpsInferScalingListFlag() );             
3224    getScalingList().inferFrom( (spsSrc->getScalingList()) ); 
3225  }
3226}
3227
3228Void TComSPS::inferSpsMaxDecPicBufferingMinus1( TComVPS* vps, Int targetOptLayerSetIdx, Int currLayerId, Bool doCheck )
3229{
3230  if ( getMultiLayerExtSpsFlag() )
3231  {
3232    const std::vector<Int>& targetDecLayerIdList = vps->getTargetDecLayerIdList( vps->olsIdxToLsIdx( targetOptLayerSetIdx )); 
3233    Int layerIdx = 0;         
3234    while (layerIdx < (Int) targetDecLayerIdList.size() )
3235    {
3236      if ( targetDecLayerIdList[layerIdx] == currLayerId )
3237      { 
3238        break; 
3239      }
3240      layerIdx++; 
3241    }
3242
3243    assert( layerIdx < (Int) targetDecLayerIdList.size() ); 
3244
3245    for (Int i = 0; i <= getSpsMaxSubLayersMinus1(); i++ ) 
3246    {
3247      Int maxDecPicBufferingMinus1 = vps->getDpbSize()->getMaxVpsDecPicBufferingMinus1( targetOptLayerSetIdx, layerIdx, i ) ; 
3248
3249      // This preliminary fix needs to be checked.
3250      Int maxNumReorderPics       = vps->getDpbSize()->getMaxVpsNumReorderPics( targetOptLayerSetIdx, i ); 
3251      Int maxLatencyIncreasePlus1 = vps->getDpbSize()->getMaxVpsLatencyIncreasePlus1( targetOptLayerSetIdx, i ); 
3252      if ( doCheck )     
3253      {
3254        assert( getMaxDecPicBuffering( i ) - 1 == maxDecPicBufferingMinus1 ); 
3255        // This preliminary fix needs to be checked.
3256        assert( getNumReorderPics( i )     == maxNumReorderPics       ); 
3257        assert( getSpsMaxLatencyIncreasePlus1( i ) == maxLatencyIncreasePlus1 ); 
3258
3259      }
3260      else
3261      {
3262        // This preliminary fix needs to be checked.
3263        setMaxDecPicBuffering( maxDecPicBufferingMinus1 + 1 , i); 
3264        setNumReorderPics    ( maxNumReorderPics, i );
3265        setSpsMaxLatencyIncreasePlus1( maxLatencyIncreasePlus1 , i); 
3266      }
3267    }   
3268  }
3269}
3270
3271Void TComSPS::checkRpsMaxNumPics( const TComVPS* vps, Int currLayerId ) const
3272{
3273  for (Int i = 0; i < getRPSList()->getNumberOfReferencePictureSets(); i++ )
3274  {
3275    const TComReferencePictureSet* rps = getRPSList()->getReferencePictureSet( i ); 
3276    if ( !rps->getInterRPSPrediction() )
3277    {
3278      rps->checkMaxNumPics( vps->getVpsExtensionFlag(), MAX_INT, getLayerId(), getMaxDecPicBuffering( getSpsMaxSubLayersMinus1() ) - 1 );   // INT_MAX to be replaced by DpbSize
3279    }
3280  }
3281}
3282
3283Void TComSPS::inferSpsMaxSubLayersMinus1(Bool atPsActivation, TComVPS* vps)
3284{
3285  assert( getLayerId() != 0 ); 
3286  if ( !atPsActivation   )
3287  {
3288    assert( vps == NULL );
3289    if (getSpsExtOrMaxSubLayersMinus1() != 7)
3290    {
3291      setSpsMaxSubLayersMinus1( getSpsExtOrMaxSubLayersMinus1() );
3292    }
3293  }
3294  else
3295  {
3296    assert( vps != NULL );
3297    if (getSpsExtOrMaxSubLayersMinus1() == 7)
3298    {
3299      setSpsMaxSubLayersMinus1( vps->getMaxSubLayersMinus1() );
3300    }
3301  }
3302}
3303#endif
3304
3305
3306TComReferencePictureSet::TComReferencePictureSet()
3307: m_numberOfPictures (0)
3308, m_numberOfNegativePictures (0)
3309, m_numberOfPositivePictures (0)
3310, m_numberOfLongtermPictures (0)
3311, m_interRPSPrediction (0)
3312, m_deltaRIdxMinus1 (0)
3313, m_deltaRPS (0)
3314, m_numRefIdc (0)
3315{
3316  ::memset( m_deltaPOC, 0, sizeof(m_deltaPOC) );
3317  ::memset( m_POC, 0, sizeof(m_POC) );
3318  ::memset( m_used, 0, sizeof(m_used) );
3319  ::memset( m_refIdc, 0, sizeof(m_refIdc) );
3320  ::memset( m_bCheckLTMSB, 0, sizeof(m_bCheckLTMSB) );
3321  ::memset( m_pocLSBLT, 0, sizeof(m_pocLSBLT) );
3322  ::memset( m_deltaPOCMSBCycleLT, 0, sizeof(m_deltaPOCMSBCycleLT) );
3323  ::memset( m_deltaPocMSBPresentFlag, 0, sizeof(m_deltaPocMSBPresentFlag) );
3324}
3325
3326TComReferencePictureSet::~TComReferencePictureSet()
3327{
3328}
3329
3330Void TComReferencePictureSet::setUsed(Int bufferNum, Bool used)
3331{
3332  m_used[bufferNum] = used;
3333}
3334
3335Void TComReferencePictureSet::setDeltaPOC(Int bufferNum, Int deltaPOC)
3336{
3337  m_deltaPOC[bufferNum] = deltaPOC;
3338}
3339
3340Void TComReferencePictureSet::setNumberOfPictures(Int numberOfPictures)
3341{
3342  m_numberOfPictures = numberOfPictures;
3343}
3344
3345Int TComReferencePictureSet::getUsed(Int bufferNum) const
3346{
3347  return m_used[bufferNum];
3348}
3349
3350Int TComReferencePictureSet::getDeltaPOC(Int bufferNum) const
3351{
3352  return m_deltaPOC[bufferNum];
3353}
3354
3355Int TComReferencePictureSet::getNumberOfPictures() const
3356{
3357  return m_numberOfPictures;
3358}
3359
3360Int TComReferencePictureSet::getPOC(Int bufferNum) const
3361{
3362  return m_POC[bufferNum];
3363}
3364
3365Void TComReferencePictureSet::setPOC(Int bufferNum, Int POC)
3366{
3367  m_POC[bufferNum] = POC;
3368}
3369
3370Bool TComReferencePictureSet::getCheckLTMSBPresent(Int bufferNum) const
3371{
3372  return m_bCheckLTMSB[bufferNum];
3373}
3374
3375Void TComReferencePictureSet::setCheckLTMSBPresent(Int bufferNum, Bool b)
3376{
3377  m_bCheckLTMSB[bufferNum] = b;
3378}
3379
3380//! set the reference idc value at uiBufferNum entry to the value of iRefIdc
3381Void TComReferencePictureSet::setRefIdc(Int bufferNum, Int refIdc)
3382{
3383  m_refIdc[bufferNum] = refIdc;
3384}
3385
3386//! get the reference idc value at uiBufferNum
3387Int  TComReferencePictureSet::getRefIdc(Int bufferNum) const
3388{
3389  return m_refIdc[bufferNum];
3390}
3391
3392/** Sorts the deltaPOC and Used by current values in the RPS based on the deltaPOC values.
3393 *  deltaPOC values are sorted with -ve values before the +ve values.  -ve values are in decreasing order.
3394 *  +ve values are in increasing order.
3395 * \returns Void
3396 */
3397Void TComReferencePictureSet::sortDeltaPOC()
3398{
3399  // sort in increasing order (smallest first)
3400  for(Int j=1; j < getNumberOfPictures(); j++)
3401  {
3402    Int deltaPOC = getDeltaPOC(j);
3403    Bool used = getUsed(j);
3404    for (Int k=j-1; k >= 0; k--)
3405    {
3406      Int temp = getDeltaPOC(k);
3407      if (deltaPOC < temp)
3408      {
3409        setDeltaPOC(k+1, temp);
3410        setUsed(k+1, getUsed(k));
3411        setDeltaPOC(k, deltaPOC);
3412        setUsed(k, used);
3413      }
3414    }
3415  }
3416  // flip the negative values to largest first
3417  Int numNegPics = getNumberOfNegativePictures();
3418  for(Int j=0, k=numNegPics-1; j < numNegPics>>1; j++, k--)
3419  {
3420    Int deltaPOC = getDeltaPOC(j);
3421    Bool used = getUsed(j);
3422    setDeltaPOC(j, getDeltaPOC(k));
3423    setUsed(j, getUsed(k));
3424    setDeltaPOC(k, deltaPOC);
3425    setUsed(k, used);
3426  }
3427}
3428
3429/** Prints the deltaPOC and RefIdc (if available) values in the RPS.
3430 *  A "*" is added to the deltaPOC value if it is Used bu current.
3431 * \returns Void
3432 */
3433Void TComReferencePictureSet::printDeltaPOC() const
3434{
3435  printf("DeltaPOC = { ");
3436  for(Int j=0; j < getNumberOfPictures(); j++)
3437  {
3438    printf("%d%s ", getDeltaPOC(j), (getUsed(j)==1)?"*":"");
3439  }
3440  if (getInterRPSPrediction())
3441  {
3442    printf("}, RefIdc = { ");
3443    for(Int j=0; j < getNumRefIdc(); j++)
3444    {
3445      printf("%d ", getRefIdc(j));
3446    }
3447  }
3448  printf("}\n");
3449}
3450
3451#if NH_MV
3452Void TComReferencePictureSet::checkMaxNumPics( Bool vpsExtensionFlag, Int maxNumPics, Int nuhLayerId, Int spsMaxDecPicBufferingMinus1 ) const
3453{
3454  assert( getNumberOfPictures() >= 0 ); 
3455  if ( nuhLayerId == 0 )
3456  {
3457    assert( getNumberOfPictures() <= spsMaxDecPicBufferingMinus1 ); 
3458  }
3459
3460  if ( vpsExtensionFlag )
3461  {
3462    assert( getNumberOfPictures() <= maxNumPics );
3463  }
3464}
3465#endif
3466
3467
3468
3469
3470TComRefPicListModification::TComRefPicListModification()
3471: m_refPicListModificationFlagL0 (false)
3472, m_refPicListModificationFlagL1 (false)
3473{
3474  ::memset( m_RefPicSetIdxL0, 0, sizeof(m_RefPicSetIdxL0) );
3475  ::memset( m_RefPicSetIdxL1, 0, sizeof(m_RefPicSetIdxL1) );
3476}
3477
3478TComRefPicListModification::~TComRefPicListModification()
3479{
3480}
3481
3482TComScalingList::TComScalingList()
3483{
3484  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
3485  {
3486    for(UInt listId = 0; listId < SCALING_LIST_NUM; listId++)
3487    {
3488      m_scalingListCoef[sizeId][listId].resize(min<Int>(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
3489    }
3490  }
3491}
3492
3493/** set default quantization matrix to array
3494*/
3495Void TComScalingList::setDefaultScalingList()
3496{
3497  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
3498  {
3499    for(UInt listId=0;listId<SCALING_LIST_NUM;listId++)
3500    {
3501      processDefaultMatrix(sizeId, listId);
3502    }
3503  }
3504}
3505/** check if use default quantization matrix
3506 * \returns true if use default quantization matrix in all size
3507*/
3508Bool TComScalingList::checkDefaultScalingList()
3509{
3510  UInt defaultCounter=0;
3511
3512  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
3513  {
3514    for(UInt listId=0;listId<SCALING_LIST_NUM;listId++)
3515    {
3516      if( !memcmp(getScalingListAddress(sizeId,listId), getScalingListDefaultAddress(sizeId, listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
3517     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == 16))) // check DC value
3518      {
3519        defaultCounter++;
3520      }
3521    }
3522  }
3523
3524  return (defaultCounter == (SCALING_LIST_NUM * SCALING_LIST_SIZE_NUM )) ? false : true;
3525}
3526
3527#if NH_MV
3528Void TComSlice::createInterLayerReferencePictureSet( TComPicLists* ivPicLists, std::vector<TComPic*>& refPicSetInterLayer0, std::vector<TComPic*>& refPicSetInterLayer1 )
3529{
3530  refPicSetInterLayer0.clear(); 
3531  refPicSetInterLayer1.clear(); 
3532
3533  for( Int i = 0; i < getNumActiveRefLayerPics(); i++ ) 
3534  {
3535    Int layerIdRef = getRefPicLayerId( i ); 
3536    TComPic* picRef = ivPicLists->getPic( layerIdRef, getPOC() ) ; 
3537    assert ( picRef != 0 ); // There shall be no entry equal to "no reference picture" in RefPicSetInterLayer0 or RefPicSetInterLayer1.
3538
3539    picRef->getPicYuvRec()->extendPicBorder(); 
3540    picRef->setIsLongTerm( true );       
3541    picRef->getSlice(0)->setReferenced( true );       
3542
3543    Int viewIdCur  = getVPS()->getViewId( getLayerId() ); 
3544    Int viewIdZero = getVPS()->getViewId( 0 );
3545    Int viewIdRef  = getVPS()->getViewId( layerIdRef ); 
3546
3547    if (  ( viewIdCur <= viewIdZero && viewIdCur <= viewIdRef ) || ( viewIdCur >= viewIdZero && viewIdCur >= viewIdRef ) )
3548    {
3549      refPicSetInterLayer0.push_back( picRef ); 
3550    }
3551    else
3552    {
3553      refPicSetInterLayer1.push_back( picRef ); 
3554    }
3555    // Consider to check here:
3556    // "If the current picture is a RADL picture, there shall be no entry in the RefPicSetInterLayer0 and RefPicSetInterLayer1 that is a RASL picture. "   
3557    assert( picRef->getSlice(0)->getDiscardableFlag() == false ); // "There shall be no picture that has discardable_flag equal to 1 in RefPicSetInterLayer0 or RefPicSetInterLayer1".       
3558  }
3559}
3560Void TComSlice::markIvRefPicsAsShortTerm( std::vector<TComPic*> refPicSetInterLayer0, std::vector<TComPic*> refPicSetInterLayer1 )
3561{
3562  // Mark as short-term
3563  for ( Int i = 0; i < refPicSetInterLayer0.size(); i++ ) 
3564  {
3565    refPicSetInterLayer0[i]->setIsLongTerm( false ); 
3566  }
3567
3568  for ( Int i = 0; i < refPicSetInterLayer1.size(); i++ ) 
3569  {
3570    refPicSetInterLayer1[i]->setIsLongTerm( false ); 
3571  }
3572
3573}
3574
3575Void TComSlice::printRefPicList()
3576{ 
3577  for ( Int li = 0; li < 2; li++)
3578  {   
3579    std::cout << std::endl << "RefPicListL" <<  li << ":" << std::endl; 
3580    for (Int rIdx = 0; rIdx <= (m_aiNumRefIdx[li]-1); rIdx ++)
3581    {     
3582      if (rIdx == 0 && li == 0) m_apcRefPicList[li][rIdx]->print( 1 );
3583      m_apcRefPicList[li][rIdx]->print( 0 );     
3584       
3585    }
3586  }
3587}
3588
3589Void TComSlice::markCurrPic( TComPic* currPic )
3590{
3591  currPic->getSlice(0)->setReferenced( true ) ; 
3592  currPic->setIsLongTerm( false ); 
3593
3594  currPic->setReconMark( true );
3595  currPic->setPicOutputFlag( currPic->getSlice(0)->getPicOutputFlag() );
3596}
3597
3598Void TComSlice::setRefPicSetInterLayer( std::vector<TComPic*>* refPicSetInterLayer0, std::vector<TComPic*>* refPicSetInterLayer1 )
3599{
3600  m_refPicSetInterLayer0 = refPicSetInterLayer0; 
3601  m_refPicSetInterLayer1 = refPicSetInterLayer1; 
3602}
3603
3604TComPic* TComSlice::getRefPicSetInterLayer( Int setIdc, Int i ) const
3605{
3606  TComPic* pic = NULL; 
3607  if (setIdc == 0 )
3608  {
3609    pic = (*m_refPicSetInterLayer0)[ i ]; 
3610  }
3611  else if (setIdc == 1 )
3612  {
3613    pic = (*m_refPicSetInterLayer1)[ i ]; 
3614  }
3615
3616  assert( pic != NULL );   
3617
3618  return pic; 
3619}
3620
3621
3622TComPic* TComSlice::getPicFromRefPicSetInterLayer(Int setIdc, Int layerId ) const
3623{
3624  assert ( setIdc == 0 || setIdc == 1);   
3625  std::vector<TComPic*>* refPicSetInterLayer = ( setIdc == 0 ? m_refPicSetInterLayer0 : m_refPicSetInterLayer1);   
3626  assert( refPicSetInterLayer != 0 ); 
3627 
3628  TComPic* pcPic = NULL; 
3629  for ( Int i = 0; i < (*refPicSetInterLayer).size(); i++ )
3630  {
3631    if ((*refPicSetInterLayer)[ i ]->getLayerId() == layerId )
3632    {
3633      pcPic = (*refPicSetInterLayer)[ i ]; 
3634    }
3635  }
3636
3637  assert(pcPic != NULL); 
3638  return pcPic;
3639}
3640
3641
3642Int  TComSlice::getRefLayerPicFlag( Int i ) const
3643{
3644  const TComVPS* vps = getVPS(); 
3645#if NH_3D
3646  Int refLayerIdx = vps->getLayerIdInVps( vps->getIdRefListLayer( getLayerId(), i ) ); 
3647#else
3648  Int refLayerIdx = vps->getLayerIdInVps( vps->getIdDirectRefLayer( getLayerId(), i ) ); 
3649#endif
3650
3651  Bool refLayerPicFlag = ( vps->getSubLayersVpsMaxMinus1( refLayerIdx ) >=  getTLayer()  && ( getTLayer() == 0   ||
3652    vps->getMaxTidIlRefPicsPlus1( refLayerIdx, vps->getLayerIdInVps( getLayerId() )) > getTLayer() )); 
3653  return refLayerPicFlag;       
3654}   
3655
3656Int TComSlice::getRefLayerPicIdc( Int j ) const
3657{ 
3658  Int refLayerPicIdc = -1; 
3659  Int curj = 0; 
3660#if NH_3D
3661  for( Int i = 0;  i < getVPS()->getNumRefListLayers( getLayerId()) ; i++ )
3662#else
3663  for( Int i = 0;  i < getVPS()->getNumDirectRefLayers( getLayerId()) ; i++ )
3664#endif
3665  {
3666    if( getRefLayerPicFlag( i ) )
3667    {
3668      if ( curj == j ) 
3669      {
3670        refLayerPicIdc = i;         
3671        break;
3672      }
3673      curj++; 
3674    }
3675  }
3676
3677  assert( curj == j ); 
3678  assert( refLayerPicIdc != -1 ); 
3679  return refLayerPicIdc; 
3680}
3681
3682Int  TComSlice::getNumRefLayerPics( ) const
3683{ 
3684  Int numRefLayerPics = 0; 
3685#if NH_3D
3686  for( Int i = 0;  i < getVPS()->getNumRefListLayers( getLayerId()) ; i++ )
3687#else
3688  for( Int i = 0;  i < getVPS()->getNumDirectRefLayers( getLayerId()) ; i++ )
3689#endif
3690  {
3691    numRefLayerPics += getRefLayerPicFlag( i ); 
3692  }
3693  return numRefLayerPics; 
3694}
3695
3696
3697
3698Int TComSlice::getNumActiveRefLayerPics() const
3699{
3700  Int numActiveRefLayerPics; 
3701
3702  if( getLayerId() == 0 || getNumRefLayerPics() ==  0 )
3703  {
3704    numActiveRefLayerPics = 0; 
3705  }
3706  else if (getVPS()->getAllRefLayersActiveFlag() )
3707  {
3708    numActiveRefLayerPics = getNumRefLayerPics(); 
3709  }
3710  else if ( !getInterLayerPredEnabledFlag() )
3711  {
3712    numActiveRefLayerPics = 0; 
3713  }
3714#if NH_3D
3715  else if( getVPS()->getMaxOneActiveRefLayerFlag() || getVPS()->getNumRefListLayers( getLayerId() ) == 1 )
3716#else
3717  else if( getVPS()->getMaxOneActiveRefLayerFlag() || getVPS()->getNumDirectRefLayers( getLayerId() ) == 1 )
3718#endif
3719  {
3720    numActiveRefLayerPics = 1; 
3721  }
3722  else
3723  {
3724    numActiveRefLayerPics = getNumInterLayerRefPicsMinus1() + 1; 
3725  }
3726  return numActiveRefLayerPics;
3727}
3728
3729Int TComSlice::getRefPicLayerId( Int i ) const
3730{
3731#if NH_3D
3732  return getVPS()->getIdRefListLayer( getLayerId(), getInterLayerPredLayerIdc( i ) );
3733#else
3734  return getVPS()->getIdDirectRefLayer( getLayerId(), getInterLayerPredLayerIdc( i ) );
3735#endif
3736}
3737#endif
3738#if NH_3D
3739Void TComSlice::setDefaultRefView()
3740{
3741  setDefaultRefViewIdx(-1);
3742  setDefaultRefViewIdxAvailableFlag(false); 
3743
3744  Int valid = 0;
3745  Int DefaultRefViewIdx = -1;
3746
3747  for(UInt curViewIdx = 0; curViewIdx < getViewIndex() && valid == 0; curViewIdx++)
3748  {
3749    for(Int iRefListId = 0; (iRefListId < (isInterB() ? 2 : 1)) && !isIntra() && valid == 0; iRefListId++)
3750    {
3751      RefPicList eRefPicList = RefPicList(iRefListId);
3752      Int        iNumRefPics = getNumRefIdx(eRefPicList);
3753
3754      for(Int i = 0; i < iNumRefPics; i++)
3755      { 
3756        if(getPOC() == getRefPic(eRefPicList, i)->getPOC() && curViewIdx == getRefPic(eRefPicList, i)->getViewIndex())
3757        {
3758          valid = 1;
3759          DefaultRefViewIdx = curViewIdx;
3760          break;
3761        }
3762      }
3763    }
3764  }
3765
3766  if(valid)
3767  {
3768    setDefaultRefViewIdx(DefaultRefViewIdx);
3769    setDefaultRefViewIdxAvailableFlag(true);
3770  }
3771}
3772
3773Void TComSlice::setARPStepNum( TComPicLists*ivPicLists )
3774{
3775  Bool tempRefPicInListsFlag = false;
3776  if( !getIvResPredFlag() || this->isIRAP())
3777  {
3778    m_nARPStepNum = 0;
3779  }
3780  else
3781  {
3782    setFirstTRefIdx (REF_PIC_LIST_0, -1);
3783    setFirstTRefIdx (REF_PIC_LIST_1, -1);
3784    for ( Int refListIdx = 0; refListIdx < ((m_eSliceType==B_SLICE) ? 2 : 1); refListIdx++ )
3785    {
3786      Int diffPOC=MAX_INT;
3787      Int idx=-1;
3788      for(Int i = 0; i < getNumRefIdx(RefPicList(refListIdx)); i++ )
3789      {
3790        if ( getRefPic(RefPicList(refListIdx), i)->getPOC() != getPOC() )
3791        {
3792          if( abs(getRefPic(RefPicList(refListIdx), i)->getPOC() - getPOC()) < diffPOC)
3793          {
3794            diffPOC=abs(getRefPic(RefPicList(refListIdx), i)->getPOC() - getPOC());
3795            idx=i;
3796          }
3797        }
3798        if(idx>=0)
3799        {
3800          setFirstTRefIdx (RefPicList(refListIdx), idx);
3801        }
3802      }
3803    }
3804    tempRefPicInListsFlag = (getFirstTRefIdx(REF_PIC_LIST_0) >= 0 || getFirstTRefIdx(REF_PIC_LIST_1) >= 0) && getDefaultRefViewIdxAvailableFlag();
3805    m_nARPStepNum = tempRefPicInListsFlag ? 3 : 0;
3806  }
3807
3808  if (tempRefPicInListsFlag)
3809  {
3810    for ( Int refListIdx = 0; refListIdx < ((m_eSliceType==B_SLICE) ? 2 : 1); refListIdx++ )
3811    {
3812      RefPicList eRefPicList = RefPicList( refListIdx );
3813      Int prevPOC = getRefPic(eRefPicList, getFirstTRefIdx(eRefPicList) )->getPOC();
3814      for( Int i = 0; i < getNumActiveRefLayerPics(); i++ )
3815      {
3816        Int layerIdInNuh = getRefPicLayerId( i );
3817
3818        TComPic* picV = getIvPic( getIsDepth(), getVPS()->getViewIndex( layerIdInNuh ) );
3819        assert( picV != NULL ); 
3820        IntAry1d pocsInCurrRPSsPicV = picV->getSlice(0)->getPocsInCurrRPSs(); 
3821        Bool refRpRefAvailFlag = false; 
3822        for (Int idx = 0; idx < pocsInCurrRPSsPicV.size(); idx++)
3823        {
3824          if ( pocsInCurrRPSsPicV[idx] == prevPOC )
3825          {
3826            refRpRefAvailFlag = true; 
3827            break; 
3828          }
3829        }
3830
3831        if (getFirstTRefIdx(eRefPicList) >= 0 && refRpRefAvailFlag )
3832        {
3833          m_arpRefPicAvailable[eRefPicList][layerIdInNuh] = true;
3834        }
3835        else
3836        {
3837          m_arpRefPicAvailable[eRefPicList][layerIdInNuh] = false;
3838        }
3839      }
3840    }
3841  }
3842  if( m_nARPStepNum > 1)
3843  {
3844    for(Int i = 0; i < getNumActiveRefLayerPics(); i ++ )
3845    {
3846      Int  iLayerId = getRefPicLayerId( i );
3847      Int  iViewIdx =   getVPS()->getViewIndex(iLayerId);
3848      Bool bIsDepth = ( getVPS()->getDepthId  ( iLayerId ) == 1 );
3849      if( iViewIdx<getViewIndex() && !bIsDepth )
3850      {
3851        setBaseViewRefPicList( ivPicLists->getSubDpb( iLayerId, false ), iViewIdx );
3852      }
3853    }
3854  }
3855}
3856
3857// This is an encoder only function and should be moved to TEncSlice or TEncSearch!!
3858Void TComSlice::xSetApplyIC(Bool bUseLowLatencyICEnc)
3859{
3860  if(bUseLowLatencyICEnc)
3861  {
3862    Bool existInterViewRef=false;
3863    TComPic* pcCurrPic = getPic();
3864    TComPic* pcRefPic = NULL;
3865    for ( Int i = 0; (i < getNumRefIdx( REF_PIC_LIST_0 )) && !existInterViewRef; i++ )
3866    {
3867      pcRefPic = getRefPic( REF_PIC_LIST_0, i );
3868      if ( pcRefPic != NULL )
3869      {
3870        if ( pcCurrPic->getViewIndex() != pcRefPic->getViewIndex() )
3871        {
3872          existInterViewRef = true;
3873        }
3874      }
3875    }
3876
3877    for ( Int i = 0; (i < getNumRefIdx( REF_PIC_LIST_1 )) && !existInterViewRef; i++ )
3878    {
3879      pcRefPic = getRefPic( REF_PIC_LIST_1, i );
3880      if ( pcRefPic != NULL )
3881      {
3882        if ( pcCurrPic->getViewIndex() != pcRefPic->getViewIndex() )
3883        {
3884          existInterViewRef = true;       
3885        }
3886      }
3887    }
3888
3889    if(!existInterViewRef)
3890    {
3891      m_bApplyIC = false;
3892    }
3893    else
3894    {
3895      Int curLayer=getDepth();
3896      if( curLayer>9) curLayer=9; // Max layer is 10
3897
3898      m_bApplyIC = true;
3899      Int refLayer = curLayer-1;
3900
3901      Int ICEnableCandidate = getICEnableCandidate(refLayer);
3902      Int ICEnableNum = getICEnableNum(refLayer);
3903      if( (refLayer>=0) && (ICEnableCandidate>0) )
3904      {   
3905        Double ratio=Double(ICEnableNum/Double(ICEnableCandidate));
3906
3907        if( ratio > IC_LOW_LATENCY_ENCODING_THRESHOLD)
3908        {
3909          m_bApplyIC=true;
3910        }
3911        else
3912        {
3913          m_bApplyIC=false;
3914        }
3915      }
3916      setICEnableCandidate(curLayer, 0);
3917      setICEnableNum(curLayer, 0);
3918    }
3919  }
3920  else
3921  {       
3922    TComPic*    pcCurrPic = getPic();
3923    TComPicYuv* pcCurrPicYuv = pcCurrPic->getPicYuvOrg();
3924   
3925    // Get InterView Reference picture
3926    // !!!!! Assume only one Interview Reference Picture in L0
3927    // GT: Is this assumption correct?
3928
3929    TComPicYuv* pcRefPicYuvOrg = NULL;
3930    for ( Int i = 0; i < getNumRefIdx( REF_PIC_LIST_0 ); i++ )
3931    {
3932      TComPic* pcRefPic = getRefPic( REF_PIC_LIST_0, i );
3933      if ( pcRefPic != NULL )
3934      {
3935        if ( pcCurrPic->getViewIndex() != pcRefPic->getViewIndex() )
3936        {
3937          pcRefPicYuvOrg = pcRefPic->getPicYuvOrg();
3938        }
3939      }
3940    }
3941
3942    if ( pcRefPicYuvOrg != NULL )
3943    {
3944      // Histogram building - luminance
3945      Int iMaxPelValue = ( 1 << getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) ); 
3946      Int *aiRefOrgHist = (Int *) xMalloc( Int,iMaxPelValue );
3947      Int *aiCurrHist   = (Int *) xMalloc( Int,iMaxPelValue );
3948      memset( aiRefOrgHist, 0, iMaxPelValue*sizeof(Int) );
3949      memset( aiCurrHist, 0, iMaxPelValue*sizeof(Int) );
3950
3951      Int iWidth   = pcCurrPicYuv->getWidth(COMPONENT_Y);
3952      Int iHeight  = pcCurrPicYuv->getHeight(COMPONENT_Y);
3953      Pel* pCurrY   = pcCurrPicYuv->getAddr(COMPONENT_Y);
3954      Pel* pRefOrgY = pcRefPicYuvOrg->getAddr(COMPONENT_Y);
3955      Int iCurrStride = pcCurrPicYuv->getStride(COMPONENT_Y);
3956      Int iRefStride = pcRefPicYuvOrg->getStride(COMPONENT_Y);
3957      for ( Int y = 0; y < iHeight; y++ )
3958      {
3959        for ( Int x = 0; x < iWidth; x++ )
3960        {
3961          aiCurrHist[pCurrY[x]]++;
3962          aiRefOrgHist[pRefOrgY[x]]++;
3963        }
3964        pCurrY += iCurrStride;
3965        pRefOrgY += iRefStride;
3966      }
3967
3968      // Histogram SAD
3969      Int iSumOrgSAD = 0;
3970      for ( Int i = 0; i < iMaxPelValue; i++ )
3971      {
3972        iSumOrgSAD += abs( aiCurrHist[i] - aiRefOrgHist[i] );
3973      }
3974
3975      // Setting
3976      Double dThresholdOrgSAD = getIsDepth() ? 0.1 : 0.05;
3977
3978      if ( iSumOrgSAD > Int( dThresholdOrgSAD * iWidth * iHeight ) )
3979      {
3980        m_bApplyIC = true;
3981      }
3982      else
3983      {
3984        m_bApplyIC = false;
3985      }
3986
3987      xFree( aiCurrHist   );
3988      xFree( aiRefOrgHist );
3989    }
3990  }//if(bUseLowLatencyICEnc)
3991}
3992
3993Void TComSlice::setIvPicLists( TComPicLists* m_ivPicLists )
3994{ 
3995  for (Int i = 0; i < MAX_NUM_LAYERS; i++ )
3996  { 
3997    for ( Int depthId = 0; depthId < 2; depthId++ )
3998    {
3999      m_ivPicsCurrPoc[ depthId ][ i ] = ( i <= m_viewIndex ) ? m_ivPicLists->getPic( i, ( depthId == 1) , 0, getPOC() ) : NULL;
4000    }       
4001  } 
4002}
4003#endif
4004#if NH_3D
4005Void TComSlice::setDepthToDisparityLUTs()
4006{ 
4007  Bool setupLUT = false; 
4008 
4009  setupLUT = setupLUT || getViewSynthesisPredFlag( ); 
4010  setupLUT = setupLUT || getDepthRefinementFlag( );
4011  setupLUT = setupLUT || ( getIvMvPredFlag() && getIsDepth() );
4012
4013  Int bitDepthY = getSPS()->getBitDepth(CHANNEL_TYPE_LUMA);
4014
4015  if( !setupLUT )
4016  {
4017    return; 
4018  }
4019
4020  m_numViews = getVPS()->getNumViews(); 
4021  /// GT: Allocation should be moved to a better place later;
4022  if ( m_depthToDisparityB == NULL )
4023  {
4024    m_depthToDisparityB = new Int*[ m_numViews ];
4025    for ( Int i = 0; i < getVPS()->getNumViews(); i++ )
4026    {
4027      m_depthToDisparityB[ i ] = new Int[ Int(1 << bitDepthY) ]; 
4028    }
4029  }
4030
4031 
4032  if ( m_depthToDisparityF == NULL )
4033  {
4034    m_depthToDisparityF = new Int*[ m_numViews ];
4035    for ( Int i = 0; i < m_numViews; i++ )
4036    {
4037      m_depthToDisparityF[ i ] = new Int[ Int(1 << bitDepthY) ]; 
4038    }
4039  }
4040
4041  assert( m_depthToDisparityB != NULL ); 
4042  assert( m_depthToDisparityF != NULL ); 
4043
4044  const TComVPS* vps = getVPS(); 
4045
4046  Int log2Div = bitDepthY - 1 + vps->getCpPrecision();
4047  Int voiInVps = vps->getVoiInVps( getViewIndex() ); 
4048  Bool camParaSH = vps->getCpInSliceSegmentHeaderFlag( voiInVps ); 
4049
4050  const IntAry1d codScale     = camParaSH ? m_aaiCodedScale [ 0 ] : vps->getCodedScale    ( voiInVps ); 
4051  const IntAry1d codOffset    = camParaSH ? m_aaiCodedOffset[ 0 ] : vps->getCodedOffset   ( voiInVps ); 
4052  const IntAry1d invCodScale  = camParaSH ? m_aaiCodedScale [ 1 ] : vps->getInvCodedScale ( voiInVps ); 
4053  const IntAry1d invCodOffset = camParaSH ? m_aaiCodedOffset[ 1 ] : vps->getInvCodedOffset( voiInVps ); 
4054
4055
4056  for (Int i = 0; i < voiInVps; i++)
4057  {
4058    Int iInVoi = vps->getVoiInVps( i ); 
4059#if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
4060    if ( g_traceCameraParameters )
4061    {
4062      std::cout << "Cp: " << codScale   [ iInVoi ] << " " <<    codOffset[ iInVoi ] << " "
4063                << invCodScale[ iInVoi ] << " " << invCodOffset[ iInVoi ] << " " << log2Div << std::endl ; 
4064    }
4065#endif
4066    for ( Int d = 0; d <= ( ( 1 << bitDepthY ) - 1 ); d++ )
4067    {     
4068      Int offset =    ( codOffset  [ iInVoi ] << bitDepthY ) + ( ( 1 << log2Div ) >> 1 );         
4069      m_depthToDisparityB[ iInVoi ][ d ] = ( codScale [ iInVoi ] * d + offset ) >> log2Div; 
4070
4071      Int invOffset = ( invCodOffset[ iInVoi ] << bitDepthY ) + ( ( 1 << log2Div ) >> 1 );         
4072      m_depthToDisparityF[ iInVoi ][ d ] = ( invCodScale[ iInVoi ] * d + invOffset ) >> log2Div; 
4073    }
4074  }
4075}
4076#endif
4077
4078
4079
4080#if NH_MV
4081Void TComSlice::checkCrossLayerBlaFlag() const
4082{
4083  // cross_layer_bla_flag shall be equal to 0 for pictures with nal_unit_type not equal to IDR_W_RADL or IDR_N_LP or with nuh_layer_id not equal to 0.
4084  if ( getLayerId() != 0 || getNalUnitType() != NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )
4085  {
4086    assert( m_crossLayerBlaFlag == 0 ); 
4087  }
4088}
4089
4090Bool TComSlice::inferPocMsbCycleValPresentFlag()
4091{
4092  Bool pocMsbValPresentFlag; 
4093  if( getSliceSegmentHeaderExtensionLength() == 0 ) 
4094  {
4095    pocMsbValPresentFlag = false; 
4096  }
4097  else if ( getPocMsbValRequiredFlag() )
4098  {
4099    pocMsbValPresentFlag = true; 
4100  }
4101  else
4102  {
4103    pocMsbValPresentFlag = false; 
4104  }
4105
4106  return pocMsbValPresentFlag;
4107}
4108
4109
4110Void TComSlice::f834decProcForRefPicListConst()
4111{
4112  // This process is invoked at the beginning of the decoding process for each P or B slice.
4113  assert( getSliceType() == B_SLICE || getSliceType() == P_SLICE );
4114
4115  // Reference pictures are addressed through reference indices as specified in clause 8.5.3.3.2. A reference index is an index into
4116  // a reference picture list. When decoding a P slice, there is a single reference picture list RefPicList0. When decoding a B
4117  // slice, there is a second independent reference picture list RefPicList1 in addition to RefPicList0.
4118
4119  // At the beginning of the decoding process for each slice, the reference picture lists RefPicList0 and, for B slices, RefPicList1
4120  // are derived as follows:
4121
4122  // The variable NumRpsCurrTempList0 is set equal to Max( num_ref_idx_l0_active_minus1 + 1, NumPicTotalCurr )
4123  Int numRpsCurrTempList0 = std::max( getNumRefIdxL0ActiveMinus1() + 1, getNumPicTotalCurr() );
4124
4125  // and the list RefPicListTemp0 is constructed as follows:
4126  std::vector<TComPic*> refPicListTemp0;
4127  refPicListTemp0.resize((MAX_NUM_REF+1),NULL);
4128
4129  const TComDecodedRps* decRps = getPic()->getDecodedRps(); 
4130
4131  const std::vector<TComPic*>& refPicSetStCurrBefore  = decRps->m_refPicSetStCurrBefore; 
4132  const std::vector<TComPic*>& refPicSetStCurrAfter   = decRps->m_refPicSetStCurrAfter;
4133  const std::vector<TComPic*>& refPicSetLtCurr        = decRps->m_refPicSetLtCurr; 
4134
4135  const Int                    numPocStCurrBefore     = decRps->m_numPocStCurrBefore; 
4136  const Int                    numPocStCurrAfter      = decRps->m_numPocStCurrAfter;
4137  const Int                    numPocLtCurr           = decRps->m_numPocLtCurr;
4138
4139  const Int                    numActiveRefLayerPics0 = decRps->m_numActiveRefLayerPics0;
4140  const Int                    numActiveRefLayerPics1 = decRps->m_numActiveRefLayerPics1;
4141
4142  const std::vector<TComPic*>& refPicSetInterLayer0   = decRps->m_refPicSetInterLayer0;
4143  const std::vector<TComPic*>& refPicSetInterLayer1   = decRps->m_refPicSetInterLayer1;
4144
4145  Int rIdx = 0;
4146  while( rIdx < numRpsCurrTempList0 )
4147  {
4148    for(Int  i = 0; i < numPocStCurrBefore  &&  rIdx < numRpsCurrTempList0; rIdx++, i++ )
4149    {
4150      refPicListTemp0[ rIdx ] = refPicSetStCurrBefore[ i ];
4151    }   
4152
4153    for(Int  i = 0; i < numActiveRefLayerPics0; rIdx++, i++ )
4154    {
4155      refPicListTemp0[ rIdx ] = refPicSetInterLayer0[ i ];
4156    }
4157
4158    for(Int  i = 0;  i < numPocStCurrAfter  &&  rIdx < numRpsCurrTempList0; rIdx++, i++ )  // (F 65)
4159    {
4160      refPicListTemp0[ rIdx ] = refPicSetStCurrAfter[ i ];
4161    }
4162
4163    for(Int  i = 0; i < numPocLtCurr  &&  rIdx < numRpsCurrTempList0; rIdx++, i++ )
4164    {
4165      refPicListTemp0[ rIdx ] = refPicSetLtCurr[ i ]; 
4166    }
4167
4168    for(Int  i = 0; i < numActiveRefLayerPics1; rIdx++, i++ )
4169    {
4170      refPicListTemp0[ rIdx ] = refPicSetInterLayer1[ i ];
4171    }
4172  }
4173
4174  // The list RefPicList0 is constructed as follows:
4175  TComRefPicListModification* rplm  = getRefPicListModification(); 
4176  for( rIdx = 0; rIdx  <=  getNumRefIdxL0ActiveMinus1(); rIdx++ )      //  (F 66)
4177  {
4178    m_apcRefPicList[ 0 ][ rIdx ] = rplm->getRefPicListModificationFlagL0( ) ? refPicListTemp0[ rplm->getListEntryL0( rIdx )] : refPicListTemp0[ rIdx ];
4179    // The decoding process below slice level requires the status
4180    // of the reference pictures, when decoding the RPS. So store it here.
4181    m_bIsUsedAsLongTerm[ 0 ][ rIdx ] = m_apcRefPicList[ 0 ][ rIdx ]->getIsLongTerm();
4182    m_aiRefPOCList     [ 0 ][ rIdx ] = m_apcRefPicList[ 0 ][ rIdx ]->getPOC();
4183    m_aiRefLayerIdList [ 0 ][ rIdx ] = m_apcRefPicList[ 0 ][ rIdx ]->getLayerId();
4184  } 
4185
4186  std::vector<TComPic*> refPicListTemp1;
4187  refPicListTemp1.resize((MAX_NUM_REF+1),NULL);
4188
4189  if (getSliceType() == B_SLICE )
4190  {
4191    // When the slice is a B slice, the variable NumRpsCurrTempList1 is set equal to
4192    // Max( num_ref_idx_l1_active_minus1 + 1, NumPicTotalCurr ) and the list RefPicListTemp1 is constructed as follows:       
4193    Int numRpsCurrTempList1 = std::max( getNumRefIdxL1ActiveMinus1() + 1, getNumPicTotalCurr() );
4194
4195    rIdx = 0; 
4196    while( rIdx < numRpsCurrTempList1 )
4197    {
4198      for( Int i = 0; i < numPocStCurrAfter  &&  rIdx < numRpsCurrTempList1; rIdx++, i++ )
4199      {
4200        refPicListTemp1[ rIdx ] = refPicSetStCurrAfter[ i ]; 
4201      }
4202      for( Int i = 0; i< numActiveRefLayerPics1; rIdx++, i++ )
4203      {
4204        refPicListTemp1[ rIdx ] = refPicSetInterLayer1[ i ]; 
4205      }
4206      for( Int i = 0;  i < numPocStCurrBefore  &&  rIdx < numRpsCurrTempList1; rIdx++, i++ )  // (F 67)
4207      {
4208        refPicListTemp1[ rIdx ] = refPicSetStCurrBefore[ i ];
4209      }         
4210      for( Int i = 0; i < numPocLtCurr  &&  rIdx < numRpsCurrTempList1; rIdx++, i++ )
4211      {
4212        refPicListTemp1[ rIdx ] = refPicSetLtCurr[ i ];
4213      }
4214      for( Int i = 0; i< numActiveRefLayerPics0; rIdx++, i++ )
4215      {
4216        refPicListTemp1[ rIdx ] = refPicSetInterLayer0[ i ]; 
4217      }
4218    }
4219  }
4220
4221  if (getSliceType() == B_SLICE )
4222  {
4223    //   When the slice is a B slice, the list RefPicList1 is constructed as follows:
4224    for( rIdx = 0; rIdx  <=  getNumRefIdxL1ActiveMinus1(); rIdx++ )      // (F 68)
4225    {
4226      m_apcRefPicList[ 1 ][ rIdx ] = rplm->getRefPicListModificationFlagL1() ? refPicListTemp1[ rplm->getListEntryL1( rIdx ) ] : refPicListTemp1[ rIdx ]; 
4227
4228      // The decoding process below slice level requires the marking status
4229      // of the reference pictures, when decoding the RPS. So store it here.
4230      m_bIsUsedAsLongTerm[ 1 ][ rIdx ] = m_apcRefPicList[ 1 ][ rIdx ]->getIsLongTerm();
4231      m_aiRefPOCList     [ 1 ][ rIdx ] = m_apcRefPicList[ 1 ][ rIdx ]->getPOC();
4232      m_aiRefLayerIdList [ 1 ][ rIdx ] = m_apcRefPicList[ 1 ][ rIdx ]->getLayerId();
4233    }   
4234  }
4235}
4236
4237
4238Void TComSlice::cl834DecProcForRefPicListConst()
4239{
4240  // This process is invoked at the beginning of the decoding process for each P or B slice.
4241  assert( getSliceType() == B_SLICE || getSliceType() == P_SLICE );
4242
4243  // Reference pictures are addressed through reference indices as specified in clause 8.5.3.3.2. A reference index is an index into
4244  // a reference picture list. When decoding a P slice, there is a single reference picture list RefPicList0. When decoding a B
4245  // slice, there is a second independent reference picture list RefPicList1 in addition to RefPicList0.
4246
4247  // At the beginning of the decoding process for each slice, the reference picture lists RefPicList0 and, for B slices, RefPicList1
4248  // are derived as follows:
4249
4250  // The variable NumRpsCurrTempList0 is set equal to Max( num_ref_idx_l0_active_minus1 + 1, NumPicTotalCurr )
4251  Int numRpsCurrTempList0 = std::max( getNumRefIdxL0ActiveMinus1() + 1, getNumPicTotalCurr() );
4252
4253  // and the list RefPicListTemp0 is constructed as follows:
4254  std::vector<TComPic*> refPicListTemp0; 
4255  refPicListTemp0.resize((MAX_NUM_REF+1),NULL);
4256
4257  const TComDecodedRps* decRps = getPic()->getDecodedRps(); 
4258
4259  const std::vector<TComPic*>& refPicSetStCurrBefore = decRps->m_refPicSetStCurrBefore; 
4260  const std::vector<TComPic*>& refPicSetStCurrAfter  = decRps->m_refPicSetStCurrAfter;
4261  const std::vector<TComPic*>& refPicSetLtCurr       = decRps->m_refPicSetLtCurr; 
4262   
4263  const Int                    numPocStCurrBefore    = decRps->m_numPocStCurrBefore; 
4264  const Int                    numPocStCurrAfter     = decRps->m_numPocStCurrAfter;
4265  const Int                    numPocLtCurr          = decRps->m_numPocLtCurr;
4266
4267  Int rIdx = 0;
4268  while( rIdx < numRpsCurrTempList0 )
4269  {
4270    for(Int  i = 0; i < numPocStCurrBefore  &&  rIdx < numRpsCurrTempList0; rIdx++, i++ )
4271    {
4272      refPicListTemp0[ rIdx ] = refPicSetStCurrBefore[ i ];
4273    }   
4274
4275    for(Int  i = 0;  i < numPocStCurrAfter  &&  rIdx < numRpsCurrTempList0; rIdx++, i++ )  // (8 8)
4276    {
4277      refPicListTemp0[ rIdx ] = refPicSetStCurrAfter[ i ];
4278    }
4279
4280    for(Int  i = 0; i < numPocLtCurr  &&  rIdx < numRpsCurrTempList0; rIdx++, i++ )
4281    {
4282      refPicListTemp0[ rIdx ] = refPicSetLtCurr[ i ]; 
4283    }
4284  }
4285
4286  // The list RefPicList0 is constructed as follows:
4287
4288  TComRefPicListModification* rplm = getRefPicListModification(); 
4289  for( rIdx = 0; rIdx  <=  getNumRefIdxL0ActiveMinus1(); rIdx++ )      //   (8-9)
4290  {
4291    m_apcRefPicList[0][ rIdx ] = rplm->getRefPicListModificationFlagL0( ) ? refPicListTemp0[ rplm->getListEntryL0( rIdx )] : refPicListTemp0[ rIdx ];
4292
4293    // The decoding process below slice level requires the marking status
4294    // of the reference pictures, when decoding the RPS. So store it here.
4295    m_bIsUsedAsLongTerm[ 0 ][ rIdx ] = m_apcRefPicList[ 0 ][ rIdx ]->getIsLongTerm();
4296    m_aiRefPOCList     [ 0 ][ rIdx ] = m_apcRefPicList[ 0 ][ rIdx ]->getPOC();
4297    m_aiRefLayerIdList [ 0 ][ rIdx ] = m_apcRefPicList[ 0 ][ rIdx ]->getLayerId();
4298  }
4299
4300  std::vector<TComPic*> refPicListTemp1;
4301  refPicListTemp1.resize((MAX_NUM_REF+1),NULL);
4302
4303  if (getSliceType() == B_SLICE )
4304  {
4305    // When the slice is a B slice, the variable NumRpsCurrTempList1 is set equal to
4306    // Max( num_ref_idx_l1_active_minus1 + 1, NumPicTotalCurr ) and the list RefPicListTemp1 is constructed as follows:
4307    Int numRpsCurrTempList1 = std::max( getNumRefIdxL1ActiveMinus1() + 1, getNumPicTotalCurr() );
4308
4309    rIdx = 0; 
4310    while( rIdx < numRpsCurrTempList1 )
4311    {
4312      for( Int i = 0; i < numPocStCurrAfter  &&  rIdx < numRpsCurrTempList1; rIdx++, i++ )
4313      {
4314        refPicListTemp1[ rIdx ] = refPicSetStCurrAfter[ i ]; 
4315      }
4316      for( Int i = 0;  i < numPocStCurrBefore  &&  rIdx < numRpsCurrTempList1; rIdx++, i++ )  // (8-10)
4317      {
4318        refPicListTemp1[ rIdx ] = refPicSetStCurrBefore[ i ];
4319      }         
4320      for( Int i = 0; i < numPocLtCurr  &&  rIdx < numRpsCurrTempList1; rIdx++, i++ )
4321      {
4322        refPicListTemp1[ rIdx ] = refPicSetLtCurr[ i ];
4323      }
4324    }
4325  }
4326
4327  if (getSliceType() == B_SLICE )
4328  {
4329    //   When the slice is a B slice, the list RefPicList1 is constructed as follows:
4330    for( rIdx = 0; rIdx  <=  getNumRefIdxL1ActiveMinus1(); rIdx++ )      // (F 68)
4331    {
4332      m_apcRefPicList[ 1 ][ rIdx ] = rplm->getRefPicListModificationFlagL1() ? refPicListTemp1[ rplm->getListEntryL1( rIdx ) ] : refPicListTemp1[ rIdx ]; 
4333
4334      // The decoding process below slice level requires the marking status
4335      // of the reference pictures, when decoding the RPS. So store it here.
4336      m_bIsUsedAsLongTerm[ 1 ][ rIdx ] = m_apcRefPicList[ 1 ][ rIdx ]->getIsLongTerm();
4337      m_aiRefPOCList     [ 1 ][ rIdx ] = m_apcRefPicList[ 1 ][ rIdx ]->getPOC();
4338      m_aiRefLayerIdList [ 1 ][ rIdx ] = m_apcRefPicList[ 1 ][ rIdx ]->getLayerId();
4339    }
4340  }
4341}
4342
4343Int TComSlice::getNumPicTotalCurr() const
4344{
4345  Int numPicTotalCurr = 0;
4346#if NH_MV_FIX_NUM_POC_TOTAL_CUR
4347  if ( !isIdr()  )
4348  {
4349    const TComStRefPicSet* stRps = getStRps( getCurrRpsIdx() ); 
4350#endif
4351    for( Int i = 0; i < stRps->getNumNegativePicsVar(); i++ )
4352    {
4353      if( stRps->getUsedByCurrPicS0Var( i ) )
4354      {
4355        numPicTotalCurr++;
4356      }
4357    }
4358    for( Int i = 0; i < stRps->getNumPositivePicsVar(); i++)  //(7 55)
4359    {
4360      if( stRps->getUsedByCurrPicS1Var(i) )
4361      {
4362        numPicTotalCurr++;
4363      }
4364    }
4365    for( Int i = 0; i < getNumLongTermSps() + getNumLongTermPics(); i++ )
4366    {
4367      if( getUsedByCurrPicLtVar( i ) )
4368      {
4369        numPicTotalCurr++;
4370      }
4371    }
4372#if NH_MV_FIX_NUM_POC_TOTAL_CUR
4373  }
4374#endif
4375
4376  if ( decProcAnnexF() )
4377  {
4378    numPicTotalCurr += getNumActiveRefLayerPics(); 
4379  }
4380  return numPicTotalCurr;
4381}
4382
4383
4384
4385Int TComSlice::getPocLsbLtVar( Int i )
4386{
4387  Int pocLsbLtVar; 
4388  if (i < getNumLongTermSps() )
4389  {
4390
4391    pocLsbLtVar = getSPS()->getLtRefPicPocLsbSps( getLtIdxSps( i ) ); 
4392  }
4393  else
4394  {
4395    pocLsbLtVar = getPocLsbLt( i ); 
4396  }
4397  return pocLsbLtVar;
4398}
4399
4400
4401Bool TComSlice::getUsedByCurrPicLtVar( Int i ) const
4402{
4403  Bool usedByCurrPicLtVar; 
4404  if (i < getNumLongTermSps() )
4405  {
4406    usedByCurrPicLtVar = getSPS()->getUsedByCurrPicLtSPSFlag( getLtIdxSps( i ) ); 
4407  }
4408  else
4409  {
4410    usedByCurrPicLtVar = getUsedByCurrPicLtFlag( i ); 
4411  }
4412  return usedByCurrPicLtVar;
4413}
4414
4415
4416Int TComSlice::getDeltaPocMsbCycleLtVar( Int i ) const
4417{
4418  Int deltaPocMsbCycleVar; 
4419  if (i == 0 || i == getNumLongTermSps() )
4420  {
4421    deltaPocMsbCycleVar = getDeltaPocMsbCycleLt( i ); 
4422  }
4423  else
4424  {
4425    deltaPocMsbCycleVar = getDeltaPocMsbCycleLt( i ) + getDeltaPocMsbCycleLtVar( i - 1 ); 
4426  }
4427  return deltaPocMsbCycleVar;
4428}
4429
4430#endif
4431
4432
4433#if NH_3D
4434Void TComSlice::init3dToolParameters()
4435{
4436  Bool depthFlag = getIsDepth();
4437
4438  Bool nRLLG0 =  ( getVPS()->getNumRefListLayers( getLayerId() ) > 0 );     
4439
4440  const TComSps3dExtension* sps3dExt = getSPS()->getSps3dExtension();
4441
4442  m_ivMvPredFlag           = sps3dExt->getIvDiMcEnabledFlag          ( depthFlag ) && nRLLG0                       ;                             
4443  m_ivMvScalingFlag        = sps3dExt->getIvMvScalEnabledFlag        ( depthFlag )                                 ;                             
4444  m_ivResPredFlag          = sps3dExt->getIvResPredEnabledFlag       ( depthFlag ) && nRLLG0                       ;                               
4445  m_depthRefinementFlag    = sps3dExt->getDepthRefEnabledFlag        ( depthFlag )           && getInCompPredFlag() && m_cpAvailableFlag;
4446  m_viewSynthesisPredFlag  = sps3dExt->getVspMcEnabledFlag           ( depthFlag ) && nRLLG0 && getInCompPredFlag() && m_cpAvailableFlag;
4447  m_depthBasedBlkPartFlag  = sps3dExt->getDbbpEnabledFlag            ( depthFlag )           && getInCompPredFlag();                         
4448  m_mpiFlag                = sps3dExt->getTexMcEnabledFlag           ( depthFlag )           && getInCompPredFlag();
4449  m_intraContourFlag       = sps3dExt->getIntraContourEnabledFlag    ( depthFlag )           && getInCompPredFlag();
4450  m_intraSdcWedgeFlag      = sps3dExt->getIntraDcOnlyWedgeEnabledFlag( depthFlag )                                 ;                         
4451  m_qtPredFlag             = sps3dExt->getCqtCuPartPredEnabledFlag   ( depthFlag )           && getInCompPredFlag();
4452  m_interSdcFlag           = sps3dExt->getInterDcOnlyEnabledFlag     ( depthFlag )                                 ; 
4453  m_depthIntraSkipFlag     = sps3dExt->getSkipIntraEnabledFlag       ( depthFlag )                                 ;                         
4454
4455  m_subPbSize              =  1 << ( sps3dExt->getLog2IvmcSubPbSizeMinus3 ( depthFlag ) + 3 ); 
4456  m_mpiSubPbSize           =  1 << ( sps3dExt->getLog2TexmcSubPbSizeMinus3( depthFlag ) + 3 );
4457
4458
4459#if NH_3D_OUTPUT_ACTIVE_TOOLS
4460  std::cout << "Layer:                  :" << getLayerId()             << std::endl;
4461  std::cout << "DepthFlag:              :" << getIsDepth()             << std::endl;
4462  std::cout << "ViewOrderIdx:           :" << getViewIndex()           << std::endl;
4463  std::cout << "InterCmpPredAvailableFlag:" << getInCmpPredAvailFlag() << std::endl;
4464  std::cout << "InterCompPredFlag       :"  << getInCompPredFlag()     << std::endl;
4465 
4466  std::cout << "ivMvPredFlag            :" << m_ivMvPredFlag           << std::endl;
4467  std::cout << "ivMvScalingFlag         :" << m_ivMvScalingFlag        << std::endl;
4468  std::cout << "ivResPredFlag           :" << m_ivResPredFlag          << std::endl;
4469  std::cout << "depthRefinementFlag     :" << m_depthRefinementFlag    << std::endl;
4470  std::cout << "viewSynthesisPredFlag   :" << m_viewSynthesisPredFlag  << std::endl;
4471  std::cout << "depthBasedBlkPartFlag   :" << m_depthBasedBlkPartFlag  << std::endl;
4472  std::cout << "mpiFlag                 :" << m_mpiFlag                << std::endl;
4473  std::cout << "intraContourFlag        :" << m_intraContourFlag       << std::endl;
4474  std::cout << "intraSdcWedgeFlag       :" << m_intraSdcWedgeFlag      << std::endl;
4475  std::cout << "qtPredFlag              :" << m_qtPredFlag             << std::endl;
4476  std::cout << "interSdcFlag            :" << m_interSdcFlag           << std::endl;
4477  std::cout << "depthIntraSkipFlag      :" << m_depthIntraSkipFlag     << std::endl;   
4478  std::cout << "subPbSize               :" << m_subPbSize              << std::endl;
4479  std::cout << "mpiSubPbSize            :" << m_mpiSubPbSize           << std::endl;
4480#endif
4481}
4482
4483Void TComSlice::deriveInCmpPredAndCpAvailFlag( )
4484{
4485  Int numCurCmpLIds = getIsDepth() ? 1 : getNumActiveRefLayerPics(); 
4486  std::vector<Int> curCmpLIds;
4487  if ( getIsDepth() )
4488  {
4489    curCmpLIds.push_back( getLayerId() );
4490  }
4491  else
4492  {
4493    for (Int i = 0; i < numCurCmpLIds; i++)
4494    {
4495      curCmpLIds.push_back( getRefPicLayerId( i ) );
4496    }
4497  }
4498
4499  m_cpAvailableFlag = true;
4500  m_inCmpRefViewIdcs.clear();
4501  Bool allRefCmpLayersAvailFlag = true;
4502
4503  for( Int i = 0; i <= numCurCmpLIds - 1; i++ )
4504  {     
4505    m_inCmpRefViewIdcs.push_back( getVPS()->getViewOrderIdx( curCmpLIds[ i ] ));
4506    if( !getVPS()->getCpPresentFlag( getVPS()->getVoiInVps( getViewIndex() ),  getVPS()->getVoiInVps( m_inCmpRefViewIdcs[ i ] ) ) )
4507    {
4508      m_cpAvailableFlag = false;
4509    }
4510    Bool refCmpCurLIdAvailFlag = false;
4511    if( getVPS()->getViewCompLayerPresentFlag( m_inCmpRefViewIdcs[ i ], !getIsDepth() ) )
4512    {
4513      Int jInNuh = getVPS()->getViewCompLayerId( m_inCmpRefViewIdcs[ i ],  !getIsDepth() );
4514      Int j = getVPS()->getLayerIdInVps( jInNuh );
4515      if  ( getVPS()->getDirectDependencyFlag( getVPS()->getLayerIdInVps( getLayerId() ) ,  j ) &&
4516        getVPS()->getSubLayersVpsMaxMinus1( j ) >= getTemporalId()   &&
4517        ( getTemporalId() == 0 || getVPS()->getMaxTidIlRefPicsPlus1( j , getVPS()->getLayerIdInVps( getLayerId() ) ) > getTemporalId() )       
4518        )
4519      {
4520        refCmpCurLIdAvailFlag = true;
4521      }
4522    }
4523    if( !refCmpCurLIdAvailFlag )
4524    {
4525      allRefCmpLayersAvailFlag = false;
4526    }
4527  }
4528
4529  if( !allRefCmpLayersAvailFlag )
4530  {
4531    m_inCmpPredAvailFlag = false;
4532  } 
4533  else 
4534  {
4535    const TComSps3dExtension* sps3dExt = getSPS()->getSps3dExtension();
4536    if( !getIsDepth() )
4537    {
4538      m_inCmpPredAvailFlag = sps3dExt->getVspMcEnabledFlag( getIsDepth() ) || 
4539        sps3dExt->getDbbpEnabledFlag( getIsDepth() ) || 
4540        sps3dExt->getDepthRefEnabledFlag  ( getIsDepth() );                           
4541    }
4542    else
4543    {
4544      m_inCmpPredAvailFlag = sps3dExt->getIntraContourEnabledFlag( getIsDepth() ) || 
4545        sps3dExt->getCqtCuPartPredEnabledFlag( getIsDepth() ) || 
4546        sps3dExt->getTexMcEnabledFlag( getIsDepth() );                                 
4547    }
4548  }
4549}
4550
4551Void TComSlice::checkInCompPredRefLayers()
4552{ 
4553  if ( getInCompPredFlag() )
4554  {
4555    for (Int i = 0; i < getNumCurCmpLIds(); i++ )
4556    {     
4557      assert( getIvPic(!getIsDepth(), getInCmpRefViewIdcs( i ) ) != NULL );       
4558      //  It is a requirement of bitstream conformance that there
4559      //  is a picture in the DPB with PicOrderCntVal equal to the PicOrderCntVal of the current picture,
4560      //  and a nuh_layer_id value equal to ViewCompLayerId[ inCmpRefViewIdcs[ i ] ][ !DepthFlag ].
4561    }
4562  } 
4563}
4564
4565Void TComSlice::setPocsInCurrRPSs()
4566{
4567  // Currently only needed at decoder side;
4568  m_pocsInCurrRPSs.clear();   
4569  std::vector<TComPic*>** rpsCurr = getPic()->getDecodedRps()->m_refPicSetsCurr;
4570  for (Int i = 0 ; i < 3; i++ )
4571  {
4572    for( Int j = 0; j < rpsCurr[i]->size(); j++ )
4573    {
4574      m_pocsInCurrRPSs.push_back( (*rpsCurr[i])[j]->getPOC() ); 
4575    }
4576  }
4577}
4578
4579#endif
4580
4581/** get scaling matrix from RefMatrixID
4582 * \param sizeId    size index
4583 * \param listId    index of input matrix
4584 * \param refListId index of reference matrix
4585 */
4586Void TComScalingList::processRefMatrix( UInt sizeId, UInt listId , UInt refListId )
4587{
4588  ::memcpy(getScalingListAddress(sizeId, listId),((listId == refListId)? getScalingListDefaultAddress(sizeId, refListId): getScalingListAddress(sizeId, refListId)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
4589}
4590
4591Void TComScalingList::checkPredMode(UInt sizeId, UInt listId)
4592{
4593  Int predListStep = (sizeId == SCALING_LIST_32x32? (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) : 1); // if 32x32, skip over chroma entries.
4594
4595  for(Int predListIdx = (Int)listId ; predListIdx >= 0; predListIdx-=predListStep)
4596  {
4597    if( !memcmp(getScalingListAddress(sizeId,listId),((listId == predListIdx) ?
4598      getScalingListDefaultAddress(sizeId, predListIdx): getScalingListAddress(sizeId, predListIdx)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
4599     && ((sizeId < SCALING_LIST_16x16) || (getScalingListDC(sizeId,listId) == getScalingListDC(sizeId,predListIdx)))) // check DC value
4600    {
4601      setRefMatrixId(sizeId, listId, predListIdx);
4602      setScalingListPredModeFlag(sizeId, listId, false);
4603      return;
4604    }
4605  }
4606  setScalingListPredModeFlag(sizeId, listId, true);
4607}
4608
4609static Void outputScalingListHelp(std::ostream &os)
4610{
4611  os << "The scaling list file specifies all matrices and their DC values; none can be missing,\n"
4612         "but their order is arbitrary.\n\n"
4613         "The matrices are specified by:\n"
4614         "<matrix name><unchecked data>\n"
4615         "  <value>,<value>,<value>,....\n\n"
4616         "  Line-feeds can be added arbitrarily between values, and the number of values needs to be\n"
4617         "  at least the number of entries for the matrix (superfluous entries are ignored).\n"
4618         "  The <unchecked data> is text on the same line as the matrix that is not checked\n"
4619         "  except to ensure that the matrix name token is unique. It is recommended that it is ' ='\n"
4620         "  The values in the matrices are the absolute values (0-255), not the delta values as\n"
4621         "  exchanged between the encoder and decoder\n\n"
4622         "The DC values (for matrix sizes larger than 8x8) are specified by:\n"
4623         "<matrix name>_DC<unchecked data>\n"
4624         "  <value>\n";
4625
4626  os << "The permitted matrix names are:\n";
4627  for(UInt sizeIdc = 0; sizeIdc < SCALING_LIST_SIZE_NUM; sizeIdc++)
4628  {
4629    for(UInt listIdc = 0; listIdc < SCALING_LIST_NUM; listIdc++)
4630    {
4631      if ((sizeIdc!=SCALING_LIST_32x32) || (listIdc%(SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) == 0))
4632      {
4633        os << "  " << MatrixType[sizeIdc][listIdc] << '\n';
4634      }
4635    }
4636  }
4637}
4638
4639Void TComScalingList::outputScalingLists(std::ostream &os) const
4640{
4641  for(UInt sizeIdc = 0; sizeIdc < SCALING_LIST_SIZE_NUM; sizeIdc++)
4642  {
4643    const UInt size = min(8,4<<(sizeIdc));
4644    for(UInt listIdc = 0; listIdc < SCALING_LIST_NUM; listIdc++)
4645    {
4646      if ((sizeIdc!=SCALING_LIST_32x32) || (listIdc%(SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) == 0))
4647      {
4648        const Int *src = getScalingListAddress(sizeIdc, listIdc);
4649        os << (MatrixType[sizeIdc][listIdc]) << " =\n  ";
4650        for(UInt y=0; y<size; y++)
4651        {
4652          for(UInt x=0; x<size; x++, src++)
4653          {
4654            os << std::setw(3) << (*src) << ", ";
4655          }
4656          os << (y+1<size?"\n  ":"\n");
4657        }
4658        if(sizeIdc > SCALING_LIST_8x8)
4659        {
4660          os << MatrixType_DC[sizeIdc][listIdc] << " = \n  " << std::setw(3) << getScalingListDC(sizeIdc, listIdc) << "\n";
4661        }
4662        os << "\n";
4663      }
4664    }
4665  }
4666}
4667
4668Bool TComScalingList::xParseScalingList(const std::string &fileName)
4669{
4670  static const Int LINE_SIZE=1024;
4671  FILE *fp = NULL;
4672  TChar line[LINE_SIZE];
4673
4674  if (fileName.empty())
4675  {
4676    fprintf(stderr, "Error: no scaling list file specified. Help on scaling lists being output\n");
4677    outputScalingListHelp(std::cout);
4678    std::cout << "\n\nExample scaling list file using default values:\n\n";
4679    outputScalingLists(std::cout);
4680    exit (1);
4681    return true;
4682  }
4683  else if ((fp = fopen(fileName.c_str(),"r")) == (FILE*)NULL)
4684  {
4685    fprintf(stderr, "Error: cannot open scaling list file %s for reading\n", fileName.c_str());
4686    return true;
4687  }
4688
4689  for(UInt sizeIdc = 0; sizeIdc < SCALING_LIST_SIZE_NUM; sizeIdc++)
4690  {
4691    const UInt size = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeIdc]);
4692
4693    for(UInt listIdc = 0; listIdc < SCALING_LIST_NUM; listIdc++)
4694    {
4695      Int * const src = getScalingListAddress(sizeIdc, listIdc);
4696
4697      if ((sizeIdc==SCALING_LIST_32x32) && (listIdc%(SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) != 0)) // derive chroma32x32 from chroma16x16
4698      {
4699        const Int *srcNextSmallerSize = getScalingListAddress(sizeIdc-1, listIdc);
4700        for(UInt i=0; i<size; i++)
4701        {
4702          src[i] = srcNextSmallerSize[i];
4703        }
4704        setScalingListDC(sizeIdc,listIdc,(sizeIdc > SCALING_LIST_8x8) ? getScalingListDC(sizeIdc-1, listIdc) : src[0]);
4705      }
4706      else
4707      {
4708        {
4709          fseek(fp, 0, SEEK_SET);
4710          Bool bFound=false;
4711          while ((!feof(fp)) && (!bFound))
4712          {
4713            TChar *ret = fgets(line, LINE_SIZE, fp);
4714            TChar *findNamePosition= ret==NULL ? NULL : strstr(line, MatrixType[sizeIdc][listIdc]);
4715            // This could be a match against the DC string as well, so verify it isn't
4716            if (findNamePosition!= NULL && (MatrixType_DC[sizeIdc][listIdc]==NULL || strstr(line, MatrixType_DC[sizeIdc][listIdc])==NULL))
4717            {
4718              bFound=true;
4719            }
4720          }
4721          if (!bFound)
4722          {
4723            fprintf(stderr, "Error: cannot find Matrix %s from scaling list file %s\n", MatrixType[sizeIdc][listIdc], fileName.c_str());
4724            return true;
4725          }
4726        }
4727        for (UInt i=0; i<size; i++)
4728        {
4729          Int data;
4730          if (fscanf(fp, "%d,", &data)!=1)
4731          {
4732            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));
4733            return true;
4734          }
4735          if (data<0 || data>255)
4736          {
4737            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));
4738            return true;
4739          }
4740          src[i] = data;
4741        }
4742
4743        //set DC value for default matrix check
4744        setScalingListDC(sizeIdc,listIdc,src[0]);
4745
4746        if(sizeIdc > SCALING_LIST_8x8)
4747        {
4748          {
4749            fseek(fp, 0, SEEK_SET);
4750            Bool bFound=false;
4751            while ((!feof(fp)) && (!bFound))
4752            {
4753              TChar *ret = fgets(line, LINE_SIZE, fp);
4754              TChar *findNamePosition= ret==NULL ? NULL : strstr(line, MatrixType_DC[sizeIdc][listIdc]);
4755              if (findNamePosition!= NULL)
4756              {
4757                // This won't be a match against the non-DC string.
4758                bFound=true;
4759              }
4760            }
4761            if (!bFound)
4762            {
4763              fprintf(stderr, "Error: cannot find DC Matrix %s from scaling list file %s\n", MatrixType_DC[sizeIdc][listIdc], fileName.c_str());
4764              return true;
4765            }
4766          }
4767          Int data;
4768          if (fscanf(fp, "%d,", &data)!=1)
4769          {
4770            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));
4771            return true;
4772          }
4773          if (data<0 || data>255)
4774          {
4775            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));
4776            return true;
4777          }
4778          //overwrite DC value when size of matrix is larger than 16x16
4779          setScalingListDC(sizeIdc,listIdc,data);
4780        }
4781      }
4782    }
4783  }
4784//  std::cout << "\n\nRead scaling lists of:\n\n";
4785//  outputScalingLists(std::cout);
4786
4787  fclose(fp);
4788  return false;
4789}
4790
4791#if NH_MV
4792Void TComScalingList::inferFrom( const TComScalingList& srcScLi )
4793{
4794  for(Int sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
4795  {
4796    for(Int listId = 0; listId <  SCALING_LIST_NUM; listId++)
4797    {
4798      setRefMatrixId  (sizeId,listId, srcScLi.getRefMatrixId  (sizeId,listId));
4799      setScalingListDC(sizeId,listId, srcScLi.getScalingListDC(sizeId,listId));         
4800      ::memcpy(getScalingListAddress(sizeId, listId),srcScLi.getScalingListAddress(sizeId, listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
4801    }
4802  }
4803}
4804#endif
4805
4806
4807/** get default address of quantization matrix
4808 * \param sizeId size index
4809 * \param listId list index
4810 * \returns pointer of quantization matrix
4811 */
4812const Int* TComScalingList::getScalingListDefaultAddress(UInt sizeId, UInt listId)
4813{
4814  const Int *src = 0;
4815  switch(sizeId)
4816  {
4817    case SCALING_LIST_4x4:
4818      src = g_quantTSDefault4x4;
4819      break;
4820    case SCALING_LIST_8x8:
4821    case SCALING_LIST_16x16:
4822    case SCALING_LIST_32x32:
4823      src = (listId < (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) ) ? g_quantIntraDefault8x8 : g_quantInterDefault8x8;
4824      break;
4825    default:
4826      assert(0);
4827      src = NULL;
4828      break;
4829  }
4830  return src;
4831}
4832
4833/** process of default matrix
4834 * \param sizeId size index
4835 * \param listId index of input matrix
4836 */
4837Void TComScalingList::processDefaultMatrix(UInt sizeId, UInt listId)
4838{
4839  ::memcpy(getScalingListAddress(sizeId, listId),getScalingListDefaultAddress(sizeId,listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
4840  setScalingListDC(sizeId,listId,SCALING_LIST_DC);
4841}
4842
4843/** check DC value of matrix for default matrix signaling
4844 */
4845Void TComScalingList::checkDcOfMatrix()
4846{
4847  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
4848  {
4849    for(UInt listId = 0; listId < SCALING_LIST_NUM; listId++)
4850    {
4851      //check default matrix?
4852      if(getScalingListDC(sizeId,listId) == 0)
4853      {
4854        processDefaultMatrix(sizeId, listId);
4855      }
4856    }
4857  }
4858}
4859
4860ParameterSetManager::ParameterSetManager()
4861: m_vpsMap(MAX_NUM_VPS)
4862, m_spsMap(MAX_NUM_SPS)
4863, m_ppsMap(MAX_NUM_PPS)
4864#if !NH_MV
4865, m_activeSPSId(-1)
4866#else
4867, m_spsActiveForLayer(MAX_NUM_LAYERS)
4868#endif
4869, m_activeVPSId(-1)
4870{
4871#if NH_MV 
4872  for (Int i = 0; i < MAX_NUM_LAYERS; i++ )
4873  {   
4874    m_activeSPSId[i] = -1; 
4875  }
4876#endif
4877}
4878
4879
4880ParameterSetManager::~ParameterSetManager()
4881{
4882}
4883
4884//! activate a SPS from a active parameter sets SEI message
4885//! \returns true, if activation is successful
4886#if NH_MV
4887//Bool ParameterSetManager::activateSPSWithSEI(Int spsId, Int layerId )
4888#else
4889//Bool ParameterSetManager::activateSPSWithSEI(Int spsId)
4890#endif
4891//{
4892//TComSPS *sps = m_spsMap.getPS(spsId);
4893//  if (sps)
4894//  {
4895//    Int vpsId = sps->getVPSId();
4896//    TComVPS *vps = m_vpsMap.getPS(vpsId);
4897//    if (vps)
4898//    {
4899#if NH_MV
4900//      m_activeVPS = *(vps);
4901//      m_activeSPS[ layerId ] = *(sps);
4902#else
4903//      m_activeVPS = *(vps);
4904//      m_activeSPS = *(sps);
4905#endif
4906//      return true;
4907//    }
4908//    else
4909//    {
4910//      printf("Warning: tried to activate SPS using an Active parameter sets SEI message. Referenced VPS does not exist.");
4911//    }
4912//  }
4913//  else
4914//  {
4915//    printf("Warning: tried to activate non-existing SPS using an Active parameter sets SEI message.");
4916//  }
4917//  return false;
4918//}
4919
4920//! activate a PPS and depending on isIDR parameter also SPS and VPS
4921//! \returns true, if activation is successful
4922#if NH_MV
4923Bool ParameterSetManager::activatePPS(Int ppsId, Bool isIRAP, Int layerId )
4924#else
4925Bool ParameterSetManager::activatePPS(Int ppsId, Bool isIRAP)
4926#endif
4927{
4928  TComPPS *pps = m_ppsMap.getPS(ppsId);
4929  if (pps)
4930  {
4931    Int spsId = pps->getSPSId();
4932#if NH_MV
4933    if (!isIRAP && (spsId != m_activeSPSId[ layerId ] ))
4934#else
4935    if (!isIRAP && (spsId != m_activeSPSId ))
4936#endif
4937    {
4938      printf("Warning: tried to activate PPS referring to a inactive SPS at non-IDR.");
4939    }
4940    else
4941    {
4942      TComSPS *sps = m_spsMap.getPS(spsId);
4943      if (sps)
4944      {
4945        Int vpsId = sps->getVPSId();
4946        if (!isIRAP && (vpsId != m_activeVPSId ))
4947        {
4948          printf("Warning: tried to activate PPS referring to a inactive VPS at non-IDR.");
4949        }
4950        else
4951        {
4952          TComVPS *vps =m_vpsMap.getPS(vpsId);
4953          if (vps)
4954          {
4955            m_activeVPSId = vpsId;
4956#if NH_MV
4957            m_activeSPSId[layerId] = spsId;
4958#else
4959            m_activeSPSId = spsId;
4960#endif
4961            return true;
4962          }
4963          else
4964          {
4965            printf("Warning: tried to activate PPS that refers to a non-existing VPS.");
4966          }
4967        }
4968      }
4969      else
4970      {
4971       printf("Warning: tried to activate a PPS that refers to a non-existing SPS.");
4972      }
4973    }
4974  }
4975  else
4976  {
4977    printf("Warning: tried to activate non-existing PPS.");
4978  }
4979
4980  // Failed to activate if reach here.
4981#if NH_MV
4982  m_activeSPSId[layerId]=-1;
4983#else
4984  m_activeSPSId=-1;
4985#endif
4986  m_activeVPSId=-1;
4987
4988  return false;
4989}
4990
4991template <>
4992Void ParameterSetMap<TComPPS>::setID(TComPPS* parameterSet, const Int psId)
4993{
4994  parameterSet->setPPSId(psId);
4995}
4996
4997template <>
4998Void ParameterSetMap<TComSPS>::setID(TComSPS* parameterSet, const Int psId)
4999{
5000  parameterSet->setSPSId(psId);
5001}
5002
5003ProfileTierLevel::ProfileTierLevel()
5004  : m_profileSpace    (0)
5005  , m_tierFlag        (Level::MAIN)
5006  , m_profileIdc      (Profile::NONE)
5007  , m_levelIdc        (Level::NONE)
5008  , m_progressiveSourceFlag  (false)
5009  , m_interlacedSourceFlag   (false)
5010  , m_nonPackedConstraintFlag(false)
5011  , m_frameOnlyConstraintFlag(false)
5012#if NH_MV
5013  , m_intraConstraintFlag         ( false )
5014  , m_onePictureOnlyConstraintFlag( false )
5015  , m_lowerBitRateConstraintFlag  ( false )
5016  , m_max12bitConstraintFlag      ( false )
5017  , m_max10bitConstraintFlag      ( false )
5018  , m_max8bitConstraintFlag       ( false )
5019  , m_max422chromaConstraintFlag  ( false )
5020  , m_max420chromaConstraintFlag  ( false )
5021  , m_maxMonochromeConstraintFlag ( false ) 
5022  , m_inbldFlag                   ( false )
5023#endif
5024{
5025  ::memset(m_profileCompatibilityFlag, 0, sizeof(m_profileCompatibilityFlag));
5026}
5027
5028#if NH_MV
5029Bool ProfileTierLevel::getV2ConstraintsPresentFlag() const
5030{
5031  return ( 
5032    getProfileIdc( ) ==  4 || getProfileCompatibilityFlag( 4 ) || getProfileIdc( ) ==  5 || getProfileCompatibilityFlag( 5 )  ||
5033    getProfileIdc( ) ==  6 || getProfileCompatibilityFlag( 6 ) || getProfileIdc( ) ==  7 || getProfileCompatibilityFlag( 7 ) 
5034    );
5035}
5036
5037Bool ProfileTierLevel::getInbldPresentFlag() const
5038{
5039  return ( 
5040    ( getProfileIdc() >= 1 && getProfileIdc() <= 5 )  || getProfileCompatibilityFlag( 1 ) || getProfileCompatibilityFlag( 2 ) || 
5041    getProfileCompatibilityFlag( 3 ) || getProfileCompatibilityFlag( 4 )  ||   getProfileCompatibilityFlag( 5 ) 
5042    );
5043}
5044
5045Void ProfileTierLevel::copyV2ConstraintFlags(ProfileTierLevel* ptlRef)
5046{
5047  setMax12bitConstraintFlag         ( ptlRef->getMax12bitConstraintFlag       ( ) );
5048  setMax10bitConstraintFlag         ( ptlRef->getMax10bitConstraintFlag       ( ) );
5049  setMax8bitConstraintFlag          ( ptlRef->getMax8bitConstraintFlag        ( ) );
5050  setMax422chromaConstraintFlag     ( ptlRef->getMax422chromaConstraintFlag   ( ) );
5051  setMax420chromaConstraintFlag     ( ptlRef->getMax420chromaConstraintFlag   ( ) );
5052  setMaxMonochromeConstraintFlag    ( ptlRef->getMaxMonochromeConstraintFlag  ( ) );
5053  setIntraConstraintFlag            ( ptlRef->getIntraConstraintFlag          ( ) );
5054  setOnePictureOnlyConstraintFlag   ( ptlRef->getOnePictureOnlyConstraintFlag ( ) );
5055  setLowerBitRateConstraintFlag     ( ptlRef->getLowerBitRateConstraintFlag   ( ) );
5056}
5057
5058Void ProfileTierLevel::copyProfile(ProfileTierLevel* ptlRef)
5059{
5060  setProfileSpace            ( ptlRef->getProfileSpace              ( ) );
5061  setTierFlag                ( ptlRef->getTierFlag                  ( ) );
5062  setProfileIdc              ( ptlRef->getProfileIdc                ( ) );
5063  for (Int j = 0; j < 32; j++)
5064  {     
5065    setProfileCompatibilityFlag(j, ptlRef->getProfileCompatibilityFlag  ( j ) );           
5066  }
5067  setProgressiveSourceFlag   ( ptlRef->getProgressiveSourceFlag     ( ) );
5068  setInterlacedSourceFlag    ( ptlRef->getInterlacedSourceFlag      ( ) );
5069  setNonPackedConstraintFlag ( ptlRef->getNonPackedConstraintFlag   ( ) );
5070  setFrameOnlyConstraintFlag ( ptlRef->getFrameOnlyConstraintFlag   ( ) );
5071  copyV2ConstraintFlags      ( ptlRef );
5072}
5073#endif
5074
5075TComPTL::TComPTL()
5076{
5077  ::memset(m_subLayerProfilePresentFlag, 0, sizeof(m_subLayerProfilePresentFlag));
5078  ::memset(m_subLayerLevelPresentFlag,   0, sizeof(m_subLayerLevelPresentFlag  ));
5079}
5080
5081Void calculateParameterSetChangedFlag(Bool &bChanged, const std::vector<UChar> *pOldData, const std::vector<UChar> *pNewData)
5082{
5083  if (!bChanged)
5084  {
5085    if ((pOldData==0 && pNewData!=0) || (pOldData!=0 && pNewData==0))
5086    {
5087      bChanged=true;
5088    }
5089    else if (pOldData!=0 && pNewData!=0)
5090    {
5091      // compare the two
5092      if (pOldData->size() != pNewData->size())
5093      {
5094        bChanged=true;
5095      }
5096      else
5097      {
5098        const UChar *pNewDataArray=&(*pNewData)[0];
5099        const UChar *pOldDataArray=&(*pOldData)[0];
5100        if (memcmp(pOldDataArray, pNewDataArray, pOldData->size()))
5101        {
5102          bChanged=true;
5103        }
5104      }
5105    }
5106  }
5107}
5108#if NH_MV
5109Void TComPTL::inferGeneralValues(Bool profilePresentFlag, Int k, TComPTL* refPTL)
5110{
5111  ProfileTierLevel* refProfileTierLevel = NULL; 
5112  if ( k > 0 )
5113  {   
5114    assert( refPTL != NULL);
5115    refProfileTierLevel = refPTL->getGeneralPTL(); 
5116  }
5117
5118  ProfileTierLevel* curProfileTierLevel = getGeneralPTL( ); 
5119  assert( curProfileTierLevel != NULL ); 
5120
5121  if( !profilePresentFlag )
5122  {
5123    assert( k > 0 ); 
5124    assert( refProfileTierLevel != NULL ); 
5125    curProfileTierLevel->copyProfile( refProfileTierLevel);
5126  }
5127  else
5128  {
5129    if ( !curProfileTierLevel->getV2ConstraintsPresentFlag() )
5130    {
5131      curProfileTierLevel->setMax12bitConstraintFlag         ( false );
5132      curProfileTierLevel->setMax10bitConstraintFlag         ( false );
5133      curProfileTierLevel->setMax8bitConstraintFlag          ( false );
5134      curProfileTierLevel->setMax422chromaConstraintFlag     ( false );
5135      curProfileTierLevel->setMax420chromaConstraintFlag     ( false );
5136      curProfileTierLevel->setMaxMonochromeConstraintFlag    ( false );
5137      curProfileTierLevel->setIntraConstraintFlag            ( false );
5138      curProfileTierLevel->setOnePictureOnlyConstraintFlag   ( false );
5139      curProfileTierLevel->setLowerBitRateConstraintFlag     ( false );   
5140    }
5141
5142    if ( !curProfileTierLevel->getInbldPresentFlag() )
5143    {
5144      curProfileTierLevel->setInbldFlag( false ); 
5145    }     
5146  }
5147}
5148
5149Void TComPTL::inferSubLayerValues(Int maxNumSubLayersMinus1, Int k, TComPTL* refPTL)
5150{
5151  assert( k == 0 || refPTL != NULL );   
5152  for (Int i = maxNumSubLayersMinus1; i >= 0; i--)
5153  {
5154    ProfileTierLevel* refProfileTierLevel;
5155    if ( k != 0 )
5156    {
5157      refProfileTierLevel = refPTL->getSubLayerPTL( i );
5158    }
5159    else
5160    {
5161      if ( i == maxNumSubLayersMinus1)     
5162      {
5163        refProfileTierLevel = getGeneralPTL();
5164      }
5165      else
5166      {
5167        refProfileTierLevel = getSubLayerPTL( i + 1 );
5168      }
5169    }   
5170
5171    assert( refProfileTierLevel != NULL ); 
5172    ProfileTierLevel* curProfileTierLevel = getSubLayerPTL( i ); 
5173    assert( curProfileTierLevel != NULL ); 
5174    if( !getSubLayerLevelPresentFlag( i ) )
5175    {
5176      curProfileTierLevel->setLevelIdc( refProfileTierLevel->getLevelIdc() ); 
5177    }
5178
5179    if( !getSubLayerProfilePresentFlag( i ) )
5180    {
5181      curProfileTierLevel->copyProfile( refProfileTierLevel);
5182    }
5183    else
5184    {
5185      if ( !curProfileTierLevel->getV2ConstraintsPresentFlag() )
5186      {
5187        curProfileTierLevel->copyV2ConstraintFlags( refProfileTierLevel ); 
5188      }
5189
5190      if ( !curProfileTierLevel->getInbldPresentFlag() )
5191      {
5192        curProfileTierLevel->setInbldFlag( refProfileTierLevel->getInbldFlag() ); 
5193      }     
5194    }     
5195  }
5196}
5197
5198#endif
5199
5200//! \}
5201
5202#if NH_MV
5203Void TComVPSVUI::init( Int numLayerSets, Int maxNumSubLayers, Int maxNumLayers )
5204{
5205  m_crossLayerIrapAlignedFlag = true; 
5206  m_allLayersIdrAlignedFlag   = false; 
5207  m_bitRatePresentVpsFlag     = false;
5208  m_picRatePresentVpsFlag     = false;
5209
5210  m_bitRatePresentFlag          .resize(numLayerSets); 
5211  m_picRatePresentFlag          .resize(numLayerSets); 
5212  m_avgBitRate                  .resize(numLayerSets); 
5213  m_maxBitRate                  .resize(numLayerSets); 
5214  m_constantPicRateIdc          .resize(numLayerSets); 
5215  m_avgPicRate                  .resize(numLayerSets); 
5216
5217  for ( Int i = 0; i < numLayerSets; i++)
5218  { 
5219    m_bitRatePresentFlag          [i].resize( maxNumSubLayers); 
5220    m_picRatePresentFlag          [i].resize( maxNumSubLayers); 
5221    m_avgBitRate                  [i].resize( maxNumSubLayers); 
5222    m_maxBitRate                  [i].resize( maxNumSubLayers); 
5223    m_constantPicRateIdc          [i].resize( maxNumSubLayers); 
5224    m_avgPicRate                  [i].resize( maxNumSubLayers); 
5225    for ( Int j = 0; j < maxNumSubLayers; j++)
5226    {   
5227      m_bitRatePresentFlag          [i][j] = false;
5228      m_picRatePresentFlag          [i][j] = false;
5229      m_avgBitRate                  [i][j] = -1;
5230      m_maxBitRate                  [i][j] = -1;
5231      m_constantPicRateIdc          [i][j] = -1;
5232      m_avgPicRate                  [i][j] = -1;
5233    }
5234  }
5235
5236  m_ilpRestrictedRefLayersFlag = false;
5237
5238  m_tileBoundariesAlignedFlag             .resize( maxNumLayers );
5239  m_minSpatialSegmentOffsetPlus1          .resize( maxNumLayers );
5240  m_ctuBasedOffsetEnabledFlag             .resize( maxNumLayers );
5241  m_minHorizontalCtuOffsetPlus1           .resize( maxNumLayers );
5242  m_baseLayerParameterSetCompatibilityFlag.resize( maxNumLayers );
5243
5244  for ( Int i = 0; i < maxNumLayers; i++)
5245  {         
5246    m_tileBoundariesAlignedFlag   [i].resize( maxNumLayers );
5247    m_minSpatialSegmentOffsetPlus1[i].resize( maxNumLayers );
5248    m_ctuBasedOffsetEnabledFlag   [i].resize( maxNumLayers );
5249    m_minHorizontalCtuOffsetPlus1 [i].resize( maxNumLayers );
5250    for ( Int j = 0; j < maxNumLayers; j++)
5251    {   
5252      m_tileBoundariesAlignedFlag   [i][j] = false;
5253      m_minSpatialSegmentOffsetPlus1[i][j] = 0;
5254      m_ctuBasedOffsetEnabledFlag   [i][j] = false;
5255      m_minHorizontalCtuOffsetPlus1 [i][j] = -1;
5256    }
5257    m_baseLayerParameterSetCompatibilityFlag[i] = false;
5258  }
5259  m_vpsVuiBspHrdPresentFlag = false; 
5260}
5261
5262Void TComRepFormat::inferChromaAndBitDepth( const TComRepFormat* prevRepFormat )
5263{
5264    setChromaAndBitDepthVpsPresentFlag( prevRepFormat->getChromaAndBitDepthVpsPresentFlag() );
5265    setSeparateColourPlaneVpsFlag     ( prevRepFormat->getSeparateColourPlaneVpsFlag     () );
5266    setBitDepthVpsLumaMinus8          ( prevRepFormat->getBitDepthVpsLumaMinus8          () );
5267    setBitDepthVpsChromaMinus8        ( prevRepFormat->getBitDepthVpsChromaMinus8        () );
5268}
5269
5270Void TComRepFormat::checkInferChromaAndBitDepth( const TComRepFormat* prevRepFormat ) const 
5271{
5272    assert( getChromaAndBitDepthVpsPresentFlag() == prevRepFormat->getChromaAndBitDepthVpsPresentFlag() );
5273    assert( getSeparateColourPlaneVpsFlag     () == prevRepFormat->getSeparateColourPlaneVpsFlag     () );
5274    assert( getBitDepthVpsLumaMinus8          () == prevRepFormat->getBitDepthVpsLumaMinus8          () );
5275    assert( getBitDepthVpsChromaMinus8        () == prevRepFormat->getBitDepthVpsChromaMinus8        () );
5276}
5277
5278Int TComVpsVuiBspHrdParameters::getBspHrdIdxLen( const TComVPS* vps) const
5279{
5280  return gCeilLog2( vps->getNumHrdParameters() + getVpsNumAddHrdParams() );
5281}
5282
5283Void TComVpsVuiBspHrdParameters::createAfterVpsNumAddHrdParams( const TComVPS* vps )
5284{
5285  m_offsetHrdParamIdx = vps->getNumHrdParameters(); 
5286  m_numHrdParam       = vps->getNumHrdParameters() + getVpsNumAddHrdParams() - m_offsetHrdParamIdx;
5287  m_numOls            = vps->getNumOutputLayerSets(); 
5288
5289  m_cprmsAddPresentFlag .resize( m_numHrdParam );
5290  m_numSubLayerHrdMinus1.resize( m_numHrdParam );
5291  m_hrdParameters       .resize( m_numHrdParam );
5292
5293  m_numSignalledPartitioningSchemes .resize( m_numOls ); 
5294  m_numPartitionsInSchemeMinus1     .resize( m_numOls );
5295  m_numBspSchedulesMinus1           .resize( m_numOls ); 
5296  m_bspHrdIdx                       .resize( m_numOls );
5297  m_bspSchedIdx                     .resize( m_numOls );
5298}
5299
5300Void TComVpsVuiBspHrdParameters::createAfterNumSignalledPartitioningSchemes( const TComVPS* vps, Int h )
5301{
5302  m_numPartitionsInSchemeMinus1 [h].resize( getNumSignalledPartitioningSchemes(h) );
5303  m_layerIncludedInPartitionFlag[h].resize( getNumSignalledPartitioningSchemes(h) );   
5304
5305  m_numBspSchedulesMinus1       [h].resize( getNumSignalledPartitioningSchemes(h) + 1 );
5306  for (Int i = 0; i < getNumSignalledPartitioningSchemes(h) + 1; i++)
5307  {
5308    Int tMax = vps->getMaxSubLayersInLayerSetMinus1( m_vps->olsIdxToLsIdx(h) ) + 1;
5309    m_numBspSchedulesMinus1[h][i].resize( tMax );
5310    m_bspHrdIdx            [h][i].resize( tMax );
5311    m_bspSchedIdx          [h][i].resize( tMax );
5312  }
5313}
5314
5315Void TComVpsVuiBspHrdParameters::createAfterNumPartitionsInSchemeMinus1( const TComVPS* vps, Int h, Int j )
5316{
5317  m_layerIncludedInPartitionFlag[h][j].resize( getNumPartitionsInSchemeMinus1(h,j));
5318  for( Int k = 0; k < getNumPartitionsInSchemeMinus1(h,j); k++ )
5319  {
5320    m_layerIncludedInPartitionFlag[h][j][k].resize( m_vps->getNumLayersInIdList( vps->olsIdxToLsIdx(h)));
5321  }
5322}
5323
5324Void TComVpsVuiBspHrdParameters::createAfterNumBspSchedulesMinus1( const TComVPS* vps, Int h, Int i, Int t )
5325{
5326  m_bspSchedIdx[h][i][t].resize( getNumBspSchedulesMinus1( h, i, t ) + 1 );
5327  m_bspHrdIdx  [h][i][t].resize( getNumBspSchedulesMinus1( h, i, t ) + 1 );
5328  for( Int j = 0; j < getNumBspSchedulesMinus1( h, i, t ) + 1; j++ )
5329  {
5330    m_bspSchedIdx[h][i][t][j].resize( getNumPartitionsInSchemeMinus1( h, i ) );
5331    m_bspHrdIdx  [h][i][t][j].resize( getNumPartitionsInSchemeMinus1( h, i ) );
5332  }
5333}
5334
5335
5336Void TComVUI::inferVideoSignalInfo( const TComVPS* vps, Int layerIdCurr )
5337{
5338  if ( layerIdCurr == 0 || !vps->getVpsVuiPresentFlag() ) 
5339  {
5340    return; 
5341  }
5342
5343  const TComVPSVUI* vpsVui = vps->getVPSVUI(); 
5344  assert( vpsVui != NULL ); 
5345
5346  const TComVideoSignalInfo* videoSignalInfo = vpsVui->getVideoSignalInfo( vpsVui->getVpsVideoSignalInfoIdx( vps->getLayerIdInVps( layerIdCurr ) ) ); 
5347  assert( videoSignalInfo != NULL );
5348
5349  setVideoFormat            ( videoSignalInfo->getVideoVpsFormat            () ); 
5350  setVideoFullRangeFlag     ( videoSignalInfo->getVideoFullRangeVpsFlag     () );
5351  setColourPrimaries        ( videoSignalInfo->getColourPrimariesVps        () );
5352  setTransferCharacteristics( videoSignalInfo->getTransferCharacteristicsVps() );
5353  setMatrixCoefficients     ( videoSignalInfo->getMatrixCoeffsVps           () );
5354}
5355
5356Void TComDpbSize::init( Int numOutputLayerSets, Int maxNumLayerIds, Int maxNumSubLayers ) 
5357{
5358  m_subLayerFlagInfoPresentFlag.resize( numOutputLayerSets );
5359  m_subLayerDpbInfoPresentFlag .resize( numOutputLayerSets );
5360  m_maxVpsDecPicBufferingMinus1.resize( numOutputLayerSets ); 
5361  m_maxVpsNumReorderPics       .resize( numOutputLayerSets );
5362  m_maxVpsLatencyIncreasePlus1 .resize( numOutputLayerSets );
5363
5364  for (Int i = 0; i < numOutputLayerSets; i++ )
5365  {     
5366    m_subLayerFlagInfoPresentFlag[i]  = false;
5367
5368    m_subLayerDpbInfoPresentFlag [i].resize( maxNumSubLayers );
5369    m_maxVpsDecPicBufferingMinus1[i].resize( maxNumLayerIds ); 
5370    m_maxVpsNumReorderPics       [i].resize( maxNumSubLayers );
5371    m_maxVpsLatencyIncreasePlus1 [i].resize( maxNumSubLayers );   
5372
5373    for (Int j = 0; j < maxNumSubLayers; j++  )
5374    {       
5375      m_subLayerDpbInfoPresentFlag [i][j] = ( j == 0) ;
5376      m_maxVpsNumReorderPics       [i][j] = 0;
5377      m_maxVpsLatencyIncreasePlus1 [i][j] = 0;
5378    }
5379
5380    for (Int k = 0; k < maxNumLayerIds; k++ )
5381    {
5382      m_maxVpsDecPicBufferingMinus1[i][k].resize( maxNumSubLayers );
5383      for (Int j = 0; j < maxNumSubLayers; j++  )
5384      {       
5385        m_maxVpsDecPicBufferingMinus1[i][k][j] = MIN_INT; 
5386      }
5387    }
5388  }
5389}
5390
5391
5392Int TComDpbSize::getVpsMaxLatencyPictures( Int i, Int j ) const
5393{
5394  return getMaxVpsNumReorderPics( i, j ) + getMaxVpsLatencyIncreasePlus1(i, j) - 1; 
5395}
5396
5397Void Window::scaleOffsets( Int scal )
5398{
5399  if (! m_scaledFlag )
5400  {
5401    m_scaledFlag         = true; 
5402    m_winLeftOffset     *= scal; 
5403    m_winRightOffset    *= scal; 
5404    m_winTopOffset      *= scal; 
5405    m_winBottomOffset   *= scal; 
5406  }
5407}
5408
5409Void TComStRefPicSet::inferRps( Int stRpsIdx, TComSPS* sps, Bool encoder )
5410{
5411  if ( getInterRefPicSetPredictionFlag() )
5412  {
5413    // When inter_ref_pic_set_prediction_flag is equal to 1, the variables DeltaPocS0[ stRpsIdx ][ i ], UsedByCurrPicS0[ stRpsIdx ][ i ],
5414    // NumNegativePics[ stRpsIdx ], DeltaPocS1[ stRpsIdx ][ i ], UsedByCurrPicS1[ stRpsIdx ][ i ] and NumPositivePics[ stRpsIdx ] are
5415    // derived as follows:
5416
5417    Int i = 0;
5418    Int refRpsIdx = getRefRpsIdx( stRpsIdx );
5419    TComStRefPicSet* refRps = sps->getStRefPicSet( refRpsIdx ); 
5420
5421    for( Int j = refRps->getNumPositivePicsVar( ) - 1; j >= 0; j-- ) 
5422    {
5423      Int dPoc = refRps->getDeltaPocS1Var( j ) + getDeltaRps();
5424      if( dPoc < 0  &&  getUseDeltaFlag( refRps->getNumNegativePicsVar( ) + j ) ) 
5425      {
5426        setDeltaPocS0Var     ( i, dPoc );
5427        setUsedByCurrPicS0Var( i++ , getUsedByCurrPicFlag( refRps->getNumNegativePicsVar( ) + j ) );
5428      }
5429    }
5430    if( getDeltaRps() < 0  && getUseDeltaFlag( refRps->getNumDeltaPocs() ) )   //   (7 59)
5431    {
5432      setDeltaPocS0Var( i,  getDeltaRps() ); 
5433      setUsedByCurrPicS0Var( i++ , getUsedByCurrPicFlag( refRps->getNumDeltaPocs() ) );
5434    }
5435    for( Int j = 0; j < refRps->getNumNegativePicsVar(); j++ )
5436    {
5437      Int dPoc = refRps->getDeltaPocS0Var( j ) + getDeltaRps(); 
5438      if( dPoc < 0  &&  getUseDeltaFlag( j ) ) 
5439      {
5440        setDeltaPocS0Var( i , dPoc);
5441        setUsedByCurrPicS0Var( i++ , getUsedByCurrPicFlag( j )) ;
5442      }
5443    }
5444
5445    setNumNegativePicsVar( i );
5446
5447    i = 0;
5448    for( Int j = refRps->getNumNegativePicsVar() - 1; j  >=  0; j-- )
5449    {
5450      Int dPoc = refRps->getDeltaPocS0Var( j ) + getDeltaRps(); 
5451      if( dPoc > 0  &&  getUseDeltaFlag( j ) )
5452      {
5453        setDeltaPocS1Var( i, dPoc );
5454        setUsedByCurrPicS1Var(  i++, getUsedByCurrPicFlag( j ) ) ;
5455      }
5456    }
5457
5458    if( getDeltaRps() > 0  &&  getUseDeltaFlag( refRps->getNumDeltaPocs() ) ) //  (7 60)
5459    { 
5460      setDeltaPocS1Var( i , getDeltaRps() );
5461      setUsedByCurrPicS1Var( i++ , getUsedByCurrPicFlag( refRps->getNumDeltaPocs() ));
5462    }
5463
5464    for( Int j = 0; j < refRps->getNumPositivePicsVar( ); j++) 
5465    {
5466      Int dPoc = refRps->getDeltaPocS1Var( j ) + getDeltaRps(); 
5467      if( dPoc > 0  &&  getUseDeltaFlag( refRps->getNumNegativePicsVar() + j ) ) 
5468      {
5469        setDeltaPocS1Var( i, dPoc);
5470        setUsedByCurrPicS1Var( i++, getUsedByCurrPicFlag( refRps->getNumNegativePicsVar() + j ));
5471      }
5472    }
5473    setNumPositivePicsVar(  i );
5474  }
5475  else
5476  {
5477    // When inter_ref_pic_set_prediction_flag is equal to 0, the variables NumNegativePics[ stRpsIdx ], NumPositivePics[ stRpsIdx ],
5478    // UsedByCurrPicS0[ stRpsIdx ][ i ], UsedByCurrPicS1[ stRpsIdx ][ i ], DeltaPocS0[ stRpsIdx ][ i ] and DeltaPocS1[ stRpsIdx ][ i ]
5479    // are derived as follows:
5480
5481    setNumNegativePicsVar( getNumNegativePics( ) );        //  (7 61)
5482    setNumPositivePicsVar( getNumPositivePics( ) );         //  (7 62)
5483
5484    for (Int i = 0 ; i < getNumNegativePics(); i++ )
5485    {     
5486      setUsedByCurrPicS0Var( i,  getUsedByCurrPicS0Flag( i ) ); //  (7 63)
5487      if (i == 0 )
5488      {
5489        setDeltaPocS0Var( i , -( getDeltaPocS0Minus1( i ) + 1 )); // (7 65)
5490      }
5491      else
5492      {
5493        setDeltaPocS0Var( i , getDeltaPocS0Var( i - 1 ) - ( getDeltaPocS0Minus1( i ) + 1 )); //  (7 67)
5494      }
5495    }
5496
5497    for (Int i = 0 ; i < getNumPositivePics(); i++ )
5498    {     
5499      setUsedByCurrPicS1Var( i,  getUsedByCurrPicS1Flag( i ) ); //  (7 64)
5500
5501      if (i == 0 )
5502      {
5503        setDeltaPocS1Var( i , getDeltaPocS1Minus1( i ) + 1    );      // (7 66)
5504      }
5505      else
5506      {
5507        setDeltaPocS1Var( i , getDeltaPocS1Var( i - 1 ) + ( getDeltaPocS1Minus1( i ) + 1 )); //  (7 68)
5508      }
5509    }
5510  }
5511}
5512
5513#endif
Note: See TracBrowser for help on using the repository browser.