source: 3DVCSoftware/branches/HTM-11.2-dev0/source/Lib/TLibCommon/TComSlice.cpp @ 1030

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

Merged 11.2-dev2-Samsung@1026.

  • Property svn:eol-style set to native
File size: 132.5 KB
Line 
1/* The copyright in this software is being made available under the BSD
2 * License, included below. This software may be subject to other third party
3 * and contributor rights, including patent rights, and no such rights are
4 * granted under this license. 
5 *
6* Copyright (c) 2010-2014, ITU/ISO/IEC
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
11 *
12 *  * Redistributions of source code must retain the above copyright notice,
13 *    this list of conditions and the following disclaimer.
14 *  * Redistributions in binary form must reproduce the above copyright notice,
15 *    this list of conditions and the following disclaimer in the documentation
16 *    and/or other materials provided with the distribution.
17 *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
18 *    be used to endorse or promote products derived from this software without
19 *    specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31 * THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34/** \file     TComSlice.cpp
35    \brief    slice header and SPS class
36*/
37
38#include "CommonDef.h"
39#include "TComSlice.h"
40#include "TComPic.h"
41#include "TLibEncoder/TEncSbac.h"
42#include "TLibDecoder/TDecSbac.h"
43
44//! \ingroup TLibCommon
45//! \{
46
47
48TComSlice::TComSlice()
49: m_iPPSId                        ( -1 )
50#if H_MV
51, m_slicePicOrderCntLsb           ( 0 )
52#endif
53, m_iPOC                          ( 0 )
54, m_iLastIDR                      ( 0 )
55, m_eNalUnitType                  ( NAL_UNIT_CODED_SLICE_IDR_W_RADL )
56, m_eSliceType                    ( I_SLICE )
57, m_iSliceQp                      ( 0 )
58, m_dependentSliceSegmentFlag            ( false )
59#if ADAPTIVE_QP_SELECTION
60, m_iSliceQpBase                  ( 0 )
61#endif
62, m_deblockingFilterDisable        ( false )
63, m_deblockingFilterOverrideFlag   ( false )
64, m_deblockingFilterBetaOffsetDiv2 ( 0 )
65, m_deblockingFilterTcOffsetDiv2   ( 0 )
66, m_bCheckLDC                     ( false )
67, m_iSliceQpDelta                 ( 0 )
68, m_iSliceQpDeltaCb               ( 0 )
69, m_iSliceQpDeltaCr               ( 0 )
70, m_iDepth                        ( 0 )
71, m_bRefenced                     ( false )
72, m_pcSPS                         ( NULL )
73, m_pcPPS                         ( NULL )
74, m_pcPic                         ( NULL )
75, m_colFromL0Flag                 ( 1 )
76#if SETTING_NO_OUT_PIC_PRIOR
77, m_noOutputPriorPicsFlag         ( false )
78, m_noRaslOutputFlag              ( false )
79, m_handleCraAsBlaFlag              ( false )
80#endif
81, m_colRefIdx                     ( 0 )
82, m_uiTLayer                      ( 0 )
83, m_bTLayerSwitchingFlag          ( false )
84, m_sliceMode                   ( 0 )
85, m_sliceArgument               ( 0 )
86, m_sliceCurStartCUAddr         ( 0 )
87, m_sliceCurEndCUAddr           ( 0 )
88, m_sliceIdx                    ( 0 )
89, m_sliceSegmentMode            ( 0 )
90, m_sliceSegmentArgument        ( 0 )
91, m_sliceSegmentCurStartCUAddr  ( 0 )
92, m_sliceSegmentCurEndCUAddr    ( 0 )
93, m_nextSlice                    ( false )
94, m_nextSliceSegment             ( false )
95, m_sliceBits                   ( 0 )
96, m_sliceSegmentBits         ( 0 )
97, m_bFinalized                    ( false )
98, m_uiTileOffstForMultES          ( 0 )
99, m_puiSubstreamSizes             ( NULL )
100, m_cabacInitFlag                 ( false )
101, m_bLMvdL1Zero                   ( false )
102, m_numEntryPointOffsets          ( 0 )
103, m_temporalLayerNonReferenceFlag ( false )
104, m_enableTMVPFlag                ( true )
105#if H_MV
106, m_refPicSetInterLayer0           ( NULL )
107, m_refPicSetInterLayer1           ( NULL )
108, m_layerId                       (0)
109, m_viewId                        (0)
110, m_viewIndex                     (0)
111#if H_3D
112, m_isDepth                       (false)
113#endif
114#if !H_MV_HLS7_GEN
115, m_pocResetFlag                  (false)
116#endif
117#if H_MV
118, m_crossLayerBlaFlag             (false)
119#endif
120, m_discardableFlag               (false)
121, m_interLayerPredEnabledFlag     (false)
122, m_numInterLayerRefPicsMinus1    (0)
123#if H_MV
124, m_sliceSegmentHeaderExtensionLength (0)
125, m_pocResetIdc                       (0)
126, m_pocResetPeriodId                  (0)
127, m_fullPocResetFlag                  (false)
128, m_pocLsbVal                         (0)
129, m_pocMsbValPresentFlag              (false)
130, m_pocMsbVal                         (0)
131, m_pocMsbValRequiredFlag         ( false )
132#endif
133#if H_3D_IC
134, m_bApplyIC                      ( false )
135, m_icSkipParseFlag               ( false )
136#endif
137#if H_3D
138, m_depthToDisparityB             ( NULL )
139, m_depthToDisparityF             ( NULL )
140#endif
141#if MTK_SINGLE_DEPTH_MODE_I0095
142, m_bApplySingleDepthMode         (false)
143#endif
144#endif
145{
146  m_aiNumRefIdx[0] = m_aiNumRefIdx[1] = 0;
147 
148  initEqualRef();
149 
150  for (Int component = 0; component < 3; component++)
151  {
152    m_lambdas[component] = 0.0;
153  }
154 
155  for ( Int idx = 0; idx < MAX_NUM_REF; idx++ )
156  {
157    m_list1IdxToList0Idx[idx] = -1;
158  }
159  for(Int iNumCount = 0; iNumCount < MAX_NUM_REF; iNumCount++)
160  {
161    m_apcRefPicList [0][iNumCount] = NULL;
162    m_apcRefPicList [1][iNumCount] = NULL;
163    m_aiRefPOCList  [0][iNumCount] = 0;
164    m_aiRefPOCList  [1][iNumCount] = 0;
165#if H_MV
166    m_aiRefLayerIdList[0][iNumCount] = 0;
167    m_aiRefLayerIdList[1][iNumCount] = 0;
168#endif
169  }
170  resetWpScaling();
171  initWpAcDcParam();
172  m_saoEnabledFlag = false;
173  m_saoEnabledFlagChroma = false;
174#if H_MV
175  for (Int i = 0; i < MAX_NUM_LAYERS; i++ )
176  {
177    m_interLayerPredLayerIdc[ i ] = -1;
178  }
179#endif
180}
181
182TComSlice::~TComSlice()
183{
184  delete[] m_puiSubstreamSizes;
185  m_puiSubstreamSizes = NULL;
186#if H_3D
187  for( UInt i = 0; i < getViewIndex(); i++ )
188  {
189    if ( m_depthToDisparityB && m_depthToDisparityB[ i ] )
190    {
191      delete[] m_depthToDisparityB [ i ];
192    }
193
194    if ( m_depthToDisparityF && m_depthToDisparityF[ i ] ) 
195    {
196      delete[] m_depthToDisparityF [ i ];
197  }
198  }
199
200  if ( m_depthToDisparityF )
201  {
202    delete[] m_depthToDisparityF; 
203  }
204
205  m_depthToDisparityF = NULL;
206
207  if ( m_depthToDisparityB )
208    delete[] m_depthToDisparityB; 
209
210  m_depthToDisparityB = NULL;
211#endif
212}
213
214
215Void TComSlice::initSlice()
216{
217  m_aiNumRefIdx[0]      = 0;
218  m_aiNumRefIdx[1]      = 0;
219 
220  m_colFromL0Flag = 1;
221 
222  m_colRefIdx = 0;
223  initEqualRef();
224  m_bCheckLDC = false;
225  m_iSliceQpDeltaCb = 0;
226  m_iSliceQpDeltaCr = 0;
227
228#if H_3D_IV_MERGE
229  m_maxNumMergeCand = MRG_MAX_NUM_CANDS_MEM;
230#else
231  m_maxNumMergeCand = MRG_MAX_NUM_CANDS;
232#endif
233
234  m_bFinalized=false;
235
236  m_tileByteLocation.clear();
237  m_cabacInitFlag        = false;
238  m_numEntryPointOffsets = 0;
239  m_enableTMVPFlag = true;
240#if H_3D_TMVP
241  m_aiAlterRefIdx[0]                  = -1;
242  m_aiAlterRefIdx[1]                  = -1;
243#endif
244}
245
246Bool TComSlice::getRapPicFlag()
247{
248  return getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
249      || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
250      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
251      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
252      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
253      || getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA;
254}
255
256/**
257 - allocate table to contain substream sizes to be written to the slice header.
258 .
259 \param uiNumSubstreams Number of substreams -- the allocation will be this value - 1.
260 */
261Void  TComSlice::allocSubstreamSizes(UInt uiNumSubstreams)
262{
263  delete[] m_puiSubstreamSizes;
264  m_puiSubstreamSizes = new UInt[uiNumSubstreams > 0 ? uiNumSubstreams-1 : 0];
265}
266
267Void  TComSlice::sortPicList        (TComList<TComPic*>& rcListPic)
268{
269  TComPic*    pcPicExtract;
270  TComPic*    pcPicInsert;
271 
272  TComList<TComPic*>::iterator    iterPicExtract;
273  TComList<TComPic*>::iterator    iterPicExtract_1;
274  TComList<TComPic*>::iterator    iterPicInsert;
275 
276  for (Int i = 1; i < (Int)(rcListPic.size()); i++)
277  {
278    iterPicExtract = rcListPic.begin();
279    for (Int j = 0; j < i; j++) iterPicExtract++;
280    pcPicExtract = *(iterPicExtract);
281    pcPicExtract->setCurrSliceIdx(0);
282   
283    iterPicInsert = rcListPic.begin();
284    while (iterPicInsert != iterPicExtract)
285    {
286      pcPicInsert = *(iterPicInsert);
287      pcPicInsert->setCurrSliceIdx(0);
288      if (pcPicInsert->getPOC() >= pcPicExtract->getPOC())
289      {
290        break;
291      }
292     
293      iterPicInsert++;
294    }
295   
296    iterPicExtract_1 = iterPicExtract;    iterPicExtract_1++;
297   
298    //  swap iterPicExtract and iterPicInsert, iterPicExtract = curr. / iterPicInsert = insertion position
299    rcListPic.insert (iterPicInsert, iterPicExtract, iterPicExtract_1);
300    rcListPic.erase  (iterPicExtract);
301  }
302}
303
304TComPic* TComSlice::xGetRefPic (TComList<TComPic*>& rcListPic,
305                                Int                 poc)
306{
307  TComList<TComPic*>::iterator  iterPic = rcListPic.begin(); 
308  TComPic*                      pcPic = *(iterPic);
309  while ( iterPic != rcListPic.end() )
310  {
311    if(pcPic->getPOC() == poc)
312    {
313      break;
314    }
315    iterPic++;
316    pcPic = *(iterPic);
317  }
318  return  pcPic;
319}
320
321
322TComPic* TComSlice::xGetLongTermRefPic(TComList<TComPic*>& rcListPic, Int poc, Bool pocHasMsb)
323{
324  TComList<TComPic*>::iterator  iterPic = rcListPic.begin(); 
325  TComPic*                      pcPic = *(iterPic);
326  TComPic*                      pcStPic = pcPic;
327 
328  Int pocCycle = 1 << getSPS()->getBitsForPOC();
329  if (!pocHasMsb)
330  {
331    poc = poc & (pocCycle - 1);
332  }
333 
334  while ( iterPic != rcListPic.end() )
335  {
336    pcPic = *(iterPic);
337    if (pcPic && pcPic->getPOC()!=this->getPOC() && pcPic->getSlice( 0 )->isReferenced())
338    {
339      Int picPoc = pcPic->getPOC();
340      if (!pocHasMsb)
341      {
342        picPoc = picPoc & (pocCycle - 1);
343      }
344     
345      if (poc == picPoc)
346    {
347      if(pcPic->getIsLongTerm())
348      {
349        return pcPic;
350      }
351      else
352      {
353        pcStPic = pcPic;
354      }
355      break;
356    }
357    }
358
359    iterPic++;
360  }
361 
362  return  pcStPic;
363}
364
365Void TComSlice::setRefPOCList       ()
366{
367  for (Int iDir = 0; iDir < 2; iDir++)
368  {
369    for (Int iNumRefIdx = 0; iNumRefIdx < m_aiNumRefIdx[iDir]; iNumRefIdx++)
370    {
371      m_aiRefPOCList[iDir][iNumRefIdx] = m_apcRefPicList[iDir][iNumRefIdx]->getPOC();
372#if H_MV
373      m_aiRefLayerIdList[iDir][iNumRefIdx] = m_apcRefPicList[iDir][iNumRefIdx]->getLayerId();
374#endif
375    }
376  }
377
378}
379
380Void TComSlice::setList1IdxToList0Idx()
381{
382  Int idxL0, idxL1;
383  for ( idxL1 = 0; idxL1 < getNumRefIdx( REF_PIC_LIST_1 ); idxL1++ )
384  {
385    m_list1IdxToList0Idx[idxL1] = -1;
386    for ( idxL0 = 0; idxL0 < getNumRefIdx( REF_PIC_LIST_0 ); idxL0++ )
387    {
388      if ( m_apcRefPicList[REF_PIC_LIST_0][idxL0]->getPOC() == m_apcRefPicList[REF_PIC_LIST_1][idxL1]->getPOC() )
389      {
390        m_list1IdxToList0Idx[idxL1] = idxL0;
391        break;
392      }
393    }
394  }
395}
396
397#if !H_MV
398Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr )
399{
400  if (!checkNumPocTotalCurr)
401  {
402    if (m_eSliceType == I_SLICE)
403    {
404      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
405      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
406
407      return;
408    }
409
410    m_aiNumRefIdx[0] = getNumRefIdx(REF_PIC_LIST_0);
411    m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
412  }
413
414  TComPic*  pcRefPic= NULL;
415  TComPic*  RefPicSetStCurr0[16];
416  TComPic*  RefPicSetStCurr1[16];
417  TComPic*  RefPicSetLtCurr[16];
418  UInt NumPocStCurr0 = 0;
419  UInt NumPocStCurr1 = 0;
420  UInt NumPocLtCurr = 0;
421  Int i;
422
423  for(i=0; i < m_pcRPS->getNumberOfNegativePictures(); i++)
424  {
425    if(m_pcRPS->getUsed(i))
426    {
427      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pcRPS->getDeltaPOC(i));
428      pcRefPic->setIsLongTerm(0);
429      pcRefPic->getPicYuvRec()->extendPicBorder();
430      RefPicSetStCurr0[NumPocStCurr0] = pcRefPic;
431      NumPocStCurr0++;
432      pcRefPic->setCheckLTMSBPresent(false); 
433    }
434  }
435
436  for(; i < m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures(); i++)
437  {
438    if(m_pcRPS->getUsed(i))
439    {
440      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pcRPS->getDeltaPOC(i));
441      pcRefPic->setIsLongTerm(0);
442      pcRefPic->getPicYuvRec()->extendPicBorder();
443      RefPicSetStCurr1[NumPocStCurr1] = pcRefPic;
444      NumPocStCurr1++;
445      pcRefPic->setCheckLTMSBPresent(false); 
446    }
447  }
448
449  for(i = m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()+m_pcRPS->getNumberOfLongtermPictures()-1; i > m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()-1 ; i--)
450  {
451    if(m_pcRPS->getUsed(i))
452    {
453      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i), m_pcRPS->getCheckLTMSBPresent(i));
454      pcRefPic->setIsLongTerm(1);
455      pcRefPic->getPicYuvRec()->extendPicBorder();
456      RefPicSetLtCurr[NumPocLtCurr] = pcRefPic;
457      NumPocLtCurr++;
458    }
459    if(pcRefPic==NULL) 
460    {
461      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i), m_pcRPS->getCheckLTMSBPresent(i));
462    }
463    pcRefPic->setCheckLTMSBPresent(m_pcRPS->getCheckLTMSBPresent(i)); 
464  }
465
466  // ref_pic_list_init
467  TComPic*  rpsCurrList0[MAX_NUM_REF+1];
468  TComPic*  rpsCurrList1[MAX_NUM_REF+1];
469  Int numPocTotalCurr = NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr;
470  if (checkNumPocTotalCurr)
471  {
472    // 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:
473    // - If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
474    // - Otherwise, when the current picture contains a P or B slice, the value of NumPocTotalCurr shall not be equal to 0.
475    if (getRapPicFlag())
476    {
477      assert(numPocTotalCurr == 0);
478    }
479
480    if (m_eSliceType == I_SLICE)
481    {
482      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
483      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
484
485      return;
486    }
487
488    assert(numPocTotalCurr > 0);
489
490    m_aiNumRefIdx[0] = getNumRefIdx(REF_PIC_LIST_0);
491    m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
492  }
493
494  Int cIdx = 0;
495  for ( i=0; i<NumPocStCurr0; i++, cIdx++)
496  {
497    rpsCurrList0[cIdx] = RefPicSetStCurr0[i];
498  }
499  for ( i=0; i<NumPocStCurr1; i++, cIdx++)
500  {
501    rpsCurrList0[cIdx] = RefPicSetStCurr1[i];
502  }
503  for ( i=0; i<NumPocLtCurr;  i++, cIdx++)
504  {
505    rpsCurrList0[cIdx] = RefPicSetLtCurr[i];
506  }
507  assert(cIdx == numPocTotalCurr);
508
509  if (m_eSliceType==B_SLICE)
510  {
511    cIdx = 0;
512    for ( i=0; i<NumPocStCurr1; i++, cIdx++)
513    {
514      rpsCurrList1[cIdx] = RefPicSetStCurr1[i];
515    }
516    for ( i=0; i<NumPocStCurr0; i++, cIdx++)
517    {
518      rpsCurrList1[cIdx] = RefPicSetStCurr0[i];
519    }
520    for ( i=0; i<NumPocLtCurr;  i++, cIdx++)
521    {
522      rpsCurrList1[cIdx] = RefPicSetLtCurr[i];
523    }
524    assert(cIdx == numPocTotalCurr);
525  }
526
527  ::memset(m_bIsUsedAsLongTerm, 0, sizeof(m_bIsUsedAsLongTerm));
528
529  for (Int rIdx = 0; rIdx < m_aiNumRefIdx[0]; rIdx ++)
530  {
531    cIdx = m_RefPicListModification.getRefPicListModificationFlagL0() ? m_RefPicListModification.getRefPicSetIdxL0(rIdx) : rIdx % numPocTotalCurr;
532    assert(cIdx >= 0 && cIdx < numPocTotalCurr);
533    m_apcRefPicList[0][rIdx] = rpsCurrList0[ cIdx ];
534    m_bIsUsedAsLongTerm[0][rIdx] = ( cIdx >= NumPocStCurr0 + NumPocStCurr1 );
535  }
536  if ( m_eSliceType != B_SLICE )
537  {
538    m_aiNumRefIdx[1] = 0;
539    ::memset( m_apcRefPicList[1], 0, sizeof(m_apcRefPicList[1]));
540  }
541  else
542  {
543    for (Int rIdx = 0; rIdx < m_aiNumRefIdx[1]; rIdx ++)
544    {
545      cIdx = m_RefPicListModification.getRefPicListModificationFlagL1() ? m_RefPicListModification.getRefPicSetIdxL1(rIdx) : rIdx % numPocTotalCurr;
546      assert(cIdx >= 0 && cIdx < numPocTotalCurr);
547      m_apcRefPicList[1][rIdx] = rpsCurrList1[ cIdx ];
548      m_bIsUsedAsLongTerm[1][rIdx] = ( cIdx >= NumPocStCurr0 + NumPocStCurr1 );
549    }
550  }
551}
552
553#else
554Void TComSlice::getTempRefPicLists( TComList<TComPic*>& rcListPic, std::vector<TComPic*>& refPicSetInterLayer0, std::vector<TComPic*>& refPicSetInterLayer1,                                     
555                                   std::vector<TComPic*> rpsCurrList[2], std::vector<Bool> usedAsLongTerm[2], Int& numPocTotalCurr, Bool checkNumPocTotalCurr )
556{
557  if (!checkNumPocTotalCurr)
558  {
559    if (m_eSliceType == I_SLICE)
560    {     
561      return;
562    }   
563  }
564
565  TComPic*  pcRefPic= NULL;
566  TComPic*  RefPicSetStCurr0[16];
567  TComPic*  RefPicSetStCurr1[16];
568  TComPic*  RefPicSetLtCurr[16];
569  UInt NumPocStCurr0 = 0;
570  UInt NumPocStCurr1 = 0;
571  UInt NumPocLtCurr = 0;
572  Int i;
573
574  for(i=0; i < m_pcRPS->getNumberOfNegativePictures(); i++)
575  {
576    if(m_pcRPS->getUsed(i))
577    {
578      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pcRPS->getDeltaPOC(i));
579      pcRefPic->setIsLongTerm(0);
580      pcRefPic->getPicYuvRec()->extendPicBorder();
581      RefPicSetStCurr0[NumPocStCurr0] = pcRefPic;
582      NumPocStCurr0++;
583      pcRefPic->setCheckLTMSBPresent(false); 
584    }
585  }
586 
587  for(; i < m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures(); i++)
588  {
589    if(m_pcRPS->getUsed(i))
590    {
591      pcRefPic = xGetRefPic(rcListPic, getPOC()+m_pcRPS->getDeltaPOC(i));
592      pcRefPic->setIsLongTerm(0);
593      pcRefPic->getPicYuvRec()->extendPicBorder();
594      RefPicSetStCurr1[NumPocStCurr1] = pcRefPic;
595      NumPocStCurr1++;
596      pcRefPic->setCheckLTMSBPresent(false); 
597    }
598  }
599 
600  for(i = m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()+m_pcRPS->getNumberOfLongtermPictures()-1; i > m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()-1 ; i--)
601  {
602    if(m_pcRPS->getUsed(i))
603    {
604      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i), m_pcRPS->getCheckLTMSBPresent(i));
605      pcRefPic->setIsLongTerm(1);
606      pcRefPic->getPicYuvRec()->extendPicBorder();
607      RefPicSetLtCurr[NumPocLtCurr] = pcRefPic;
608      NumPocLtCurr++;
609    }
610    if(pcRefPic==NULL) 
611    {
612      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i), m_pcRPS->getCheckLTMSBPresent(i));
613    }
614    pcRefPic->setCheckLTMSBPresent(m_pcRPS->getCheckLTMSBPresent(i)); 
615  }
616
617  Int numPocInterCurr = NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr; 
618  numPocTotalCurr = numPocInterCurr + getNumActiveRefLayerPics( );
619  assert( numPocTotalCurr == getNumRpsCurrTempList() );
620
621  if (checkNumPocTotalCurr)
622  {
623    // 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:
624    // - 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.
625    // - Otherwise, when the current picture contains a P or B slice, the value of NumPocTotalCurr shall not be equal to 0.
626    if ( getRapPicFlag() && m_layerId == 0 )
627    {
628      assert(numPocTotalCurr == 0);
629    }
630
631    if (m_eSliceType == I_SLICE)
632    {
633      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
634      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
635     
636      return;
637    }
638   
639    assert(numPocTotalCurr > 0);
640   
641    m_aiNumRefIdx[0] = getNumRefIdx(REF_PIC_LIST_0);
642    m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
643  }
644
645  std::vector<TComPic*>* refPicSetInterLayer[2] = { &refPicSetInterLayer0, &refPicSetInterLayer1}; 
646  Int numPocInterLayer[2] = { getNumActiveRefLayerPics0( ), getNumActiveRefLayerPics1( ) }; 
647 
648  TComPic**             refPicSetStCurr    [2] = { RefPicSetStCurr0, RefPicSetStCurr1 };
649#if FIX_WARNING
650  Int numPocStCurr[2] = { (Int)NumPocStCurr0, (Int)NumPocStCurr1 }; 
651#else
652  Int numPocStCurr[2] = { NumPocStCurr0, NumPocStCurr1 }; 
653#endif
654
655  for (Int li = 0; li < ((m_eSliceType==B_SLICE) ? 2 : 1); li++)
656  { 
657    rpsCurrList   [li].resize(MAX_NUM_REF+1,NULL ); 
658    usedAsLongTerm[li].resize(MAX_NUM_REF+1,false); 
659
660    Int cIdx = 0;
661    for ( i=0; i < numPocStCurr[li]; i++, cIdx++)
662    {
663      rpsCurrList[li][cIdx] = refPicSetStCurr[li][i];
664      usedAsLongTerm [li][cIdx] = false; 
665    }
666
667    for ( i=0; i < numPocInterLayer[li];  i++, cIdx++)
668    {   
669      rpsCurrList[li][cIdx] = (*refPicSetInterLayer[li])[i];
670      usedAsLongTerm [li][cIdx] = true; 
671    }
672
673    for ( i=0; i < numPocStCurr[1-li]; i++, cIdx++)
674    {
675      rpsCurrList[li][cIdx] = refPicSetStCurr[1-li][i];
676      usedAsLongTerm [li][cIdx] = false; 
677    }
678
679    for ( i=0; i<NumPocLtCurr;  i++, cIdx++)
680    {
681      rpsCurrList[li][cIdx] = RefPicSetLtCurr[i];
682      usedAsLongTerm [li][cIdx] = true; 
683    }
684
685    for ( i=0; i < numPocInterLayer[1-li];  i++, cIdx++)
686    {   
687      assert( cIdx < MAX_NUM_REF );   
688      rpsCurrList[li][cIdx] = (*refPicSetInterLayer[1-li])[i];
689      usedAsLongTerm [li][cIdx] = true; 
690    }
691
692    assert(cIdx == numPocTotalCurr);
693  }
694}
695
696Void TComSlice::setRefPicList( std::vector<TComPic*> rpsCurrList[2], std::vector<Bool> usedAsLongTerm[2], Int numPocTotalCurr, Bool checkNumPocTotalCurr )
697
698{
699  if (!checkNumPocTotalCurr)
700  {
701    if (m_eSliceType == I_SLICE)
702    {
703      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
704      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
705
706      return;
707    }   
708  }
709
710  ::memset(m_bIsUsedAsLongTerm, 0, sizeof(m_bIsUsedAsLongTerm));
711
712  for (Int li = 0; li < 2; li++)
713  {
714    if ( m_eSliceType == P_SLICE && li == 1 )
715    {
716      m_aiNumRefIdx[1] = 0;
717      ::memset( m_apcRefPicList[1], 0, sizeof(m_apcRefPicList[1]));
718    } 
719    else
720    {
721      for (Int rIdx = 0; rIdx <= (m_aiNumRefIdx[ li ] - 1 ); rIdx ++)
722      { 
723        Bool listModified             =                m_RefPicListModification.getRefPicListModificationFlagL( li ); 
724        Int orgIdx                    = listModified ? m_RefPicListModification.getRefPicSetIdxL(li, rIdx) : (rIdx % numPocTotalCurr); 
725
726        assert( rpsCurrList[li][ orgIdx ] != NULL ); 
727        m_apcRefPicList    [li][rIdx] = rpsCurrList    [li][ orgIdx ];
728        m_bIsUsedAsLongTerm[li][rIdx] = usedAsLongTerm [li][ orgIdx ] ; 
729      }
730    }
731  }
732}
733#endif
734Int TComSlice::getNumRpsCurrTempList()
735{
736  Int numRpsCurrTempList = 0;
737
738  if (m_eSliceType == I_SLICE) 
739  {
740    return 0;
741  }
742  for(UInt i=0; i < m_pcRPS->getNumberOfNegativePictures()+ m_pcRPS->getNumberOfPositivePictures() + m_pcRPS->getNumberOfLongtermPictures(); i++)
743  {
744    if(m_pcRPS->getUsed(i))
745    {
746      numRpsCurrTempList++;
747    }
748  }
749#if H_MV
750  numRpsCurrTempList = numRpsCurrTempList + getNumActiveRefLayerPics();
751#endif
752  return numRpsCurrTempList;
753}
754
755Void TComSlice::initEqualRef()
756{
757  for (Int iDir = 0; iDir < 2; iDir++)
758  {
759    for (Int iRefIdx1 = 0; iRefIdx1 < MAX_NUM_REF; iRefIdx1++)
760    {
761      for (Int iRefIdx2 = iRefIdx1; iRefIdx2 < MAX_NUM_REF; iRefIdx2++)
762      {
763        m_abEqualRef[iDir][iRefIdx1][iRefIdx2] = m_abEqualRef[iDir][iRefIdx2][iRefIdx1] = (iRefIdx1 == iRefIdx2? true : false);
764      }
765    }
766  }
767}
768#if H_3D
769#if H_3D_TMVP
770Void TComSlice::generateAlterRefforTMVP()
771{
772  for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
773  {       
774    if ( this->getNumRefIdx( RefPicList( uiRefListIdx ) ) == 0)
775    {
776        continue;
777    }
778    Bool bZeroIdxLtFlag = this->getRefPic(RefPicList(uiRefListIdx), 0)->getIsLongTerm();
779    for(Int i = 1; i < this->getNumRefIdx(RefPicList(uiRefListIdx)); i++ )
780    {
781      if ( ( bZeroIdxLtFlag && !this->getRefPic(RefPicList(uiRefListIdx), i)->getIsLongTerm() ) ||
782           (!bZeroIdxLtFlag &&  this->getRefPic(RefPicList(uiRefListIdx), i)->getIsLongTerm() ) )
783      {
784        this->setAlterRefIdx(RefPicList(uiRefListIdx),i);
785        break;
786      }
787    }
788  }
789}
790#endif
791Void TComSlice::setCamparaSlice( Int** aaiScale, Int** aaiOffset )
792{ 
793  if( m_pcVPS->hasCamParInSliceHeader( m_viewIndex ) )
794  {   
795    for( UInt uiBaseViewIndex = 0; uiBaseViewIndex < m_viewIndex; uiBaseViewIndex++ )
796    {
797      m_aaiCodedScale [ 0 ][ uiBaseViewIndex ] = aaiScale [ uiBaseViewIndex ][     m_viewIndex ];
798      m_aaiCodedScale [ 1 ][ uiBaseViewIndex ] = aaiScale [     m_viewIndex ][ uiBaseViewIndex ];
799      m_aaiCodedOffset[ 0 ][ uiBaseViewIndex ] = aaiOffset[ uiBaseViewIndex ][     m_viewIndex ];
800      m_aaiCodedOffset[ 1 ][ uiBaseViewIndex ] = aaiOffset[     m_viewIndex ][ uiBaseViewIndex ];
801    }
802  } 
803}
804#endif
805
806Void TComSlice::checkColRefIdx(UInt curSliceIdx, TComPic* pic)
807{
808  Int i;
809  TComSlice* curSlice = pic->getSlice(curSliceIdx);
810  Int currColRefPOC =  curSlice->getRefPOC( RefPicList(1-curSlice->getColFromL0Flag()), curSlice->getColRefIdx());
811  TComSlice* preSlice;
812  Int preColRefPOC;
813  for(i=curSliceIdx-1; i>=0; i--)
814  {
815    preSlice = pic->getSlice(i);
816    if(preSlice->getSliceType() != I_SLICE)
817    {
818      preColRefPOC  = preSlice->getRefPOC( RefPicList(1-preSlice->getColFromL0Flag()), preSlice->getColRefIdx());
819      if(currColRefPOC != preColRefPOC)
820      {
821        printf("Collocated_ref_idx shall always be the same for all slices of a coded picture!\n");
822        exit(EXIT_FAILURE);
823      }
824      else
825      {
826        break;
827      }
828    }
829  }
830}
831
832Void TComSlice::checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, NalUnitType& associatedIRAPType, TComList<TComPic *>& rcListPic)
833{
834  for(Int i = 0; i < pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i++)
835  {
836    if(pocCRA < MAX_UINT && getPOC() > pocCRA)
837    {
838      assert(getPOC()+pReferencePictureSet->getDeltaPOC(i) >= pocCRA);
839    }
840  }
841  for(Int i = pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i < pReferencePictureSet->getNumberOfPictures(); i++)
842  {
843    if(pocCRA < MAX_UINT && getPOC() > pocCRA)
844    {
845      if (!pReferencePictureSet->getCheckLTMSBPresent(i))
846      {
847        assert(xGetLongTermRefPic(rcListPic, pReferencePictureSet->getPOC(i), false)->getPOC() >= pocCRA);
848      }
849      else
850      {
851      assert(pReferencePictureSet->getPOC(i) >= pocCRA);
852    }
853  }
854  }
855  if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP ) // IDR picture found
856  {
857    pocCRA = getPOC();
858    associatedIRAPType = getNalUnitType();
859  }
860  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
861  {
862    pocCRA = getPOC();
863    associatedIRAPType = getNalUnitType();
864  }
865  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
866         || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
867         || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP ) // BLA picture found
868  {
869    pocCRA = getPOC();
870    associatedIRAPType = getNalUnitType();
871  }
872}
873
874/** Function for marking the reference pictures when an IDR/CRA/CRANT/BLA/BLANT is encountered.
875 * \param pocCRA POC of the CRA/CRANT/BLA/BLANT picture
876 * \param bRefreshPending flag indicating if a deferred decoding refresh is pending
877 * \param rcListPic reference to the reference picture list
878 * This function marks the reference pictures as "unused for reference" in the following conditions.
879 * If the nal_unit_type is IDR/BLA/BLANT, all pictures in the reference picture list 
880 * are marked as "unused for reference"
881 *    If the nal_unit_type is BLA/BLANT, set the pocCRA to the temporal reference of the current picture.
882 * Otherwise
883 *    If the bRefreshPending flag is true (a deferred decoding refresh is pending) and the current
884 *    temporal reference is greater than the temporal reference of the latest CRA/CRANT/BLA/BLANT picture (pocCRA),
885 *    mark all reference pictures except the latest CRA/CRANT/BLA/BLANT picture as "unused for reference" and set
886 *    the bRefreshPending flag to false.
887 *    If the nal_unit_type is CRA/CRANT, set the bRefreshPending flag to true and pocCRA to the temporal
888 *    reference of the current picture.
889 * Note that the current picture is already placed in the reference list and its marking is not changed.
890 * If the current picture has a nal_ref_idc that is not 0, it will remain marked as "used for reference".
891 */
892Void TComSlice::decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic)
893{
894  TComPic*                 rpcPic;
895#if !FIX1172
896  setAssociatedIRAPPOC(pocCRA);
897#endif
898  Int pocCurr = getPOC(); 
899
900  if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
901    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
902    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
903    || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
904    || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )  // IDR or BLA picture
905  {
906    // mark all pictures as not used for reference
907    TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
908    while (iterPic != rcListPic.end())
909    {
910      rpcPic = *(iterPic);
911      rpcPic->setCurrSliceIdx(0);
912      if (rpcPic->getPOC() != pocCurr) rpcPic->getSlice(0)->setReferenced(false);
913      iterPic++;
914    }
915    if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
916      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
917      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
918    {
919      pocCRA = pocCurr;
920    }
921#if EFFICIENT_FIELD_IRAP
922    bRefreshPending = true;
923#endif
924  }
925  else // CRA or No DR
926  {
927#if EFFICIENT_FIELD_IRAP
928    if(getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_IDR_N_LP || getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL)
929    {
930      if (bRefreshPending==true && pocCurr > m_iLastIDR) // IDR reference marking pending
931      {
932        TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
933        while (iterPic != rcListPic.end())
934        {
935          rpcPic = *(iterPic);
936          if (rpcPic->getPOC() != pocCurr && rpcPic->getPOC() != m_iLastIDR)
937          {
938            rpcPic->getSlice(0)->setReferenced(false);
939          }
940          iterPic++;
941        }
942        bRefreshPending = false; 
943      }
944    }
945    else
946    {
947#endif
948    if (bRefreshPending==true && pocCurr > pocCRA) // CRA reference marking pending
949    {
950      TComList<TComPic*>::iterator        iterPic       = rcListPic.begin();
951      while (iterPic != rcListPic.end())
952      {
953        rpcPic = *(iterPic);
954        if (rpcPic->getPOC() != pocCurr && rpcPic->getPOC() != pocCRA)
955        {
956          rpcPic->getSlice(0)->setReferenced(false);
957        }
958        iterPic++;
959      }
960      bRefreshPending = false; 
961    }
962#if EFFICIENT_FIELD_IRAP
963    }
964#endif
965    if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA ) // CRA picture found
966    {
967      bRefreshPending = true; 
968      pocCRA = pocCurr;
969    }
970  }
971}
972
973Void TComSlice::copySliceInfo(TComSlice *pSrc)
974{
975  assert( pSrc != NULL );
976
977  Int i, j, k;
978
979  m_iPOC                 = pSrc->m_iPOC;
980  m_eNalUnitType         = pSrc->m_eNalUnitType;
981#if H_MV
982  m_layerId              = pSrc->m_layerId;
983  // GT: Copying of several other values might be be missing here, or is above not necessary?
984#endif
985  m_eSliceType           = pSrc->m_eSliceType;
986  m_iSliceQp             = pSrc->m_iSliceQp;
987#if ADAPTIVE_QP_SELECTION
988  m_iSliceQpBase         = pSrc->m_iSliceQpBase;
989#endif
990  m_deblockingFilterDisable   = pSrc->m_deblockingFilterDisable;
991  m_deblockingFilterOverrideFlag = pSrc->m_deblockingFilterOverrideFlag;
992  m_deblockingFilterBetaOffsetDiv2 = pSrc->m_deblockingFilterBetaOffsetDiv2;
993  m_deblockingFilterTcOffsetDiv2 = pSrc->m_deblockingFilterTcOffsetDiv2;
994 
995  for (i = 0; i < 2; i++)
996  {
997    m_aiNumRefIdx[i]     = pSrc->m_aiNumRefIdx[i];
998  }
999
1000  for (i = 0; i < MAX_NUM_REF; i++)
1001  {
1002    m_list1IdxToList0Idx[i] = pSrc->m_list1IdxToList0Idx[i];
1003  } 
1004  m_bCheckLDC             = pSrc->m_bCheckLDC;
1005  m_iSliceQpDelta        = pSrc->m_iSliceQpDelta;
1006  m_iSliceQpDeltaCb      = pSrc->m_iSliceQpDeltaCb;
1007  m_iSliceQpDeltaCr      = pSrc->m_iSliceQpDeltaCr;
1008  for (i = 0; i < 2; i++)
1009  {
1010    for (j = 0; j < MAX_NUM_REF; j++)
1011    {
1012      m_apcRefPicList[i][j]  = pSrc->m_apcRefPicList[i][j];
1013      m_aiRefPOCList[i][j]   = pSrc->m_aiRefPOCList[i][j];
1014#if H_MV
1015      m_aiRefLayerIdList[i][j] = pSrc->m_aiRefLayerIdList[i][j];
1016#endif
1017    }
1018  }
1019  for (i = 0; i < 2; i++)
1020  {
1021    for (j = 0; j < MAX_NUM_REF + 1; j++)
1022    {
1023      m_bIsUsedAsLongTerm[i][j] = pSrc->m_bIsUsedAsLongTerm[i][j];
1024    }
1025  }
1026  m_iDepth               = pSrc->m_iDepth;
1027
1028  // referenced slice
1029  m_bRefenced            = pSrc->m_bRefenced;
1030
1031  // access channel
1032#if H_MV
1033  m_pcVPS                = pSrc->m_pcVPS;
1034#endif
1035  m_pcSPS                = pSrc->m_pcSPS;
1036  m_pcPPS                = pSrc->m_pcPPS;
1037  m_pcRPS                = pSrc->m_pcRPS;
1038  m_iLastIDR             = pSrc->m_iLastIDR;
1039
1040  m_pcPic                = pSrc->m_pcPic;
1041
1042  m_colFromL0Flag        = pSrc->m_colFromL0Flag;
1043  m_colRefIdx            = pSrc->m_colRefIdx;
1044  setLambdas(pSrc->getLambdas());
1045  for (i = 0; i < 2; i++)
1046  {
1047    for (j = 0; j < MAX_NUM_REF; j++)
1048    {
1049      for (k =0; k < MAX_NUM_REF; k++)
1050      {
1051        m_abEqualRef[i][j][k] = pSrc->m_abEqualRef[i][j][k];
1052      }
1053    }
1054  }
1055
1056  m_uiTLayer                      = pSrc->m_uiTLayer;
1057  m_bTLayerSwitchingFlag          = pSrc->m_bTLayerSwitchingFlag;
1058
1059  m_sliceMode                   = pSrc->m_sliceMode;
1060  m_sliceArgument               = pSrc->m_sliceArgument;
1061  m_sliceCurStartCUAddr         = pSrc->m_sliceCurStartCUAddr;
1062  m_sliceCurEndCUAddr           = pSrc->m_sliceCurEndCUAddr;
1063  m_sliceIdx                    = pSrc->m_sliceIdx;
1064  m_sliceSegmentMode            = pSrc->m_sliceSegmentMode;
1065  m_sliceSegmentArgument        = pSrc->m_sliceSegmentArgument; 
1066  m_sliceSegmentCurStartCUAddr  = pSrc->m_sliceSegmentCurStartCUAddr;
1067  m_sliceSegmentCurEndCUAddr    = pSrc->m_sliceSegmentCurEndCUAddr;
1068  m_nextSlice                    = pSrc->m_nextSlice;
1069  m_nextSliceSegment             = pSrc->m_nextSliceSegment;
1070  for ( Int e=0 ; e<2 ; e++ )
1071  {
1072    for ( Int n=0 ; n<MAX_NUM_REF ; n++ )
1073    {
1074      memcpy(m_weightPredTable[e][n], pSrc->m_weightPredTable[e][n], sizeof(wpScalingParam)*3 );
1075    }
1076  }
1077  m_saoEnabledFlag = pSrc->m_saoEnabledFlag; 
1078  m_saoEnabledFlagChroma = pSrc->m_saoEnabledFlagChroma;
1079  m_cabacInitFlag                = pSrc->m_cabacInitFlag;
1080  m_numEntryPointOffsets  = pSrc->m_numEntryPointOffsets;
1081
1082  m_bLMvdL1Zero = pSrc->m_bLMvdL1Zero;
1083  m_LFCrossSliceBoundaryFlag = pSrc->m_LFCrossSliceBoundaryFlag;
1084  m_enableTMVPFlag                = pSrc->m_enableTMVPFlag;
1085  m_maxNumMergeCand               = pSrc->m_maxNumMergeCand;
1086
1087#if H_MV
1088  // Additional slice header syntax elements
1089#if !H_MV_HLS7_GEN
1090  m_pocResetFlag               = pSrc->m_pocResetFlag; 
1091#endif
1092  m_discardableFlag            = pSrc->m_discardableFlag; 
1093  m_interLayerPredEnabledFlag  = pSrc->m_interLayerPredEnabledFlag; 
1094  m_numInterLayerRefPicsMinus1 = pSrc->m_numInterLayerRefPicsMinus1;
1095
1096  for (Int layer = 0; layer < MAX_NUM_LAYERS; layer++ )
1097  {
1098    m_interLayerPredLayerIdc[ layer ] = pSrc->m_interLayerPredLayerIdc[ layer ]; 
1099  }
1100#endif
1101#if MTK_SINGLE_DEPTH_MODE_I0095
1102  m_bApplySingleDepthMode = pSrc->m_bApplySingleDepthMode;
1103#endif
1104#if H_3D_IC
1105  m_bApplyIC = pSrc->m_bApplyIC;
1106  m_icSkipParseFlag = pSrc->m_icSkipParseFlag;
1107#endif
1108}
1109
1110Int TComSlice::m_prevTid0POC = 0;
1111
1112/** Function for setting the slice's temporal layer ID and corresponding temporal_layer_switching_point_flag.
1113 * \param uiTLayer Temporal layer ID of the current slice
1114 * The decoder calls this function to set temporal_layer_switching_point_flag for each temporal layer based on
1115 * the SPS's temporal_id_nesting_flag and the parsed PPS.  Then, current slice's temporal layer ID and
1116 * temporal_layer_switching_point_flag is set accordingly.
1117 */
1118Void TComSlice::setTLayerInfo( UInt uiTLayer )
1119{
1120  m_uiTLayer = uiTLayer;
1121}
1122
1123/** Function for checking if this is a switching-point
1124*/
1125Bool TComSlice::isTemporalLayerSwitchingPoint( TComList<TComPic*>& rcListPic )
1126{
1127  TComPic* rpcPic;
1128  // loop through all pictures in the reference picture buffer
1129  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1130  while ( iterPic != rcListPic.end())
1131  {
1132    rpcPic = *(iterPic++);
1133    if(rpcPic->getSlice(0)->isReferenced() && rpcPic->getPOC() != getPOC())
1134    {
1135      if(rpcPic->getTLayer() >= getTLayer())
1136      {
1137        return false;
1138      }
1139    }
1140  }
1141  return true;
1142}
1143
1144/** Function for checking if this is a STSA candidate
1145 */
1146Bool TComSlice::isStepwiseTemporalLayerSwitchingPointCandidate( TComList<TComPic*>& rcListPic )
1147{
1148    TComPic* rpcPic;
1149   
1150    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1151    while ( iterPic != rcListPic.end())
1152    {
1153        rpcPic = *(iterPic++);
1154        if(rpcPic->getSlice(0)->isReferenced() &&  (rpcPic->getUsedByCurr()==true) && rpcPic->getPOC() != getPOC())
1155        {
1156            if(rpcPic->getTLayer() >= getTLayer())
1157            {
1158                return false;
1159            }
1160        }
1161    }
1162    return true;
1163}
1164
1165
1166Void TComSlice::checkLeadingPictureRestrictions(TComList<TComPic*>& rcListPic)
1167{
1168  TComPic* rpcPic;
1169
1170  Int nalUnitType = this->getNalUnitType();
1171
1172  // When a picture is a leading picture, it shall be a RADL or RASL picture.
1173  if(this->getAssociatedIRAPPOC() > this->getPOC())
1174  {
1175    // Do not check IRAP pictures since they may get a POC lower than their associated IRAP
1176    if(nalUnitType < NAL_UNIT_CODED_SLICE_BLA_W_LP ||
1177       nalUnitType > NAL_UNIT_RESERVED_IRAP_VCL23)
1178    {
1179      assert(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1180             nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R ||
1181             nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
1182             nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R);
1183    }
1184  }
1185
1186  // When a picture is a trailing picture, it shall not be a RADL or RASL picture.
1187  if(this->getAssociatedIRAPPOC() < this->getPOC())
1188  {
1189    assert(nalUnitType != NAL_UNIT_CODED_SLICE_RASL_N &&
1190           nalUnitType != NAL_UNIT_CODED_SLICE_RASL_R &&
1191           nalUnitType != NAL_UNIT_CODED_SLICE_RADL_N &&
1192           nalUnitType != NAL_UNIT_CODED_SLICE_RADL_R);
1193  }
1194
1195  // No RASL pictures shall be present in the bitstream that are associated
1196  // with a BLA picture having nal_unit_type equal to BLA_W_RADL or BLA_N_LP.
1197  if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1198     nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
1199  {
1200    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_W_RADL &&
1201           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_N_LP);
1202  }
1203
1204  // No RASL pictures shall be present in the bitstream that are associated with
1205  // an IDR picture.
1206  if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1207     nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
1208  {
1209    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_N_LP   &&
1210           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_W_RADL);
1211  }
1212
1213  // No RADL pictures shall be present in the bitstream that are associated with
1214  // a BLA picture having nal_unit_type equal to BLA_N_LP or that are associated
1215  // with an IDR picture having nal_unit_type equal to IDR_N_LP.
1216  if(nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
1217     nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R)
1218  {
1219    assert(this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_BLA_N_LP   &&
1220           this->getAssociatedIRAPType() != NAL_UNIT_CODED_SLICE_IDR_N_LP);
1221  }
1222
1223  // loop through all pictures in the reference picture buffer
1224  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1225  while ( iterPic != rcListPic.end())
1226  {
1227    rpcPic = *(iterPic++);
1228#if BUGFIX_INTRAPERIOD
1229    if(!rpcPic->getReconMark())
1230    {
1231      continue;
1232    }
1233#endif
1234    if (rpcPic->getPOC() == this->getPOC())
1235    {
1236      continue;
1237    }
1238
1239    // Any picture that has PicOutputFlag equal to 1 that precedes an IRAP picture
1240    // in decoding order shall precede the IRAP picture in output order.
1241    // (Note that any picture following in output order would be present in the DPB)
1242#if !SETTING_NO_OUT_PIC_PRIOR
1243    if(rpcPic->getSlice(0)->getPicOutputFlag() == 1)
1244#else
1245    if(rpcPic->getSlice(0)->getPicOutputFlag() == 1 && !this->getNoOutputPriorPicsFlag())
1246#endif
1247    {
1248      if(nalUnitType == NAL_UNIT_CODED_SLICE_BLA_N_LP    ||
1249         nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_LP    ||
1250         nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_RADL  ||
1251         nalUnitType == NAL_UNIT_CODED_SLICE_CRA         ||
1252         nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP    ||
1253         nalUnitType == NAL_UNIT_CODED_SLICE_IDR_W_RADL)
1254      {
1255        assert(rpcPic->getPOC() < this->getPOC());
1256      }
1257    }
1258
1259    // Any picture that has PicOutputFlag equal to 1 that precedes an IRAP picture
1260    // in decoding order shall precede any RADL picture associated with the IRAP
1261    // picture in output order.
1262    if(rpcPic->getSlice(0)->getPicOutputFlag() == 1)
1263    {
1264      if((nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
1265          nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R))
1266      {
1267        // rpcPic precedes the IRAP in decoding order
1268        if(this->getAssociatedIRAPPOC() > rpcPic->getSlice(0)->getAssociatedIRAPPOC())
1269        {
1270          // rpcPic must not be the IRAP picture
1271          if(this->getAssociatedIRAPPOC() != rpcPic->getPOC())
1272          {
1273            assert(rpcPic->getPOC() < this->getPOC());
1274          }
1275        }
1276      }
1277    }
1278
1279    // When a picture is a leading picture, it shall precede, in decoding order,
1280    // all trailing pictures that are associated with the same IRAP picture.
1281    if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1282       nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R ||
1283       nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N ||
1284       nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R)
1285    {
1286      if(rpcPic->getSlice(0)->getAssociatedIRAPPOC() == this->getAssociatedIRAPPOC())
1287      {
1288        // rpcPic is a picture that preceded the leading in decoding order since it exist in the DPB
1289        // rpcPic would violate the constraint if it was a trailing picture
1290        assert(rpcPic->getPOC() <= this->getAssociatedIRAPPOC());
1291      }
1292    }
1293
1294    // Any RASL picture associated with a CRA or BLA picture shall precede any
1295    // RADL picture associated with the CRA or BLA picture in output order
1296    if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1297       nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
1298    { 
1299      if((this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_N_LP   ||
1300          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_W_LP   ||
1301          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL ||
1302          this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_CRA)       &&
1303          this->getAssociatedIRAPPOC() == rpcPic->getSlice(0)->getAssociatedIRAPPOC())
1304      {
1305        if(rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N ||
1306           rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_R)
1307        {
1308          assert(rpcPic->getPOC() > this->getPOC());
1309        }
1310      }
1311    }
1312
1313    // Any RASL picture associated with a CRA picture shall follow, in output
1314    // order, any IRAP picture that precedes the CRA picture in decoding order.
1315    if(nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N ||
1316       nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R)
1317    {
1318      if(this->getAssociatedIRAPType() == NAL_UNIT_CODED_SLICE_CRA)
1319      {
1320        if(rpcPic->getSlice(0)->getPOC() < this->getAssociatedIRAPPOC() &&
1321           (rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP   ||
1322            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP   ||
1323            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL ||
1324            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP   ||
1325            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL ||
1326            rpcPic->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA))
1327        {
1328          assert(this->getPOC() > rpcPic->getSlice(0)->getPOC());
1329        }
1330      }
1331    }
1332  }
1333}
1334
1335
1336/** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
1337*/
1338Void TComSlice::applyReferencePictureSet( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet)
1339{
1340  TComPic* rpcPic;
1341  Int i, isReference;
1342
1343  checkLeadingPictureRestrictions(rcListPic);
1344
1345  // loop through all pictures in the reference picture buffer
1346  TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1347  while ( iterPic != rcListPic.end())
1348  {
1349    rpcPic = *(iterPic++);
1350
1351    if(!rpcPic->getSlice( 0 )->isReferenced())
1352    {
1353      continue;
1354    }
1355
1356    isReference = 0;
1357    // loop through all pictures in the Reference Picture Set
1358    // to see if the picture should be kept as reference picture
1359    for(i=0;i<pReferencePictureSet->getNumberOfPositivePictures()+pReferencePictureSet->getNumberOfNegativePictures();i++)
1360    {
1361      if(!rpcPic->getIsLongTerm() && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i))
1362      {
1363        isReference = 1;
1364        rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
1365        rpcPic->setIsLongTerm(0);
1366      }
1367    }
1368    for(;i<pReferencePictureSet->getNumberOfPictures();i++)
1369    {
1370      if(pReferencePictureSet->getCheckLTMSBPresent(i)==true)
1371      {
1372        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()) == pReferencePictureSet->getPOC(i))
1373        {
1374          isReference = 1;
1375          rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
1376        }
1377      }
1378      else 
1379      {
1380        Int pocCycle = 1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
1381        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC() & (pocCycle-1);
1382        Int refPoc = pReferencePictureSet->getPOC(i) & (pocCycle-1);
1383        if(rpcPic->getIsLongTerm() && curPoc == refPoc)
1384        {
1385          isReference = 1;
1386          rpcPic->setUsedByCurr(pReferencePictureSet->getUsed(i));
1387        }
1388      }
1389
1390    }
1391#if H_MV
1392    if( isReference ) // Current picture is in the temporal RPS
1393    {
1394      assert( rpcPic->getSlice(0)->getDiscardableFlag() == 0 ); // Temporal RPS shall not contain picture with discardable_flag equal to 1
1395    }
1396#endif
1397    // mark the picture as "unused for reference" if it is not in
1398    // the Reference Picture Set
1399    if(rpcPic->getPicSym()->getSlice(0)->getPOC() != this->getPOC() && isReference == 0)   
1400    {           
1401      rpcPic->getSlice( 0 )->setReferenced( false );   
1402      rpcPic->setUsedByCurr(0);
1403      rpcPic->setIsLongTerm(0);
1404    }
1405    //check that pictures of higher temporal layers are not used
1406    assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getUsedByCurr()==0||rpcPic->getTLayer()<=this->getTLayer());
1407    //check that pictures of higher or equal temporal layer are not in the RPS if the current picture is a TSA picture
1408    if(this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_R || this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N)
1409    {
1410      assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getTLayer()<this->getTLayer());
1411    }
1412    //check that pictures marked as temporal layer non-reference pictures are not used for reference
1413    if(rpcPic->getPicSym()->getSlice(0)->getPOC() != this->getPOC() && rpcPic->getTLayer()==this->getTLayer())
1414    {
1415      assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getUsedByCurr()==0||rpcPic->getSlice( 0 )->getTemporalLayerNonReferenceFlag()==false);
1416    }
1417  }
1418}
1419
1420/** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
1421*/
1422#if ALLOW_RECOVERY_POINT_AS_RAP
1423Int TComSlice::checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess, Bool bUseRecoveryPoint)
1424#else
1425Int TComSlice::checkThatAllRefPicsAreAvailable( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool printErrors, Int pocRandomAccess)
1426#endif
1427{
1428#if ALLOW_RECOVERY_POINT_AS_RAP
1429  Int atLeastOneUnabledByRecoveryPoint = 0;
1430  Int atLeastOneFlushedByPreviousIDR = 0;
1431#endif
1432  TComPic* rpcPic;
1433  Int i, isAvailable;
1434  Int atLeastOneLost = 0;
1435  Int atLeastOneRemoved = 0;
1436  Int iPocLost = 0;
1437
1438  // loop through all long-term pictures in the Reference Picture Set
1439  // to see if the picture should be kept as reference picture
1440  for(i=pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures();i<pReferencePictureSet->getNumberOfPictures();i++)
1441  {
1442    isAvailable = 0;
1443    // loop through all pictures in the reference picture buffer
1444    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1445    while ( iterPic != rcListPic.end())
1446    {
1447      rpcPic = *(iterPic++);
1448      if(pReferencePictureSet->getCheckLTMSBPresent(i)==true)
1449      {
1450        if(rpcPic->getIsLongTerm() && (rpcPic->getPicSym()->getSlice(0)->getPOC()) == pReferencePictureSet->getPOC(i) && rpcPic->getSlice(0)->isReferenced())
1451        {
1452#if ALLOW_RECOVERY_POINT_AS_RAP
1453          if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
1454          {
1455            isAvailable = 0;
1456          }
1457          else
1458          {
1459          isAvailable = 1;
1460        }
1461#else
1462          isAvailable = 1;
1463#endif
1464        }
1465      }
1466      else 
1467      {
1468        Int pocCycle = 1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
1469        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC() & (pocCycle-1);
1470        Int refPoc = pReferencePictureSet->getPOC(i) & (pocCycle-1);
1471        if(rpcPic->getIsLongTerm() && curPoc == refPoc && rpcPic->getSlice(0)->isReferenced())
1472        {
1473#if ALLOW_RECOVERY_POINT_AS_RAP
1474          if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
1475          {
1476            isAvailable = 0;
1477          }
1478          else
1479          {
1480          isAvailable = 1;
1481        }
1482#else
1483          isAvailable = 1;
1484#endif
1485        }
1486      }
1487    }
1488    // if there was no such long-term check the short terms
1489    if(!isAvailable)
1490    {
1491      iterPic = rcListPic.begin();
1492      while ( iterPic != rcListPic.end())
1493      {
1494        rpcPic = *(iterPic++);
1495
1496        Int pocCycle = 1 << rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
1497        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC();
1498        Int refPoc = pReferencePictureSet->getPOC(i);
1499        if (!pReferencePictureSet->getCheckLTMSBPresent(i))
1500        {
1501          curPoc = curPoc & (pocCycle - 1);
1502          refPoc = refPoc & (pocCycle - 1);
1503        }
1504       
1505        if (rpcPic->getSlice(0)->isReferenced() && curPoc == refPoc)
1506        {
1507#if ALLOW_RECOVERY_POINT_AS_RAP
1508          if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
1509          {
1510            isAvailable = 0;
1511          }
1512          else
1513          {
1514          isAvailable = 1;
1515          rpcPic->setIsLongTerm(1);
1516          break;
1517        }
1518#else
1519          isAvailable = 1;
1520          rpcPic->setIsLongTerm(1);
1521          break;
1522#endif
1523        }
1524      }
1525    }
1526    // report that a picture is lost if it is in the Reference Picture Set
1527    // but not available as reference picture
1528    if(isAvailable == 0)   
1529    {           
1530      if (this->getPOC() + pReferencePictureSet->getDeltaPOC(i) >= pocRandomAccess)
1531      {
1532        if(!pReferencePictureSet->getUsed(i) )
1533        {
1534          if(printErrors)
1535          {
1536            printf("\nLong-term reference picture with POC = %3d seems to have been removed or not correctly decoded.", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
1537          }
1538          atLeastOneRemoved = 1;
1539        }
1540        else
1541        {
1542          if(printErrors)
1543          {
1544            printf("\nLong-term reference picture with POC = %3d is lost or not correctly decoded!", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
1545          }
1546          atLeastOneLost = 1;
1547          iPocLost=this->getPOC() + pReferencePictureSet->getDeltaPOC(i);
1548        }
1549      }
1550#if ALLOW_RECOVERY_POINT_AS_RAP
1551      else if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess)
1552      {
1553        atLeastOneUnabledByRecoveryPoint = 1;
1554      }
1555      else if(bUseRecoveryPoint && (this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_N_LP || this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_W_RADL))
1556      {
1557        atLeastOneFlushedByPreviousIDR = 1;
1558      }
1559#endif
1560    }
1561  } 
1562  // loop through all short-term pictures in the Reference Picture Set
1563  // to see if the picture should be kept as reference picture
1564  for(i=0;i<pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures();i++)
1565  {
1566    isAvailable = 0;
1567    // loop through all pictures in the reference picture buffer
1568    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1569    while ( iterPic != rcListPic.end())
1570    {
1571      rpcPic = *(iterPic++);
1572
1573      if(!rpcPic->getIsLongTerm() && rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i) && rpcPic->getSlice(0)->isReferenced())
1574      {
1575#if ALLOW_RECOVERY_POINT_AS_RAP
1576        if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess)
1577        {
1578          isAvailable = 0;
1579        }
1580        else
1581        {
1582        isAvailable = 1;
1583      }
1584#else
1585        isAvailable = 1;
1586#endif
1587      }
1588    }
1589    // report that a picture is lost if it is in the Reference Picture Set
1590    // but not available as reference picture
1591    if(isAvailable == 0)   
1592    {           
1593      if (this->getPOC() + pReferencePictureSet->getDeltaPOC(i) >= pocRandomAccess)
1594      {
1595        if(!pReferencePictureSet->getUsed(i) )
1596        {
1597          if(printErrors)
1598          {
1599            printf("\nShort-term reference picture with POC = %3d seems to have been removed or not correctly decoded.", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
1600          }
1601          atLeastOneRemoved = 1;
1602        }
1603        else
1604        {
1605          if(printErrors)
1606          {
1607            printf("\nShort-term reference picture with POC = %3d is lost or not correctly decoded!", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
1608          }
1609          atLeastOneLost = 1;
1610          iPocLost=this->getPOC() + pReferencePictureSet->getDeltaPOC(i);
1611        }
1612      }
1613#if ALLOW_RECOVERY_POINT_AS_RAP
1614      else if(bUseRecoveryPoint && this->getPOC() > pocRandomAccess)
1615      {
1616        atLeastOneUnabledByRecoveryPoint = 1;
1617    }
1618      else if(bUseRecoveryPoint && (this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_N_LP || this->getAssociatedIRAPType()==NAL_UNIT_CODED_SLICE_IDR_W_RADL))
1619      {
1620        atLeastOneFlushedByPreviousIDR = 1;
1621  }   
1622#endif
1623    }
1624    }
1625#if ALLOW_RECOVERY_POINT_AS_RAP
1626  if(atLeastOneUnabledByRecoveryPoint || atLeastOneFlushedByPreviousIDR)
1627  {
1628    return -1;
1629  }   
1630#endif
1631  if(atLeastOneLost)
1632  {
1633    return iPocLost+1;
1634  }
1635  if(atLeastOneRemoved)
1636  {
1637    return -2;
1638  }
1639  else
1640  {
1641    return 0;
1642  }
1643}
1644
1645/** Function for constructing an explicit Reference Picture Set out of the available pictures in a referenced Reference Picture Set
1646*/
1647#if ALLOW_RECOVERY_POINT_AS_RAP
1648Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP, Int pocRandomAccess, Bool bUseRecoveryPoint)
1649#else
1650Void TComSlice::createExplicitReferencePictureSetFromReference( TComList<TComPic*>& rcListPic, TComReferencePictureSet *pReferencePictureSet, Bool isRAP)
1651#endif
1652{
1653  TComPic* rpcPic;
1654  Int i, j;
1655  Int k = 0;
1656  Int nrOfNegativePictures = 0;
1657  Int nrOfPositivePictures = 0;
1658  TComReferencePictureSet* pcRPS = this->getLocalRPS();
1659
1660  // loop through all pictures in the Reference Picture Set
1661  for(i=0;i<pReferencePictureSet->getNumberOfPictures();i++)
1662  {
1663    j = 0;
1664    // loop through all pictures in the reference picture buffer
1665    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1666    while ( iterPic != rcListPic.end())
1667    {
1668      j++;
1669      rpcPic = *(iterPic++);
1670
1671      if(rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getPOC() + pReferencePictureSet->getDeltaPOC(i) && rpcPic->getSlice(0)->isReferenced())
1672      {
1673        // This picture exists as a reference picture
1674        // and should be added to the explicit Reference Picture Set
1675        pcRPS->setDeltaPOC(k, pReferencePictureSet->getDeltaPOC(i));
1676        pcRPS->setUsed(k, pReferencePictureSet->getUsed(i) && (!isRAP));
1677#if ALLOW_RECOVERY_POINT_AS_RAP
1678        pcRPS->setUsed(k, pcRPS->getUsed(k) && !(bUseRecoveryPoint && this->getPOC() > pocRandomAccess && this->getPOC() + pReferencePictureSet->getDeltaPOC(i) < pocRandomAccess) ); 
1679#endif
1680        if(pcRPS->getDeltaPOC(k) < 0)
1681        {
1682          nrOfNegativePictures++;
1683        }
1684        else
1685        {
1686          nrOfPositivePictures++;
1687        }
1688        k++;
1689      }
1690    }
1691  }
1692#if EFFICIENT_FIELD_IRAP
1693  Bool useNewRPS = false;
1694  // if current picture is complimentary field associated to IRAP, add the IRAP to its RPS.
1695  if(m_pcPic->isField())
1696  {
1697    TComList<TComPic*>::iterator iterPic = rcListPic.begin();
1698    while ( iterPic != rcListPic.end())
1699    {
1700      rpcPic = *(iterPic++);
1701      if(rpcPic->getPicSym()->getSlice(0)->getPOC() == this->getAssociatedIRAPPOC() && this->getAssociatedIRAPPOC() == this->getPOC()+1)
1702      {
1703        pcRPS->setDeltaPOC(k, 1);
1704        pcRPS->setUsed(k, true);
1705        nrOfPositivePictures++;
1706        k ++;
1707        useNewRPS = true;
1708      }
1709    }
1710  }
1711#endif
1712  pcRPS->setNumberOfNegativePictures(nrOfNegativePictures);
1713  pcRPS->setNumberOfPositivePictures(nrOfPositivePictures);
1714  pcRPS->setNumberOfPictures(nrOfNegativePictures+nrOfPositivePictures);
1715  // This is a simplistic inter rps example. A smarter encoder will look for a better reference RPS to do the
1716  // inter RPS prediction with.  Here we just use the reference used by pReferencePictureSet.
1717  // If pReferencePictureSet is not inter_RPS_predicted, then inter_RPS_prediction is for the current RPS also disabled.
1718  if (!pReferencePictureSet->getInterRPSPrediction()
1719#if EFFICIENT_FIELD_IRAP
1720    || useNewRPS
1721#endif
1722    )
1723  {
1724    pcRPS->setInterRPSPrediction(false);
1725    pcRPS->setNumRefIdc(0);
1726  }
1727  else
1728  {
1729    Int rIdx =  this->getRPSidx() - pReferencePictureSet->getDeltaRIdxMinus1() - 1;
1730    Int deltaRPS = pReferencePictureSet->getDeltaRPS();
1731    TComReferencePictureSet* pcRefRPS = this->getSPS()->getRPSList()->getReferencePictureSet(rIdx);
1732    Int iRefPics = pcRefRPS->getNumberOfPictures();
1733    Int iNewIdc=0;
1734    for(i=0; i<= iRefPics; i++) 
1735    {
1736      Int deltaPOC = ((i != iRefPics)? pcRefRPS->getDeltaPOC(i) : 0);  // check if the reference abs POC is >= 0
1737      Int iRefIdc = 0;
1738      for (j=0; j < pcRPS->getNumberOfPictures(); j++) // loop through the  pictures in the new RPS
1739      {
1740        if ( (deltaPOC + deltaRPS) == pcRPS->getDeltaPOC(j))
1741        {
1742          if (pcRPS->getUsed(j))
1743          {
1744            iRefIdc = 1;
1745          }
1746          else
1747          {
1748            iRefIdc = 2;
1749          }
1750        }
1751      }
1752      pcRPS->setRefIdc(i, iRefIdc);
1753      iNewIdc++;
1754    }
1755    pcRPS->setInterRPSPrediction(true);
1756    pcRPS->setNumRefIdc(iNewIdc);
1757    pcRPS->setDeltaRPS(deltaRPS); 
1758    pcRPS->setDeltaRIdxMinus1(pReferencePictureSet->getDeltaRIdxMinus1() + this->getSPS()->getRPSList()->getNumberOfReferencePictureSets() - this->getRPSidx());
1759  }
1760
1761  this->setRPS(pcRPS);
1762  this->setRPSidx(-1);
1763}
1764
1765/** get AC and DC values for weighted pred
1766 * \param *wp
1767 * \returns Void
1768 */
1769Void  TComSlice::getWpAcDcParam(wpACDCParam *&wp)
1770{
1771  wp = m_weightACDCParam;
1772}
1773
1774/** init AC and DC values for weighted pred
1775 * \returns Void
1776 */
1777Void  TComSlice::initWpAcDcParam()
1778{
1779  for(Int iComp = 0; iComp < 3; iComp++ )
1780  {
1781    m_weightACDCParam[iComp].iAC = 0;
1782    m_weightACDCParam[iComp].iDC = 0;
1783  }
1784}
1785
1786/** get WP tables for weighted pred
1787 * \param RefPicList
1788 * \param iRefIdx
1789 * \param *&wpScalingParam
1790 * \returns Void
1791 */
1792Void  TComSlice::getWpScaling( RefPicList e, Int iRefIdx, wpScalingParam *&wp )
1793{
1794  wp = m_weightPredTable[e][iRefIdx];
1795}
1796
1797/** reset Default WP tables settings : no weight.
1798 * \param wpScalingParam
1799 * \returns Void
1800 */
1801Void  TComSlice::resetWpScaling()
1802{
1803  for ( Int e=0 ; e<2 ; e++ )
1804  {
1805    for ( Int i=0 ; i<MAX_NUM_REF ; i++ )
1806    {
1807      for ( Int yuv=0 ; yuv<3 ; yuv++ )
1808      {
1809        wpScalingParam  *pwp = &(m_weightPredTable[e][i][yuv]);
1810        pwp->bPresentFlag      = false;
1811        pwp->uiLog2WeightDenom = 0;
1812        pwp->uiLog2WeightDenom = 0;
1813        pwp->iWeight           = 1;
1814        pwp->iOffset           = 0;
1815      }
1816    }
1817  }
1818}
1819
1820/** init WP table
1821 * \returns Void
1822 */
1823Void  TComSlice::initWpScaling()
1824{
1825  for ( Int e=0 ; e<2 ; e++ )
1826  {
1827    for ( Int i=0 ; i<MAX_NUM_REF ; i++ )
1828    {
1829      for ( Int yuv=0 ; yuv<3 ; yuv++ )
1830      {
1831        wpScalingParam  *pwp = &(m_weightPredTable[e][i][yuv]);
1832        if ( !pwp->bPresentFlag ) 
1833        {
1834          // Inferring values not present :
1835          pwp->iWeight = (1 << pwp->uiLog2WeightDenom);
1836          pwp->iOffset = 0;
1837        }
1838
1839        pwp->w      = pwp->iWeight;
1840        Int bitDepth = yuv ? g_bitDepthC : g_bitDepthY;
1841        pwp->o      = pwp->iOffset << (bitDepth-8);
1842        pwp->shift  = pwp->uiLog2WeightDenom;
1843        pwp->round  = (pwp->uiLog2WeightDenom>=1) ? (1 << (pwp->uiLog2WeightDenom-1)) : (0);
1844      }
1845    }
1846  }
1847}
1848
1849// ------------------------------------------------------------------------------------------------
1850// Video parameter set (VPS)
1851// ------------------------------------------------------------------------------------------------
1852TComVPS::TComVPS()
1853: m_VPSId                     (  0)
1854, m_uiMaxTLayers              (  1)
1855#if H_MV
1856, m_uiMaxLayersMinus1         (  0)
1857#else
1858, m_uiMaxLayers               (  1)
1859#endif
1860, m_bTemporalIdNestingFlag    (false)
1861, m_numHrdParameters          (  0)
1862#if H_MV
1863, m_maxLayerId             (  0)
1864#else
1865, m_maxNuhReservedZeroLayerId (  0)
1866#endif
1867, m_hrdParameters             (NULL)
1868, m_hrdOpSetIdx               (NULL)
1869, m_cprmsPresentFlag          (NULL)
1870#if H_MV
1871, m_dpbSize                   (NULL)
1872, m_vpsVUI                 (  NULL )
1873#endif
1874{
1875#if H_MV
1876  m_vpsBaseLayerInternalFlag = true; 
1877#endif
1878
1879  for( Int i = 0; i < MAX_TLAYER; i++)
1880  {
1881    m_numReorderPics[i] = 0;
1882    m_uiMaxDecPicBuffering[i] = 1; 
1883    m_uiMaxLatencyIncrease[i] = 0;
1884  }
1885#if H_MV
1886  for (Int lsIdx = 0; lsIdx < MAX_VPS_OP_SETS_PLUS1; lsIdx++ )
1887  { 
1888    for( Int layerId = 0; layerId < MAX_VPS_NUH_LAYER_ID_PLUS1; layerId++ )
1889    {
1890      m_layerIdIncludedFlag[lsIdx][layerId] = (( lsIdx == 0 ) && ( layerId == 0 )) ; 
1891    }
1892  } 
1893  m_vpsNumProfileTierLevelMinus1 = -1; 
1894   
1895  m_numAddLayerSets              = 0;   
1896  m_numAddOlss                   = 0; 
1897  m_defaultOutputLayerIdc     = 0; 
1898 
1899  for ( Int i = 0; i < MAX_VPS_OUTPUTLAYER_SETS; i++)
1900  {
1901    m_layerSetIdxForOlsMinus1[i]  = -1; 
1902    m_profileLevelTierIdx[i]      = 0; 
1903    for ( Int j = 0; j < MAX_VPS_NUH_LAYER_ID_PLUS1; j++)
1904    {
1905      m_outputLayerFlag[i][j] = false; 
1906    }
1907    m_altOutputLayerFlag[ i ]       = false; 
1908  }
1909
1910  m_repFormatIdxPresentFlag = false; 
1911  m_maxOneActiveRefLayerFlag = false; 
1912  m_directDepTypeLenMinus2   = 0;         
1913 
1914
1915  m_vpsExtensionFlag = true; 
1916  m_vpsNonVuiExtensionLength = 0;
1917  m_splittingFlag    = false;
1918 
1919  for( Int i = 0; i < MAX_NUM_SCALABILITY_TYPES; i++ )
1920  {
1921    m_scalabilityMaskFlag[i] = false;
1922    m_dimensionIdLen [i]  = -1; 
1923  }
1924
1925  m_vpsNuhLayerIdPresentFlag = false;
1926
1927  for( Int i = 0; i < MAX_VPS_OP_SETS_PLUS1; i++ )
1928  {
1929    m_vpsProfilePresentFlag   [i] = false;
1930    m_layerSetIdxForOlsMinus1       [i] = 0;
1931    for( Int j = 0; j < MAX_VPS_NUH_LAYER_ID_PLUS1; j++ )
1932    {
1933      m_outputLayerFlag[i][j] = false;
1934    }
1935  }
1936
1937  for( Int i = 0; i < MAX_NUM_LAYER_IDS; i++ )
1938  {
1939    m_layerIdInVps[i] =  (i == 0 ) ? 0 : -1;         
1940  }
1941
1942  for( Int i = 0; i < MAX_NUM_LAYERS; i++ )
1943  {
1944    m_layerIdInNuh      [i] = ( i == 0 ) ? 0 : -1; 
1945    m_numDirectRefLayers[i] = 0; 
1946    m_vpsRepFormatIdx    [i] = 0; 
1947    m_pocLsbNotPresentFlag[i] = 0;
1948    m_repFormat          [i] = NULL; 
1949    m_viewIdVal          [i] = 0; 
1950
1951#if H_3D
1952    m_viewIndex         [i] = -1; 
1953    m_vpsDepthModesFlag [i] = false;
1954#if SEC_HLS_CLEANUP_I0100
1955    m_ivMvScalingFlag[i] = true; 
1956#else
1957    m_ivMvScalingFlag = true; 
1958#endif
1959#endif
1960#if SEPARATE_FLAG_I0085
1961    m_bIVPFlag [i]      = false;
1962#endif
1963    m_ivMvScalingFlag = true; 
1964#endif
1965
1966    for( Int j = 0; j < MAX_NUM_LAYERS; j++ )
1967    {
1968      m_directDependencyFlag[i][j] = false;
1969      m_directDependencyType[i][j] = -1; 
1970      m_refLayerId[i][j]           = -1; 
1971      m_maxTidIlRefPicsPlus1[i][j]  = 7;
1972    }
1973
1974    for( Int j = 0; j < MAX_NUM_SCALABILITY_TYPES; j++ )
1975    {
1976      m_dimensionId[i][j] = 0;
1977    }
1978#if H_3D_ARP
1979    m_uiUseAdvResPred[i]  = 0;
1980    m_uiARPStepNum[i]     = 1;
1981#endif
1982  }
1983  m_vpsVUI = new TComVPSVUI; 
1984  m_dpbSize = new TComDpbSize; 
1985
1986#if H_3D
1987  for( Int i = 0; i < MAX_NUM_LAYERS; i++ )
1988  {
1989#if H_3D_IV_MERGE
1990    m_ivMvPredFlag         [ i ] = false;
1991#if H_3D_SPIVMP
1992    m_iSubPULog2Size       [ i ] = 0;
1993#endif
1994#endif
1995#if MTK_I0099_VPS_EX2
1996    m_bLimQtPredFlag       [ i ] = false;
1997#endif
1998#if H_3D_VSP
1999    m_viewSynthesisPredFlag[ i ] = false;
2000#endif
2001#if H_3D_NBDV_REF
2002    m_depthRefinementFlag  [ i ] = false;
2003#endif
2004#if H_3D_INTER_SDC
2005    m_bInterSDCFlag        [ i ] = false;
2006#endif
2007#if SEPARATE_FLAG_I0085
2008    m_bIVPFlag             [ i ] = false;
2009#endif
2010#if H_3D_DBBP
2011    m_dbbpFlag             [ i ] = false;
2012#endif
2013#if H_3D_IV_MERGE
2014    m_bMPIFlag             [ i ] = false;
2015#endif
2016  } 
2017#endif
2018#endif
2019}
2020
2021TComVPS::~TComVPS()
2022{
2023  if( m_hrdParameters    != NULL )     delete[] m_hrdParameters;
2024  if( m_hrdOpSetIdx      != NULL )     delete[] m_hrdOpSetIdx;
2025  if( m_cprmsPresentFlag != NULL )     delete[] m_cprmsPresentFlag;
2026#if H_MV
2027  if ( m_vpsVUI          != NULL )     delete m_vpsVUI; 
2028  if ( m_dpbSize         != NULL )     delete m_dpbSize; 
2029
2030  for( Int i = 0; i < MAX_NUM_LAYERS; i++ )
2031  {
2032    if (m_repFormat[ i ] != NULL )      delete m_repFormat[ i ];   
2033  }
2034#endif
2035#if H_3D
2036  deleteCamPars();
2037#endif
2038}
2039
2040#if H_MV
2041
2042Bool TComVPS::checkVPSExtensionSyntax()
2043{
2044  for( Int layer = 1; layer <= getMaxLayersMinus1(); layer++ )
2045  {
2046    // check layer_id_in_nuh constraint
2047    assert( getLayerIdInNuh( layer ) > getLayerIdInNuh( layer -1 ) );
2048  }
2049
2050  //The value of vps_num_rep_formats_minus1 shall be in the range of 0 to 255, inclusive.
2051  assert( getVpsNumRepFormatsMinus1() >= 0 ); 
2052  assert( getVpsNumRepFormatsMinus1() <= 255 ); 
2053
2054  return true; 
2055}
2056
2057Int TComVPS::getNumScalabilityTypes()
2058{
2059  return scalTypeToScalIdx( ScalabilityType(MAX_NUM_SCALABILITY_TYPES) );
2060}
2061
2062Int TComVPS::scalTypeToScalIdx( ScalabilityType scalType )
2063{
2064  assert( scalType >= 0 && scalType <= MAX_NUM_SCALABILITY_TYPES ); 
2065  assert( scalType == MAX_NUM_SCALABILITY_TYPES || getScalabilityMaskFlag( scalType ) );
2066  Int scalIdx = 0; 
2067  for( Int curScalType = 0; curScalType < scalType; curScalType++ )
2068  {
2069    scalIdx += ( getScalabilityMaskFlag( curScalType ) ? 1 : 0 );
2070
2071  }
2072
2073  return scalIdx; 
2074}
2075Void TComVPS::setScalabilityMaskFlag( UInt val )
2076{
2077  for ( Int scalType = 0; scalType < MAX_NUM_SCALABILITY_TYPES; scalType++ ) 
2078  {
2079    setScalabilityMaskFlag( scalType, ( val & (1 << scalType ) ) != 0 );
2080  }
2081}
2082
2083Void TComVPS::setRefLayers()
2084{
2085  for( Int i = 0; i  <= getMaxLayersMinus1(); i++ )
2086  {
2087    Int iNuhLId = getLayerIdInNuh( i ); 
2088    m_numDirectRefLayers[ iNuhLId ] = 0; 
2089    for( Int j = 0; j < i; j++ )
2090    {
2091      if( getDirectDependencyFlag(i , j) )
2092      {
2093        m_refLayerId[ iNuhLId ][m_numDirectRefLayers[ iNuhLId ]++ ] = getLayerIdInNuh( j );
2094      }
2095    }
2096  }
2097
2098  for (Int i = 0 ; i < MAX_NUM_LAYER_IDS; i++ )
2099  {
2100    m_numRefLayers[i] = 0; 
2101  }
2102
2103  for (Int currLayerId = 0; currLayerId <= 62; currLayerId++ ) 
2104  {
2105    for (Int i = 0 ; i < MAX_NUM_LAYER_IDS; i++ )
2106    {
2107      m_recursiveRefLayerFlag[currLayerId][i] = 0; 
2108    }
2109  }
2110
2111  for( Int i = 0; i  <=  getMaxLayersMinus1(); i++ )
2112  {
2113    Int iNuhLId = getLayerIdInNuh( i );
2114    xSetRefLayerFlags( iNuhLId );
2115    for( Int j = 0; j < 63; j++ )
2116    {
2117      m_numRefLayers[ iNuhLId ]  +=  m_recursiveRefLayerFlag[ iNuhLId ][ j ];
2118    }
2119  }
2120
2121  for( Int i = 0; i <= getMaxLayersMinus1(); i++ )  // Bug in spec "<" instead of "<="
2122  {
2123    Int iNuhLId = getLayerIdInNuh( i );
2124    Int predIdx = 0;
2125    for( Int j = iNuhLId + 1; j < 63; j++ )
2126    {
2127      if( m_recursiveRefLayerFlag[ j ][ iNuhLId ] )
2128      {
2129        m_predictedLayerId[ iNuhLId ][ predIdx++ ] = j;
2130      }
2131    }
2132    m_numPredictedLayers[ iNuhLId ] = predIdx;
2133  }
2134 
2135  Bool countedLayerIdxFlag[ MAX_NUM_LAYERS ]; 
2136  for( Int i = 0; i  <=  getMaxLayersMinus1(); i++ )
2137  {
2138    countedLayerIdxFlag[ i ] = 0;
2139  }
2140 
2141  for( Int i = 0, k = 0; i  <=  getMaxLayersMinus1(); i++ )
2142  {
2143    Int iNuhLId = getLayerIdInNuh( i );
2144    if( m_numDirectRefLayers[ iNuhLId ]  ==  0 )
2145    {
2146      m_treePartitionLayerIdList[ k ][ 0 ] = iNuhLId;
2147      m_numLayersInTreePartition[ k ]      = 1;
2148      for( Int j = 0; j < m_numPredictedLayers[ iNuhLId ]; j++ ) 
2149      {
2150        if( !countedLayerIdxFlag[ getLayerIdInVps( m_predictedLayerId[ iNuhLId ][ j ] ) ] )   
2151        {
2152          m_treePartitionLayerIdList[ k ][ m_numLayersInTreePartition[ k ] ] = m_predictedLayerId[ iNuhLId ][ j ];
2153          m_numLayersInTreePartition[ k ]++;
2154          countedLayerIdxFlag[ getLayerIdInVps( m_predictedLayerId[ iNuhLId ][ j ] ) ] = 1;
2155        }
2156      }
2157      k++;
2158    }
2159    m_numIndependentLayers = k;
2160  }
2161}
2162
2163Int TComVPS::getRefLayerId( Int layerIdInNuh, Int idx )
2164{
2165  assert( idx >= 0 && idx < m_numDirectRefLayers[layerIdInNuh] );     
2166  Int refLayerIdInNuh = m_refLayerId[ layerIdInNuh ][ idx ];   
2167  assert ( refLayerIdInNuh >= 0 ); 
2168  return refLayerIdInNuh;
2169}
2170
2171Int TComVPS::getScalabilityId( Int layerIdInVps, ScalabilityType scalType )
2172{
2173  return getScalabilityMaskFlag( scalType ) ? getDimensionId( layerIdInVps, scalTypeToScalIdx( scalType ) ) : 0;
2174}
2175
2176#if H_3D
2177Int TComVPS::getLayerIdInNuh( Int viewIndex, Bool depthFlag )
2178{
2179  Int foundLayerIdinNuh = -1; 
2180
2181  for (Int layerIdInVps = 0 ; layerIdInVps <= getMaxLayersMinus1(); layerIdInVps++ )
2182  {
2183    Int layerIdInNuh = getLayerIdInNuh( layerIdInVps ); 
2184    if( ( getViewIndex( layerIdInNuh ) == viewIndex ) && ( getDepthId( layerIdInNuh ) == ( depthFlag ? 1 : 0 ) )  )
2185    {
2186      foundLayerIdinNuh = layerIdInNuh; 
2187      break; 
2188    }
2189  }
2190#if !BUG_FIX_TK65
2191  assert( foundLayerIdinNuh != -1 ); 
2192#endif
2193  return foundLayerIdinNuh;
2194}
2195
2196Void TComVPS::createCamPars(Int iNumViews)
2197{
2198  Int i = 0, j = 0;
2199
2200  m_bCamParPresent = new Bool[ iNumViews ];
2201  m_bCamParInSliceHeader = new Bool[ iNumViews ];
2202
2203  m_aaaiCodedScale = new Int**[ iNumViews ];
2204  m_aaaiCodedOffset = new Int**[ iNumViews ];
2205  for ( i = 0; i < iNumViews ; i++ )
2206  {
2207    m_bCamParInSliceHeader[i] = false; 
2208    m_aaaiCodedScale[i] = new Int*[ 2 ];
2209    m_aaaiCodedOffset[i] = new Int*[ 2 ];
2210    for ( j = 0; j < 2; j++ )
2211    {
2212      m_aaaiCodedScale[i][j] = new Int[ MAX_NUM_LAYERS ];
2213      m_aaaiCodedOffset[i][j] = new Int[ MAX_NUM_LAYERS ];
2214      for ( Int k = 0; k < MAX_NUM_LAYERS; k++ )
2215      {
2216        m_aaaiCodedScale[i][j][k] = 0;
2217        m_aaaiCodedOffset[i][j][k] = 0;
2218      }
2219    }
2220  }
2221}
2222
2223Void TComVPS::deleteCamPars()
2224{
2225  Int iNumViews = getNumViews();
2226  Int i = 0, j = 0;
2227
2228  if ( m_bCamParPresent != NULL )
2229  {
2230    delete [] m_bCamParPresent;
2231  }
2232  if ( m_bCamParInSliceHeader != NULL )
2233  {
2234    delete [] m_bCamParInSliceHeader;
2235  }
2236
2237  if ( m_aaaiCodedScale != NULL )
2238  {
2239    for ( i = 0; i < iNumViews ; i++ )
2240    {
2241      for ( j = 0; j < 2; j++ )
2242      {
2243        delete [] m_aaaiCodedScale[i][j];
2244      }
2245      delete [] m_aaaiCodedScale[i];
2246    }
2247    delete [] m_aaaiCodedScale;
2248  }
2249
2250  if ( m_aaaiCodedOffset != NULL )
2251  {
2252    for ( i = 0; i < iNumViews ; i++ )
2253    {
2254      for ( j = 0; j < 2; j++ )
2255      {
2256        delete [] m_aaaiCodedOffset[i][j];
2257      }
2258      delete [] m_aaaiCodedOffset[i];
2259    }
2260    delete [] m_aaaiCodedOffset;
2261  }
2262}
2263
2264
2265Void
2266  TComVPS::initCamParaVPS( UInt uiViewIndex, Bool bCamParPresent, UInt uiCamParPrecision, Bool bCamParSlice, Int** aaiScale, Int** aaiOffset )
2267{
2268  AOT( uiViewIndex != 0 && !bCamParSlice && ( aaiScale == 0 || aaiOffset == 0 ) ); 
2269
2270  m_uiCamParPrecision = ( ( uiViewIndex != 0 )? uiCamParPrecision : 0 );
2271  m_bCamParPresent[ uiViewIndex ] = (( uiViewIndex != 0 )? bCamParPresent  : false );
2272  m_bCamParInSliceHeader[ uiViewIndex ]  = ( (uiViewIndex != 0)? bCamParSlice  : false );
2273
2274  if( !m_bCamParInSliceHeader[ uiViewIndex ] )
2275  {
2276    for( UInt uiBaseViewIndex = 0; uiBaseViewIndex < uiViewIndex; uiBaseViewIndex++ )
2277    {
2278      m_aaaiCodedScale [ uiViewIndex ][ 0 ][ uiBaseViewIndex ] = aaiScale [ uiBaseViewIndex ][     uiViewIndex ];
2279      m_aaaiCodedScale [ uiViewIndex ][ 1 ][ uiBaseViewIndex ] = aaiScale [     uiViewIndex ][ uiBaseViewIndex ];
2280      m_aaaiCodedOffset[ uiViewIndex ][ 0 ][ uiBaseViewIndex ] = aaiOffset[ uiBaseViewIndex ][     uiViewIndex ];
2281      m_aaaiCodedOffset[ uiViewIndex ][ 1 ][ uiBaseViewIndex ] = aaiOffset[     uiViewIndex ][ uiBaseViewIndex ];
2282    }
2283  }
2284}
2285
2286#endif // H_3D
2287
2288
2289Int TComVPS::xGetDimBitOffset( Int j )
2290{
2291  Int dimBitOffset = 0; 
2292  if ( getSplittingFlag() && j == getNumScalabilityTypes() )
2293  {
2294     dimBitOffset = 6; 
2295  }
2296  else
2297  {
2298    for (Int dimIdx = 0; dimIdx <= j-1; dimIdx++)
2299    {
2300      dimBitOffset += getDimensionIdLen( dimIdx ); 
2301    }
2302  }
2303  return dimBitOffset; 
2304}
2305
2306Int TComVPS::inferDimensionId( Int i, Int j )
2307{
2308    return ( ( getLayerIdInNuh( i ) & ( (1 << xGetDimBitOffset( j + 1 ) ) - 1) ) >> xGetDimBitOffset( j ) ); 
2309}
2310
2311Int TComVPS::inferLastDimsionIdLenMinus1()
2312{
2313  return ( 5 - xGetDimBitOffset( getNumScalabilityTypes() - 1 ) ); 
2314}
2315
2316Int TComVPS::getNumLayersInIdList( Int lsIdx )
2317{
2318  assert( lsIdx >= 0 ); 
2319  assert( lsIdx <= getVpsNumLayerSetsMinus1() ); 
2320  return (Int) m_layerSetLayerIdList[ lsIdx ].size(); 
2321}
2322
2323Int    TComVPS::getNumOutputLayerSets() 
2324{
2325  return getNumAddOlss() + getNumLayerSets(); 
2326}
2327
2328Int TComVPS::getNumViews()
2329{
2330  Int numViews = 1; 
2331  for( Int i = 0; i <=  getMaxLayersMinus1(); i++ )
2332  {
2333    Int lId = getLayerIdInNuh( i ); 
2334    if ( i > 0 && ( getViewIndex( lId ) != getScalabilityId( i - 1, VIEW_ORDER_INDEX ) ) )
2335    {
2336      numViews++; 
2337    }   
2338  }
2339
2340  return numViews;
2341}
2342
2343Bool TComVPS::getInDirectDependencyFlag( Int depLayeridInVps, Int refLayeridInVps, Int depth /*= 0 */ )
2344{
2345  assert( depth < 65 ); 
2346  Bool dependentFlag = getDirectDependencyFlag( depLayeridInVps, refLayeridInVps ); 
2347
2348  for( Int i = 0; i < depLayeridInVps && !dependentFlag; i++ )
2349  {
2350    if ( getDirectDependencyFlag( depLayeridInVps, i ) )
2351    {
2352      dependentFlag = getInDirectDependencyFlag( i, refLayeridInVps, depth++ ); 
2353    }
2354  }
2355  return dependentFlag;
2356}
2357
2358Void TComVPS::deriveLayerSetLayerIdList()
2359{
2360  m_layerSetLayerIdList.resize( getVpsNumLayerSetsMinus1() + 1 ); 
2361  for (Int i = 0; i <= getVpsNumLayerSetsMinus1(); i++ )
2362  {
2363    for( Int m = 0; m  <= getVpsMaxLayerId(); m++ )
2364    {
2365      if( getLayerIdIncludedFlag( i, m) ) 
2366      {
2367        m_layerSetLayerIdList[ i ].push_back( m );       
2368      }
2369    }
2370  }
2371}
2372
2373Void TComVPS::initTargetLayerIdLists()
2374{
2375  m_targetDecLayerIdLists.resize( getNumOutputLayerSets() ); 
2376  m_targetOptLayerIdLists.resize( getNumOutputLayerSets() ); 
2377}
2378
2379Void TComVPS::deriveTargetLayerIdList( Int i )
2380{ 
2381  Int lsIdx = olsIdxToLsIdx( i );     
2382 
2383  for( Int j = 0; j < getNumLayersInIdList( lsIdx ); j++ )
2384  {
2385    m_targetDecLayerIdLists[i].push_back( m_layerSetLayerIdList[ lsIdx ][ j ] ); 
2386    if( getOutputLayerFlag( i, j  ))
2387    {
2388      m_targetOptLayerIdLists[i].push_back( m_layerSetLayerIdList[ lsIdx ][ j ] );
2389    }
2390  } 
2391  assert( getNumOutputLayersInOutputLayerSet( i ) > 0 ); 
2392}
2393
2394Bool TComVPS::inferOutputLayerFlag( Int i, Int j )
2395{
2396  Bool outputLayerFlag; 
2397  switch ( getDefaultOutputLayerIdc( ) )
2398  {
2399  case 0:
2400    outputLayerFlag = true; 
2401    break; 
2402  case 1:
2403    outputLayerFlag = ( j == m_layerSetLayerIdList[ olsIdxToLsIdx( i ) ].size() - 1 ); 
2404    break;
2405  case 2:
2406    if ( i == 0 && j == 0)
2407    {     
2408      outputLayerFlag = true;  // This is a software only fix for a bug in the spec. In spec outputLayerFlag is neither present nor inferred.
2409    }
2410    else
2411    {
2412      assert( 0 ); 
2413    }
2414    break; 
2415  default:     
2416    assert( 0 );
2417    break; 
2418  }
2419  return outputLayerFlag;
2420}
2421
2422Int TComVPS::getMaxSubLayersInLayerSetMinus1( Int i )
2423{
2424  Int maxSLMinus1 = 0; 
2425  for( Int k = 0; k < getNumLayersInIdList( i ); k++ )
2426  {
2427    Int lId = m_layerSetLayerIdList[i][k];
2428    maxSLMinus1 = std::max( maxSLMinus1, getSubLayersVpsMaxMinus1( getLayerIdInVps( lId ) ));
2429  }
2430  return maxSLMinus1;
2431}
2432
2433Void TComVPS::inferDbpSizeLayerSetZero( TComSPS* sps, Bool encoder )
2434{
2435  for( Int j = 0; j <= getMaxSubLayersInLayerSetMinus1( 0 ); j++ )
2436  {
2437    Int maxDecPicBufferingMinus1 = sps->getMaxDecPicBuffering( j ) - 1; 
2438    Int numReorderPics           = sps->getNumReorderPics    ( j ); 
2439    Int maxLatencyIncreasePlus1  = sps->getMaxLatencyIncrease( j ); 
2440
2441    if ( encoder )
2442    {
2443      assert( getDpbSize()->getMaxVpsDecPicBufferingMinus1(0, 0, j ) == maxDecPicBufferingMinus1 );
2444      assert( getDpbSize()->getMaxVpsNumReorderPics       (0,    j ) == numReorderPics           );
2445      assert( getDpbSize()->getMaxVpsLatencyIncreasePlus1 (0,    j ) == maxLatencyIncreasePlus1  );
2446    }
2447    else
2448    {
2449      getDpbSize()->setMaxVpsDecPicBufferingMinus1(0, 0, j, maxDecPicBufferingMinus1 );
2450      getDpbSize()->setMaxVpsNumReorderPics       (0,    j, numReorderPics           );
2451      getDpbSize()->setMaxVpsLatencyIncreasePlus1 (0,    j, maxLatencyIncreasePlus1  );       
2452    }     
2453  }
2454}
2455
2456Bool TComVPS::getAltOutputLayerFlagVar( Int i )
2457{
2458  // Semantics variable not syntax element !
2459
2460  Bool altOptLayerFlag = false;     
2461  if ( i > 0 && getNumOutputLayersInOutputLayerSet( i ) == 1 && 
2462    getNumDirectRefLayers( getOlsHighestOutputLayerId( i ) ) > 0 )
2463  {
2464    altOptLayerFlag = getAltOutputLayerFlag( i ); 
2465  }
2466  return altOptLayerFlag;
2467}
2468
2469Int TComVPS::getMaxNumPics( Int layerId )
2470{
2471  Int maxNumPics = MAX_INT; 
2472  for( Int olsIdx = 0; olsIdx < getNumOutputLayerSets(); olsIdx++)
2473  {
2474    Int lsIdx = olsIdxToLsIdx( olsIdx ); 
2475    for( Int j = 0; j < getNumLayersInIdList( lsIdx ); j++ )
2476    {
2477      if( getLayerSetLayerIdList(lsIdx, j ) ==  layerId )
2478      {
2479        Int maxSL = getMaxSubLayersInLayerSetMinus1( lsIdx ); 
2480        maxNumPics = std::min( maxNumPics, getDpbSize()->getMaxVpsDecPicBufferingMinus1( olsIdx , j,  maxSL ) );
2481      }
2482    }
2483  }
2484  assert( maxNumPics != MAX_INT ); 
2485  return maxNumPics;
2486}
2487
2488Void TComVPS::xSetRefLayerFlags( Int currLayerId )
2489{
2490  for( Int j = 0; j < getNumDirectRefLayers( currLayerId ); j++ )
2491  {
2492    Int refLayerId = m_refLayerId[ currLayerId ][ j ];
2493    m_recursiveRefLayerFlag[ currLayerId ][ refLayerId ] = 1;
2494    for( Int k = 0; k < MAX_NUM_LAYER_IDS; k++ )
2495    {
2496      m_recursiveRefLayerFlag[ currLayerId ][ k ] = m_recursiveRefLayerFlag[ currLayerId ][ k ]  ||  m_recursiveRefLayerFlag[ refLayerId ][ k ];
2497    }
2498  }
2499}
2500
2501#endif // H_MV
2502
2503// ------------------------------------------------------------------------------------------------
2504// Sequence parameter set (SPS)
2505// ------------------------------------------------------------------------------------------------
2506
2507TComSPS::TComSPS()
2508: m_SPSId                     (  0)
2509, m_VPSId                     (  0)
2510, m_chromaFormatIdc           (CHROMA_420)
2511, m_uiMaxTLayers              (  1)
2512// Structure
2513, m_picWidthInLumaSamples     (352)
2514, m_picHeightInLumaSamples    (288)
2515, m_log2MinCodingBlockSize    (  0)
2516, m_log2DiffMaxMinCodingBlockSize (0)
2517, m_uiMaxCUWidth              ( 32)
2518, m_uiMaxCUHeight             ( 32)
2519, m_uiMaxCUDepth              (  3)
2520, m_bLongTermRefsPresent      (false)
2521, m_uiQuadtreeTULog2MaxSize   (  0)
2522, m_uiQuadtreeTULog2MinSize   (  0)
2523, m_uiQuadtreeTUMaxDepthInter (  0)
2524, m_uiQuadtreeTUMaxDepthIntra (  0)
2525// Tool list
2526, m_usePCM                   (false)
2527, m_pcmLog2MaxSize            (  5)
2528, m_uiPCMLog2MinSize          (  7)
2529#if !MTK_I0099_VPS_EX2
2530#if H_3D_QTLPC
2531, m_bUseQTL                   (false)
2532, m_bUsePC                    (false)
2533#endif
2534#endif
2535, m_bitDepthY                 (  8)
2536, m_bitDepthC                 (  8)
2537, m_qpBDOffsetY               (  0)
2538, m_qpBDOffsetC               (  0)
2539, m_uiPCMBitDepthLuma         (  8)
2540, m_uiPCMBitDepthChroma       (  8)
2541, m_bPCMFilterDisableFlag     (false)
2542, m_uiBitsForPOC              (  8)
2543, m_numLongTermRefPicSPS    (  0) 
2544, m_uiMaxTrSize               ( 32)
2545, m_bUseSAO                   (false) 
2546, m_bTemporalIdNestingFlag    (false)
2547, m_scalingListEnabledFlag    (false)
2548, m_useStrongIntraSmoothing   (false)
2549, m_vuiParametersPresentFlag  (false)
2550, m_vuiParameters             ()
2551#if H_MV
2552, m_pcVPS                     ( NULL )
2553, m_spsInferScalingListFlag   ( false )
2554, m_spsScalingListRefLayerId  ( 0 )
2555
2556, m_updateRepFormatFlag       ( false ) 
2557, m_spsRepFormatIdx           ( 0 )
2558, m_interViewMvVertConstraintFlag (false)
2559#endif
2560#if H_3D
2561, m_bCamParInSliceHeader      (false)
2562#endif
2563{
2564  for ( Int i = 0; i < MAX_TLAYER; i++ )
2565  {
2566    m_uiMaxLatencyIncrease[i] = 0;
2567    m_uiMaxDecPicBuffering[i] = 1;
2568    m_numReorderPics[i]       = 0;
2569  }
2570  m_scalingList = new TComScalingList;
2571  ::memset(m_ltRefPicPocLsbSps, 0, sizeof(m_ltRefPicPocLsbSps));
2572  ::memset(m_usedByCurrPicLtSPSFlag, 0, sizeof(m_usedByCurrPicLtSPSFlag));
2573#if H_MV
2574  m_spsRangeExtensionsFlag     = false;
2575  m_spsMultilayerExtensionFlag = false;
2576#if H_3D
2577  m_spsExtension5bits          = 0;
2578  m_sps3dExtensionFlag         = false; 
2579#else
2580  m_spsExtension6bits          = 0;
2581#endif
2582
2583  m_numScaledRefLayerOffsets = 0; 
2584
2585  for (Int i = 0; i < MAX_NUM_SCALED_REF_LAYERS; i++ )
2586  {
2587    m_scaledRefLayerId             [i] = -1;
2588  }
2589
2590  for (Int i = 0; i < MAX_NUM_LAYERS; i++ )
2591  {
2592    m_scaledRefLayerLeftOffset     [i] = 0;
2593    m_scaledRefLayerTopOffset      [i] = 0;
2594    m_scaledRefLayerRightOffset    [i] = 0;
2595    m_scaledRefLayerBottomOffset   [i] = 0;
2596  }
2597#endif
2598}
2599
2600TComSPS::~TComSPS()
2601{
2602  delete m_scalingList;
2603  m_RPSList.destroy();
2604}
2605
2606Void  TComSPS::createRPSList( Int numRPS )
2607{ 
2608  m_RPSList.destroy();
2609  m_RPSList.create(numRPS);
2610}
2611
2612Void TComSPS::setHrdParameters( UInt frameRate, UInt numDU, UInt bitRate, Bool randomAccess )
2613{
2614  if( !getVuiParametersPresentFlag() )
2615  {
2616    return;
2617  }
2618
2619  TComVUI *vui = getVuiParameters();
2620  TComHRD *hrd = vui->getHrdParameters();
2621
2622  TimingInfo *timingInfo = vui->getTimingInfo();
2623  timingInfo->setTimingInfoPresentFlag( true );
2624  switch( frameRate )
2625  {
2626  case 24:
2627    timingInfo->setNumUnitsInTick( 1125000 );    timingInfo->setTimeScale    ( 27000000 );
2628    break;
2629  case 25:
2630    timingInfo->setNumUnitsInTick( 1080000 );    timingInfo->setTimeScale    ( 27000000 );
2631    break;
2632  case 30:
2633    timingInfo->setNumUnitsInTick( 900900 );     timingInfo->setTimeScale    ( 27000000 );
2634    break;
2635  case 50:
2636    timingInfo->setNumUnitsInTick( 540000 );     timingInfo->setTimeScale    ( 27000000 );
2637    break;
2638  case 60:
2639    timingInfo->setNumUnitsInTick( 450450 );     timingInfo->setTimeScale    ( 27000000 );
2640    break;
2641  default:
2642    timingInfo->setNumUnitsInTick( 1001 );       timingInfo->setTimeScale    ( 60000 );
2643    break;
2644  }
2645
2646  Bool rateCnt = ( bitRate > 0 );
2647  hrd->setNalHrdParametersPresentFlag( rateCnt );
2648  hrd->setVclHrdParametersPresentFlag( rateCnt );
2649
2650  hrd->setSubPicCpbParamsPresentFlag( ( numDU > 1 ) );
2651
2652  if( hrd->getSubPicCpbParamsPresentFlag() )
2653  {
2654    hrd->setTickDivisorMinus2( 100 - 2 );                          //
2655    hrd->setDuCpbRemovalDelayLengthMinus1( 7 );                    // 8-bit precision ( plus 1 for last DU in AU )
2656    hrd->setSubPicCpbParamsInPicTimingSEIFlag( true );
2657    hrd->setDpbOutputDelayDuLengthMinus1( 5 + 7 );                 // With sub-clock tick factor of 100, at least 7 bits to have the same value as AU dpb delay
2658  }
2659  else
2660  {
2661    hrd->setSubPicCpbParamsInPicTimingSEIFlag( false ); 
2662  }
2663
2664  hrd->setBitRateScale( 4 );                                       // in units of 2~( 6 + 4 ) = 1,024 bps
2665  hrd->setCpbSizeScale( 6 );                                       // in units of 2~( 4 + 4 ) = 1,024 bit
2666  hrd->setDuCpbSizeScale( 6 );                                       // in units of 2~( 4 + 4 ) = 1,024 bit
2667 
2668  hrd->setInitialCpbRemovalDelayLengthMinus1(15);                  // assuming 0.5 sec, log2( 90,000 * 0.5 ) = 16-bit
2669  if( randomAccess )
2670  {
2671    hrd->setCpbRemovalDelayLengthMinus1(5);                        // 32 = 2^5 (plus 1)
2672    hrd->setDpbOutputDelayLengthMinus1 (5);                        // 32 + 3 = 2^6
2673  }
2674  else
2675  {
2676    hrd->setCpbRemovalDelayLengthMinus1(9);                        // max. 2^10
2677    hrd->setDpbOutputDelayLengthMinus1 (9);                        // max. 2^10
2678  }
2679
2680/*
2681   Note: only the case of "vps_max_temporal_layers_minus1 = 0" is supported.
2682*/
2683  Int i, j;
2684  UInt birateValue, cpbSizeValue;
2685  UInt ducpbSizeValue;
2686  UInt duBitRateValue = 0;
2687
2688  for( i = 0; i < MAX_TLAYER; i ++ )
2689  {
2690    hrd->setFixedPicRateFlag( i, 1 );
2691    hrd->setPicDurationInTcMinus1( i, 0 );
2692    hrd->setLowDelayHrdFlag( i, 0 );
2693    hrd->setCpbCntMinus1( i, 0 );
2694
2695    birateValue  = bitRate;
2696    cpbSizeValue = bitRate;                                     // 1 second
2697    ducpbSizeValue = bitRate/numDU;
2698    duBitRateValue = bitRate;
2699    for( j = 0; j < ( hrd->getCpbCntMinus1( i ) + 1 ); j ++ )
2700    {
2701      hrd->setBitRateValueMinus1( i, j, 0, ( birateValue  - 1 ) );
2702      hrd->setCpbSizeValueMinus1( i, j, 0, ( cpbSizeValue - 1 ) );
2703      hrd->setDuCpbSizeValueMinus1( i, j, 0, ( ducpbSizeValue - 1 ) );
2704      hrd->setCbrFlag( i, j, 0, ( j == 0 ) );
2705
2706      hrd->setBitRateValueMinus1( i, j, 1, ( birateValue  - 1) );
2707      hrd->setCpbSizeValueMinus1( i, j, 1, ( cpbSizeValue - 1 ) );
2708      hrd->setDuCpbSizeValueMinus1( i, j, 1, ( ducpbSizeValue - 1 ) );
2709      hrd->setDuBitRateValueMinus1( i, j, 1, ( duBitRateValue - 1 ) );
2710      hrd->setCbrFlag( i, j, 1, ( j == 0 ) );
2711    }
2712  }
2713}
2714const Int TComSPS::m_winUnitX[]={1,2,2,1};
2715const Int TComSPS::m_winUnitY[]={1,2,1,1};
2716
2717TComPPS::TComPPS()
2718: m_PPSId                       (0)
2719, m_SPSId                       (0)
2720, m_picInitQPMinus26            (0)
2721, m_useDQP                      (false)
2722, m_bConstrainedIntraPred       (false)
2723, m_bSliceChromaQpFlag          (false)
2724, m_pcSPS                       (NULL)
2725, m_uiMaxCuDQPDepth             (0)
2726, m_uiMinCuDQPSize              (0)
2727, m_chromaCbQpOffset            (0)
2728, m_chromaCrQpOffset            (0)
2729, m_numRefIdxL0DefaultActive    (1)
2730, m_numRefIdxL1DefaultActive    (1)
2731, m_TransquantBypassEnableFlag  (false)
2732, m_useTransformSkip             (false)
2733, m_dependentSliceSegmentsEnabledFlag    (false)
2734, m_tilesEnabledFlag               (false)
2735, m_entropyCodingSyncEnabledFlag   (false)
2736, m_loopFilterAcrossTilesEnabledFlag  (true)
2737, m_uniformSpacingFlag           (0)
2738, m_iNumColumnsMinus1            (0)
2739, m_puiColumnWidth               (NULL)
2740, m_iNumRowsMinus1               (0)
2741, m_puiRowHeight                 (NULL)
2742, m_iNumSubstreams             (1)
2743, m_signHideFlag(0)
2744, m_cabacInitPresentFlag        (false)
2745, m_encCABACTableIdx            (I_SLICE)
2746, m_sliceHeaderExtensionPresentFlag    (false)
2747, m_loopFilterAcrossSlicesEnabledFlag (false)
2748, m_listsModificationPresentFlag(  0)
2749, m_numExtraSliceHeaderBits(0)
2750#if H_MV
2751, m_ppsInferScalingListFlag(false)
2752, m_ppsScalingListRefLayerId(0)
2753, m_pocResetInfoPresentFlag(false)
2754#if H_3D
2755, m_pcDLT(NULL)
2756#endif
2757#endif
2758{
2759  m_scalingList = new TComScalingList;
2760
2761#if H_MV
2762  m_ppsRangeExtensionsFlag     = false;
2763  m_ppsMultilayerExtensionFlag = false;
2764#if !H_3D
2765  m_ppsExtension6bits          = 0;
2766#else
2767  m_pps3dExtensionFlag         = false;
2768  m_ppsExtension5bits          = 0;
2769#endif
2770#endif
2771}
2772
2773TComPPS::~TComPPS()
2774{
2775  if( m_iNumColumnsMinus1 > 0 && m_uniformSpacingFlag == 0 )
2776  {
2777    if (m_puiColumnWidth) delete [] m_puiColumnWidth; 
2778    m_puiColumnWidth = NULL;
2779  }
2780  if( m_iNumRowsMinus1 > 0 && m_uniformSpacingFlag == 0 )
2781  {
2782    if (m_puiRowHeight) delete [] m_puiRowHeight;
2783    m_puiRowHeight = NULL;
2784  }
2785  delete m_scalingList;
2786}
2787
2788#if H_3D
2789TComDLT::TComDLT()
2790: m_bDltPresentFlag(false)
2791, m_iNumDepthViews(0)
2792, m_uiDepthViewBitDepth(8)
2793{
2794  m_uiDepthViewBitDepth = g_bitDepthY; 
2795
2796  for( Int i = 0; i < MAX_NUM_LAYERS; i++ )
2797  {
2798    m_bUseDLTFlag                 [i] = false;
2799    m_bInterViewDltPredEnableFlag [i] = false;
2800
2801    // allocate some memory and initialize with default mapping
2802    m_iNumDepthmapValues[i] = ((1 << m_uiDepthViewBitDepth)-1)+1;
2803    m_iBitsPerDepthValue[i] = numBitsForValue(m_iNumDepthmapValues[i]);
2804
2805    m_iDepthValue2Idx[i]    = (Int*) xMalloc(Int, m_iNumDepthmapValues[i]);
2806    m_iIdx2DepthValue[i]    = (Int*) xMalloc(Int, m_iNumDepthmapValues[i]);
2807
2808    //default mapping
2809    for (Int d=0; d<m_iNumDepthmapValues[i]; d++)
2810    {
2811      m_iDepthValue2Idx[i][d] = d;
2812      m_iIdx2DepthValue[i][d] = d;
2813    }
2814  }
2815}
2816
2817TComDLT::~TComDLT()
2818{
2819  for( Int i = 0; i < MAX_NUM_LAYERS; i++ )
2820  {
2821    if ( m_iDepthValue2Idx[i] != NULL ) 
2822    {
2823      xFree( m_iDepthValue2Idx[i] );
2824      m_iDepthValue2Idx[i] = NULL; 
2825    }
2826
2827    if ( m_iIdx2DepthValue[i] != NULL ) 
2828    {
2829      xFree( m_iIdx2DepthValue[i] );
2830      m_iIdx2DepthValue[i] = NULL; 
2831    }
2832  }
2833}
2834
2835Void TComDLT::setDepthLUTs(Int layerIdInVps, Int* idxToDepthValueTable, Int iNumDepthValues)
2836{
2837  if( idxToDepthValueTable == NULL || iNumDepthValues == 0 ) // default mapping only
2838    return;
2839
2840  // copy idx2DepthValue to internal array
2841  memcpy(m_iIdx2DepthValue[layerIdInVps], idxToDepthValueTable, iNumDepthValues*sizeof(UInt));
2842
2843  UInt uiMaxDepthValue = ((1 << g_bitDepthY)-1);
2844  for(Int p=0; p<=uiMaxDepthValue; p++)
2845  {
2846    Int iIdxDown    = 0;
2847    Int iIdxUp      = iNumDepthValues-1;
2848    Bool bFound     = false;
2849
2850    // iterate over indices to find lower closest depth
2851    Int i = 1;
2852    while(!bFound && i<iNumDepthValues)
2853    {
2854      if( m_iIdx2DepthValue[layerIdInVps][i] > p )
2855      {
2856        iIdxDown  = i-1;
2857        bFound    = true;
2858      }
2859
2860      i++;
2861    }
2862    // iterate over indices to find upper closest depth
2863    i = iNumDepthValues-2;
2864    bFound = false;
2865    while(!bFound && i>=0)
2866    {
2867      if( m_iIdx2DepthValue[layerIdInVps][i] < p )
2868      {
2869        iIdxUp  = i+1;
2870        bFound    = true;
2871      }
2872
2873      i--;
2874    }
2875
2876    // assert monotony
2877    assert(iIdxDown<=iIdxUp);
2878
2879    // assign closer depth value/idx
2880    if( abs(p-m_iIdx2DepthValue[layerIdInVps][iIdxDown]) < abs(p-m_iIdx2DepthValue[layerIdInVps][iIdxUp]) )
2881    {
2882      m_iDepthValue2Idx[layerIdInVps][p] = iIdxDown;
2883    }
2884    else
2885    {
2886      m_iDepthValue2Idx[layerIdInVps][p] = iIdxUp;
2887    }
2888
2889  }
2890
2891  // update DLT variables
2892  m_iNumDepthmapValues[layerIdInVps] = iNumDepthValues;
2893  m_iBitsPerDepthValue[layerIdInVps] = numBitsForValue(m_iNumDepthmapValues[layerIdInVps]);
2894}
2895
2896#if H_3D_DELTA_DLT
2897Void TComDLT::getDeltaDLT( Int layerIdInVps, Int* piDLTInRef, UInt uiDLTInRefNum, Int* piDeltaDLTOut, UInt *puiDeltaDLTOutNum )
2898{
2899  Bool abBM0[ 256 ];
2900  Bool abBM1[ 256 ];
2901 
2902  memset( abBM0, 0, sizeof( abBM0 ));
2903  memset( abBM1, 0, sizeof( abBM1 ));
2904 
2905  // convert reference DLT to bit string
2906  for( Int i = 0; i < uiDLTInRefNum; i++ )
2907  {
2908    abBM0[ piDLTInRef[ i ] ] = true;
2909  }
2910  // convert internal DLT to bit string
2911  for( Int i = 0; i < m_iNumDepthmapValues[ layerIdInVps ]; i++ )
2912  {
2913    abBM1[ m_iIdx2DepthValue[ layerIdInVps ][ i ] ] = true;
2914  }
2915 
2916  *puiDeltaDLTOutNum = 0;
2917  for( Int i = 0; i < 256; i++ )
2918  {
2919    if( abBM0[ i ] ^ abBM1[ i ] )
2920    {
2921      piDeltaDLTOut[ *puiDeltaDLTOutNum ] = i;
2922      *puiDeltaDLTOutNum = *puiDeltaDLTOutNum + 1;
2923    }
2924  }
2925}
2926
2927Void TComDLT::setDeltaDLT( Int layerIdInVps, Int* piDLTInRef, UInt uiDLTInRefNum, Int* piDeltaDLTIn, UInt uiDeltaDLTInNum )
2928{
2929  Bool abBM0[ 256 ];
2930  Bool abBM1[ 256 ];
2931 
2932  memset( abBM0, 0, sizeof( abBM0 ));
2933  memset( abBM1, 0, sizeof( abBM1 ));
2934 
2935  // convert reference DLT to bit string
2936  for( Int i = 0; i < uiDLTInRefNum; i++ )
2937  {
2938    abBM0[ piDLTInRef[ i ] ] = true;
2939  }
2940  // convert delta DLT to bit string
2941  for( Int i = 0; i < uiDeltaDLTInNum; i++ )
2942  {
2943    abBM1[ piDeltaDLTIn[ i ] ] = true;
2944  }
2945 
2946  Int aiIdx2DepthValue[256];
2947  UInt uiNumDepthValues = 0;
2948  memset( aiIdx2DepthValue, 0, sizeof( aiIdx2DepthValue ));
2949 
2950  for( Int i = 0; i < 256; i++ )
2951  {
2952    if( abBM0[ i ] ^ abBM1[ i ] )
2953    {
2954      aiIdx2DepthValue[ uiNumDepthValues++ ] = i;
2955    }
2956  }
2957 
2958  // update internal tables
2959  setDepthLUTs(layerIdInVps, aiIdx2DepthValue, uiNumDepthValues);
2960}
2961#endif
2962
2963#endif
2964
2965#if H_MV
2966Void TComSPS::inferRepFormat( TComVPS* vps, Int layerIdCurr )
2967{
2968  if ( layerIdCurr > 0 )
2969  { 
2970    Int            repFormatIdx = getUpdateRepFormatFlag() ?  getSpsRepFormatIdx() : vps->getVpsRepFormatIdx( vps->getLayerIdInVps( layerIdCurr ) ) ;
2971    TComRepFormat* repFormat    = vps->getRepFormat( repFormatIdx ); 
2972      setChromaFormatIdc( repFormat->getChromaFormatVpsIdc() );         
2973      //// ToDo: add when supported:
2974      // setSeperateColourPlaneFlag( repFormat->getSeparateColourPlaneVpsFlag() ) ;
2975
2976      setPicWidthInLumaSamples ( repFormat->getPicWidthVpsInLumaSamples()  ); 
2977      setPicHeightInLumaSamples( repFormat->getPicHeightVpsInLumaSamples() ); 
2978
2979      setBitDepthY             ( repFormat->getBitDepthVpsLumaMinus8()   + 8 ); 
2980      setQpBDOffsetY           ( (Int) (6*( getBitDepthY() - 8 )) );
2981
2982      setBitDepthC             ( repFormat->getBitDepthVpsChromaMinus8() + 8 ); 
2983      setQpBDOffsetC           ( (Int) (6* ( getBitDepthC() -8 ) ) );
2984    if ( getLayerId() > 0 && getUpdateRepFormatFlag() )
2985    {
2986      assert( getChromaFormatIdc()      <=  repFormat->getChromaFormatVpsIdc()         ); 
2987      //// ToDo: add when supported:
2988      // assert( getSeperateColourPlaneFlag() <=  repFormat->getSeparateColourPlaneVpsFlag() ) ;
2989
2990      assert( getPicWidthInLumaSamples()  <= repFormat->getPicWidthVpsInLumaSamples()    ); 
2991      assert( getPicHeightInLumaSamples() <= repFormat->getPicHeightVpsInLumaSamples()   ); 
2992
2993      assert( getBitDepthY()              <= repFormat->getBitDepthVpsLumaMinus8()   + 8 );         
2994      assert( getBitDepthC()              <= repFormat->getBitDepthVpsChromaMinus8() + 8 ); 
2995    }
2996  }
2997
2998  // Set conformance window
2999  Int scal = TComSPS::getWinUnitX( getChromaFormatIdc() ) ;
3000  getConformanceWindow().scaleOffsets( scal );
3001  getVuiParameters()->getDefaultDisplayWindow().scaleOffsets( scal );
3002}
3003
3004Void TComSPS::inferScalingList( TComSPS* spsSrc )
3005{
3006  if ( getSpsInferScalingListFlag() ) 
3007  {
3008    assert( spsSrc != NULL ); 
3009    assert( !spsSrc->getSpsInferScalingListFlag() );             
3010    getScalingList()->inferFrom( spsSrc->getScalingList() ); 
3011  }
3012}
3013
3014Void TComSPS::inferSpsMaxDecPicBufferingMinus1( TComVPS* vps, Int targetOptLayerSetIdx, Int currLayerId, Bool encoder )
3015{
3016  const std::vector<Int>& targetDecLayerIdList = vps->getTargetDecLayerIdList( vps->olsIdxToLsIdx( targetOptLayerSetIdx )); 
3017
3018  if (getLayerId() > 0 )
3019  {
3020    Int layerIdx = 0;         
3021    while (layerIdx < (Int) targetDecLayerIdList.size() )
3022    {
3023      if ( targetDecLayerIdList[layerIdx] == currLayerId )
3024      { 
3025        break; 
3026      }
3027      layerIdx++; 
3028    }
3029
3030    assert( layerIdx < (Int) targetDecLayerIdList.size() ); 
3031
3032    for (Int i = 0; i <= getSpsMaxSubLayersMinus1(); i++ ) 
3033    {
3034      Int maxDecPicBufferingMinus1 = vps->getDpbSize()->getMaxVpsDecPicBufferingMinus1( targetOptLayerSetIdx, layerIdx, i ) ; 
3035
3036      if ( encoder )
3037      {
3038        assert( getMaxDecPicBuffering( i ) - 1 == maxDecPicBufferingMinus1 ); 
3039      }
3040      else
3041      {
3042        setMaxDecPicBuffering(i, maxDecPicBufferingMinus1 + 1 ); 
3043      }
3044    }
3045  }
3046}
3047
3048Void TComSPS::checkRpsMaxNumPics( TComVPS* vps, Int currLayerId )
3049{
3050  // In spec, when rps is in SPS, nuh_layer_id of SPS is used instead
3051  // of nuh_layer_id of slice (currLayerId), this seems to be a bug.
3052
3053  for (Int i = 0; i < getRPSList()->getNumberOfReferencePictureSets(); i++ )
3054  {
3055    TComReferencePictureSet* rps = getRPSList()->getReferencePictureSet( i ); 
3056    if ( !rps->getInterRPSPrediction() )
3057    {
3058      rps->checkMaxNumPics( vps->getVpsExtensionFlag(), vps->getMaxNumPics( currLayerId ), 
3059        getLayerId(), getMaxDecPicBuffering( getSpsMaxSubLayersMinus1() ) - 1 ); 
3060    }
3061  }
3062}
3063
3064#endif
3065
3066TComReferencePictureSet::TComReferencePictureSet()
3067: m_numberOfPictures (0)
3068, m_numberOfNegativePictures (0)
3069, m_numberOfPositivePictures (0)
3070, m_numberOfLongtermPictures (0)
3071, m_interRPSPrediction (0) 
3072, m_deltaRIdxMinus1 (0)   
3073, m_deltaRPS (0) 
3074, m_numRefIdc (0) 
3075{
3076  ::memset( m_deltaPOC, 0, sizeof(m_deltaPOC) );
3077  ::memset( m_POC, 0, sizeof(m_POC) );
3078  ::memset( m_used, 0, sizeof(m_used) );
3079  ::memset( m_refIdc, 0, sizeof(m_refIdc) );
3080}
3081
3082TComReferencePictureSet::~TComReferencePictureSet()
3083{
3084}
3085
3086Void TComReferencePictureSet::setUsed(Int bufferNum, Bool used)
3087{
3088  m_used[bufferNum] = used;
3089}
3090
3091Void TComReferencePictureSet::setDeltaPOC(Int bufferNum, Int deltaPOC)
3092{
3093  m_deltaPOC[bufferNum] = deltaPOC;
3094}
3095
3096Void TComReferencePictureSet::setNumberOfPictures(Int numberOfPictures)
3097{
3098  m_numberOfPictures = numberOfPictures;
3099}
3100
3101Int TComReferencePictureSet::getUsed(Int bufferNum)
3102{
3103  return m_used[bufferNum];
3104}
3105
3106Int TComReferencePictureSet::getDeltaPOC(Int bufferNum)
3107{
3108  return m_deltaPOC[bufferNum];
3109}
3110
3111Int TComReferencePictureSet::getNumberOfPictures()
3112{
3113  return m_numberOfPictures;
3114}
3115
3116Int TComReferencePictureSet::getPOC(Int bufferNum)
3117{
3118  return m_POC[bufferNum];
3119}
3120
3121Void TComReferencePictureSet::setPOC(Int bufferNum, Int POC)
3122{
3123  m_POC[bufferNum] = POC;
3124}
3125
3126Bool TComReferencePictureSet::getCheckLTMSBPresent(Int bufferNum)
3127{
3128  return m_bCheckLTMSB[bufferNum];
3129}
3130
3131Void TComReferencePictureSet::setCheckLTMSBPresent(Int bufferNum, Bool b)
3132{
3133  m_bCheckLTMSB[bufferNum] = b;
3134}
3135
3136/** set the reference idc value at uiBufferNum entry to the value of iRefIdc
3137 * \param uiBufferNum
3138 * \param iRefIdc
3139 * \returns Void
3140 */
3141Void TComReferencePictureSet::setRefIdc(Int bufferNum, Int refIdc)
3142{
3143  m_refIdc[bufferNum] = refIdc;
3144}
3145
3146/** get the reference idc value at uiBufferNum
3147 * \param uiBufferNum
3148 * \returns Int
3149 */
3150Int  TComReferencePictureSet::getRefIdc(Int bufferNum)
3151{
3152  return m_refIdc[bufferNum];
3153}
3154
3155/** Sorts the deltaPOC and Used by current values in the RPS based on the deltaPOC values.
3156 *  deltaPOC values are sorted with -ve values before the +ve values.  -ve values are in decreasing order.
3157 *  +ve values are in increasing order.
3158 * \returns Void
3159 */
3160Void TComReferencePictureSet::sortDeltaPOC()
3161{
3162  // sort in increasing order (smallest first)
3163  for(Int j=1; j < getNumberOfPictures(); j++)
3164  { 
3165    Int deltaPOC = getDeltaPOC(j);
3166    Bool used = getUsed(j);
3167    for (Int k=j-1; k >= 0; k--)
3168    {
3169      Int temp = getDeltaPOC(k);
3170      if (deltaPOC < temp)
3171      {
3172        setDeltaPOC(k+1, temp);
3173        setUsed(k+1, getUsed(k));
3174        setDeltaPOC(k, deltaPOC);
3175        setUsed(k, used);
3176      }
3177    }
3178  }
3179  // flip the negative values to largest first
3180  Int numNegPics = getNumberOfNegativePictures();
3181  for(Int j=0, k=numNegPics-1; j < numNegPics>>1; j++, k--)
3182  { 
3183    Int deltaPOC = getDeltaPOC(j);
3184    Bool used = getUsed(j);
3185    setDeltaPOC(j, getDeltaPOC(k));
3186    setUsed(j, getUsed(k));
3187    setDeltaPOC(k, deltaPOC);
3188    setUsed(k, used);
3189  }
3190}
3191
3192/** Prints the deltaPOC and RefIdc (if available) values in the RPS.
3193 *  A "*" is added to the deltaPOC value if it is Used bu current.
3194 * \returns Void
3195 */
3196Void TComReferencePictureSet::printDeltaPOC()
3197{
3198  printf("DeltaPOC = { ");
3199  for(Int j=0; j < getNumberOfPictures(); j++)
3200  {
3201    printf("%d%s ", getDeltaPOC(j), (getUsed(j)==1)?"*":"");
3202  } 
3203  if (getInterRPSPrediction()) 
3204  {
3205    printf("}, RefIdc = { ");
3206    for(Int j=0; j < getNumRefIdc(); j++)
3207    {
3208      printf("%d ", getRefIdc(j));
3209    } 
3210  }
3211  printf("}\n");
3212}
3213#if H_MV
3214Void TComReferencePictureSet::checkMaxNumPics( Bool vpsExtensionFlag, Int maxNumPics, Int nuhLayerId, Int spsMaxDecPicBufferingMinus1 )
3215{
3216  assert( getNumberOfPictures() >= 0 ); 
3217  if ( nuhLayerId == 0 )
3218  {
3219    assert( getNumberOfPictures() <= spsMaxDecPicBufferingMinus1 ); 
3220  }
3221
3222  if ( vpsExtensionFlag )
3223  {
3224    assert( getNumberOfPictures() <= maxNumPics );
3225  }
3226}
3227#endif
3228
3229TComRPSList::TComRPSList()
3230:m_referencePictureSets (NULL)
3231{
3232}
3233
3234TComRPSList::~TComRPSList()
3235{
3236}
3237
3238Void TComRPSList::create( Int numberOfReferencePictureSets)
3239{
3240  m_numberOfReferencePictureSets = numberOfReferencePictureSets;
3241  m_referencePictureSets = new TComReferencePictureSet[numberOfReferencePictureSets];
3242}
3243
3244Void TComRPSList::destroy()
3245{
3246  if (m_referencePictureSets)
3247  {
3248    delete [] m_referencePictureSets;
3249  }
3250  m_numberOfReferencePictureSets = 0;
3251  m_referencePictureSets = NULL;
3252}
3253
3254
3255
3256TComReferencePictureSet* TComRPSList::getReferencePictureSet(Int referencePictureSetNum)
3257{
3258  return &m_referencePictureSets[referencePictureSetNum];
3259}
3260
3261Int TComRPSList::getNumberOfReferencePictureSets()
3262{
3263  return m_numberOfReferencePictureSets;
3264}
3265
3266Void TComRPSList::setNumberOfReferencePictureSets(Int numberOfReferencePictureSets)
3267{
3268  m_numberOfReferencePictureSets = numberOfReferencePictureSets;
3269}
3270
3271TComRefPicListModification::TComRefPicListModification()
3272: m_bRefPicListModificationFlagL0 (false)
3273, m_bRefPicListModificationFlagL1 (false)
3274{
3275  ::memset( m_RefPicSetIdxL0, 0, sizeof(m_RefPicSetIdxL0) );
3276  ::memset( m_RefPicSetIdxL1, 0, sizeof(m_RefPicSetIdxL1) );
3277}
3278
3279TComRefPicListModification::~TComRefPicListModification()
3280{
3281}
3282
3283TComScalingList::TComScalingList()
3284{
3285  init();
3286}
3287TComScalingList::~TComScalingList()
3288{
3289  destroy();
3290}
3291
3292/** set default quantization matrix to array
3293*/
3294Void TComSlice::setDefaultScalingList()
3295{
3296  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
3297  {
3298    for(UInt listId=0;listId<g_scalingListNum[sizeId];listId++)
3299    {
3300      getScalingList()->processDefaultMatrix(sizeId, listId);
3301    }
3302  }
3303}
3304/** check if use default quantization matrix
3305 * \returns true if use default quantization matrix in all size
3306*/
3307Bool TComSlice::checkDefaultScalingList()
3308{
3309  UInt defaultCounter=0;
3310
3311  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
3312  {
3313    for(UInt listId=0;listId<g_scalingListNum[sizeId];listId++)
3314    {
3315      if( !memcmp(getScalingList()->getScalingListAddress(sizeId,listId), getScalingList()->getScalingListDefaultAddress(sizeId, listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])) // check value of matrix
3316     && ((sizeId < SCALING_LIST_16x16) || (getScalingList()->getScalingListDC(sizeId,listId) == 16))) // check DC value
3317      {
3318        defaultCounter++;
3319      }
3320    }
3321  }
3322  return (defaultCounter == (SCALING_LIST_NUM * SCALING_LIST_SIZE_NUM - 4)) ? false : true; // -4 for 32x32
3323}
3324
3325#if H_MV
3326Void TComSlice::createInterLayerReferencePictureSet( TComPicLists* ivPicLists, std::vector<TComPic*>& refPicSetInterLayer0, std::vector<TComPic*>& refPicSetInterLayer1 )
3327{
3328  refPicSetInterLayer0.clear(); 
3329  refPicSetInterLayer1.clear(); 
3330
3331  for( Int i = 0; i < getNumActiveRefLayerPics(); i++ ) 
3332  {
3333    Int layerIdRef = getRefPicLayerId( i ); 
3334    TComPic* picRef = ivPicLists->getPic( layerIdRef, getPOC() ) ; 
3335    assert ( picRef != 0 ); // There shall be no entry equal to "no reference picture" in RefPicSetInterLayer0 or RefPicSetInterLayer1.
3336
3337    picRef->getPicYuvRec()->extendPicBorder(); 
3338    picRef->setIsLongTerm( true );       
3339    picRef->getSlice(0)->setReferenced( true );       
3340
3341    Int viewIdCur  = getVPS()->getViewId( getLayerId() ); 
3342    Int viewIdZero = getVPS()->getViewId( 0 );
3343    Int viewIdRef  = getVPS()->getViewId( layerIdRef ); 
3344
3345    if (  ( viewIdCur <= viewIdZero && viewIdCur <= viewIdRef ) || ( viewIdCur >= viewIdZero && viewIdCur >= viewIdRef ) )
3346    {
3347      refPicSetInterLayer0.push_back( picRef ); 
3348    }
3349    else
3350    {
3351      refPicSetInterLayer1.push_back( picRef ); 
3352    }
3353    // Consider to check here:
3354    // "If the current picture is a RADL picture, there shall be no entry in the RefPicSetInterLayer0 and RefPicSetInterLayer1 that is a RASL picture. "   
3355    assert( picRef->getSlice(0)->getDiscardableFlag() == false ); // "There shall be no picture that has discardable_flag equal to 1 in RefPicSetInterLayer0 or RefPicSetInterLayer1".       
3356  }
3357}
3358
3359Void TComSlice::markIvRefPicsAsShortTerm( std::vector<TComPic*> refPicSetInterLayer0, std::vector<TComPic*> refPicSetInterLayer1 )
3360{
3361  // Mark as short-term
3362  for ( Int i = 0; i < refPicSetInterLayer0.size(); i++ ) 
3363  {
3364    refPicSetInterLayer0[i]->setIsLongTerm( false ); 
3365  }
3366
3367  for ( Int i = 0; i < refPicSetInterLayer1.size(); i++ ) 
3368  {
3369    refPicSetInterLayer1[i]->setIsLongTerm( false ); 
3370  }
3371
3372}
3373
3374Void TComSlice::printRefPicList()
3375{ 
3376  for ( Int li = 0; li < 2; li++)
3377  {   
3378    std::cout << std::endl << "RefPicListL" <<  li << ":" << std::endl; 
3379    for (Int rIdx = 0; rIdx <= (m_aiNumRefIdx[li]-1); rIdx ++)
3380    {     
3381      if (rIdx == 0 && li == 0) m_apcRefPicList[li][rIdx]->print( true );
3382       
3383      m_apcRefPicList[li][rIdx]->print( false );
3384    }
3385  }
3386}
3387
3388Void TComSlice::markCurrPic( TComPic* currPic )
3389{
3390  currPic->getSlice(0)->setReferenced( true ) ; 
3391  currPic->setIsLongTerm( false ); 
3392
3393  currPic->setReconMark( true );
3394  currPic->setPicOutputFlag( currPic->getSlice(0)->getPicOutputFlag() );
3395}
3396
3397Void TComSlice::setRefPicSetInterLayer( std::vector<TComPic*>* refPicSetInterLayer0, std::vector<TComPic*>* refPicSetInterLayer1 )
3398{
3399  m_refPicSetInterLayer0 = refPicSetInterLayer0; 
3400  m_refPicSetInterLayer1 = refPicSetInterLayer1; 
3401}
3402
3403TComPic* TComSlice::getPicFromRefPicSetInterLayer(Int setIdc, Int layerId )
3404{
3405  assert ( setIdc == 0 || setIdc == 1);   
3406  std::vector<TComPic*>* refPicSetInterLayer = ( setIdc == 0 ? m_refPicSetInterLayer0 : m_refPicSetInterLayer1);   
3407  assert( refPicSetInterLayer != 0 ); 
3408 
3409  TComPic* pcPic = NULL; 
3410  for ( Int i = 0; i < (*refPicSetInterLayer).size(); i++ )
3411  {
3412    if ((*refPicSetInterLayer)[ i ]->getLayerId() == layerId )
3413    {
3414      pcPic = (*refPicSetInterLayer)[ i ]; 
3415    }
3416  }
3417
3418  assert(pcPic != NULL); 
3419  return pcPic;
3420}
3421
3422
3423Int  TComSlice::getRefLayerPicFlag( Int i ) 
3424{
3425  TComVPS* vps = getVPS(); 
3426  Int refLayerIdx = vps->getLayerIdInVps( vps->getRefLayerId( getLayerId(), i ) ); 
3427
3428  Bool refLayerPicFlag = ( vps->getSubLayersVpsMaxMinus1( refLayerIdx ) >=  getTLayer() )  && ( getTLayer() == 0  ) &&
3429    ( vps->getMaxTidIlRefPicsPlus1( refLayerIdx, vps->getLayerIdInVps( getLayerId() )) > getTLayer() ); 
3430
3431  return refLayerPicFlag;       
3432}   
3433
3434Int TComSlice::getRefLayerPicIdc( Int j ) 
3435{ 
3436  Int refLayerPicIdc = -1; 
3437  Int curj = 0; 
3438  for( Int i = 0;  i < getVPS()->getNumDirectRefLayers( getLayerId()) ; i++ )
3439  {
3440    if( getRefLayerPicFlag( i ) )
3441    {
3442      if ( curj == j ) 
3443      {
3444        refLayerPicIdc = i;         
3445        break;
3446      }
3447      curj++; 
3448    }
3449  }
3450
3451  assert( curj == j ); 
3452  assert( refLayerPicIdc != -1 ); 
3453  return refLayerPicIdc; 
3454}
3455
3456Int  TComSlice::getNumRefLayerPics( )
3457{ 
3458  Int numRefLayerPics = 0; 
3459  for( Int i = 0;  i < getVPS()->getNumDirectRefLayers( getLayerId()) ; i++ )
3460  {
3461    numRefLayerPics += getRefLayerPicFlag( i ); 
3462  }
3463  return numRefLayerPics; 
3464}
3465
3466
3467
3468Int TComSlice::getNumActiveRefLayerPics()
3469{
3470  Int numActiveRefLayerPics; 
3471
3472  if( getLayerId() == 0 || getNumRefLayerPics() ==  0 )
3473  {
3474    numActiveRefLayerPics = 0; 
3475  }
3476  else if (getVPS()->getAllRefLayersActiveFlag() )
3477  {
3478    numActiveRefLayerPics = getNumRefLayerPics(); 
3479  }
3480  else if ( !getInterLayerPredEnabledFlag() )
3481  {
3482    numActiveRefLayerPics = 0; 
3483  }
3484  else if( getVPS()->getMaxOneActiveRefLayerFlag() || getVPS()->getNumDirectRefLayers( getLayerId() ) == 1 )
3485  {
3486    numActiveRefLayerPics = 1; 
3487  }
3488  else
3489  {
3490    numActiveRefLayerPics = getNumInterLayerRefPicsMinus1() + 1; 
3491  }
3492  return numActiveRefLayerPics;
3493}
3494
3495Int TComSlice::getRefPicLayerId( Int i )
3496{
3497  return getVPS()->getRefLayerId( getLayerId(), getInterLayerPredLayerIdc( i ) );
3498}
3499
3500#if H_3D_ARP
3501Void TComSlice::setARPStepNum( TComPicLists*ivPicLists )
3502{
3503  Bool tempRefPicInListsFlag = false;
3504  if(!getVPS()->getUseAdvRP(getLayerId()) || this->isIRAP())
3505  {
3506    m_nARPStepNum = 0;
3507  }
3508  else
3509  {
3510    setFirstTRefIdx (REF_PIC_LIST_0, -1);
3511    setFirstTRefIdx (REF_PIC_LIST_1, -1);
3512    for ( Int refListIdx = 0; refListIdx < ((m_eSliceType==B_SLICE) ? 2 : 1); refListIdx++ )
3513    {
3514      Int diffPOC=MAX_INT;
3515      Int idx=-1;
3516      for(Int i = 0; i < getNumRefIdx(RefPicList(refListIdx)); i++ )
3517      {
3518        if ( getRefPic(RefPicList(refListIdx), i)->getPOC() != getPOC() )
3519        {
3520          if( abs(getRefPic(RefPicList(refListIdx), i)->getPOC() - getPOC()) < diffPOC)
3521          {
3522            diffPOC=abs(getRefPic(RefPicList(refListIdx), i)->getPOC() - getPOC());
3523            idx=i;
3524          }
3525        }
3526        if(idx>=0)
3527        {
3528          setFirstTRefIdx (RefPicList(refListIdx), idx);
3529        }
3530      }
3531    }
3532    tempRefPicInListsFlag = getFirstTRefIdx(REF_PIC_LIST_0) >= 0 || getFirstTRefIdx(REF_PIC_LIST_1) >= 0;
3533    m_nARPStepNum = tempRefPicInListsFlag ? getVPS()->getARPStepNum(getLayerId()) : 0;
3534  }
3535
3536  if (tempRefPicInListsFlag)
3537  {
3538    for ( Int refListIdx = 0; refListIdx < ((m_eSliceType==B_SLICE) ? 2 : 1); refListIdx++ )
3539    {
3540      RefPicList eRefPicList = RefPicList( refListIdx );
3541      Int prevPOC = getRefPic(eRefPicList, getFirstTRefIdx(eRefPicList) )->getPOC();
3542      for( Int i = 0; i < getNumActiveRefLayerPics(); i++ )
3543      {
3544        Int layerIdInNuh = getRefPicLayerId( i );
3545        Int viewIdx = getVPS()->getViewId( layerIdInNuh );
3546        TComPic*pcPicPrev = ivPicLists->getPic(viewIdx, 0, prevPOC);
3547        if (getFirstTRefIdx(eRefPicList) >= 0 && pcPicPrev && pcPicPrev->getSlice( 0 )->isReferenced())
3548        {
3549          m_arpRefPicAvailable[eRefPicList][layerIdInNuh] = true;
3550        }
3551        else
3552        {
3553          m_arpRefPicAvailable[eRefPicList][layerIdInNuh] = false;
3554        }
3555      }
3556    }
3557  }
3558}
3559#endif
3560#if H_3D_IC
3561Void TComSlice::xSetApplyIC(Bool bUseLowLatencyICEnc)
3562{
3563  if(bUseLowLatencyICEnc)
3564  {
3565    Bool existInterViewRef=false;
3566    TComPic* pcCurrPic = getPic();
3567    TComPic* pcRefPic = NULL;
3568    for ( Int i = 0; (i < getNumRefIdx( REF_PIC_LIST_0 )) && !existInterViewRef; i++ )
3569    {
3570      pcRefPic = getRefPic( REF_PIC_LIST_0, i );
3571      if ( pcRefPic != NULL )
3572      {
3573        if ( pcCurrPic->getViewIndex() != pcRefPic->getViewIndex() )
3574        {
3575          existInterViewRef = true;       
3576        }
3577      }
3578    }
3579
3580    for ( Int i = 0; (i < getNumRefIdx( REF_PIC_LIST_1 )) && !existInterViewRef; i++ )
3581    {
3582      pcRefPic = getRefPic( REF_PIC_LIST_1, i );
3583      if ( pcRefPic != NULL )
3584      {
3585        if ( pcCurrPic->getViewIndex() != pcRefPic->getViewIndex() )
3586        {
3587          existInterViewRef = true;       
3588        }
3589      }
3590    }
3591
3592    if(!existInterViewRef)
3593    {
3594      m_bApplyIC = false;
3595    }
3596    else
3597    {
3598      Int curLayer=getDepth();
3599      if( curLayer>9) curLayer=9; // Max layer is 10
3600
3601      m_bApplyIC = true;
3602      Int refLayer = curLayer-1;
3603      if( (refLayer>=0) && (g_aICEnableCANDIDATE[refLayer]>0) )
3604      {   
3605        Double ratio=Double(g_aICEnableNUM[refLayer])/Double(g_aICEnableCANDIDATE[refLayer]);
3606
3607        if( ratio > IC_LOW_LATENCY_ENCODING_THRESHOLD)
3608{
3609          m_bApplyIC=true;
3610        }
3611        else
3612        {
3613          m_bApplyIC=false;
3614        }
3615      }
3616      g_aICEnableNUM[curLayer]=0;
3617      g_aICEnableCANDIDATE[curLayer]=0;
3618      g_lastlayer=getDepth();
3619    }
3620  }
3621  else
3622  {
3623  Int iMaxPelValue = ( 1 << g_bitDepthY ); 
3624  Int *aiRefOrgHist;
3625  Int *aiCurrHist;
3626  aiRefOrgHist = (Int *) xMalloc( Int,iMaxPelValue );
3627  aiCurrHist   = (Int *) xMalloc( Int,iMaxPelValue );
3628  memset( aiRefOrgHist, 0, iMaxPelValue*sizeof(Int) );
3629  memset( aiCurrHist, 0, iMaxPelValue*sizeof(Int) );
3630  // Reference Idx Number
3631  Int iNumRefIdx = getNumRefIdx( REF_PIC_LIST_0 );
3632  TComPic* pcCurrPic = NULL;
3633  TComPic* pcRefPic = NULL;
3634  TComPicYuv* pcCurrPicYuv = NULL;
3635  TComPicYuv* pcRefPicYuvOrg = NULL;
3636  pcCurrPic = getPic();
3637  pcCurrPicYuv = pcCurrPic->getPicYuvOrg();
3638  Int iWidth = pcCurrPicYuv->getWidth();
3639  Int iHeight = pcCurrPicYuv->getHeight();
3640
3641
3642  // Get InterView Reference picture
3643  // !!!!! Assume only one Interview Reference Picture in L0
3644  for ( Int i = 0; i < iNumRefIdx; i++ )
3645  {
3646    pcRefPic = getRefPic( REF_PIC_LIST_0, i );
3647    if ( pcRefPic != NULL )
3648    {
3649      if ( pcCurrPic->getViewIndex() != pcRefPic->getViewIndex() )
3650      {
3651        pcRefPicYuvOrg = pcRefPic->getPicYuvOrg();
3652      }
3653    }
3654  }
3655
3656  if ( pcRefPicYuvOrg != NULL )
3657  {
3658    Pel* pCurrY = pcCurrPicYuv ->getLumaAddr();
3659    Pel* pRefOrgY = pcRefPicYuvOrg  ->getLumaAddr();
3660    Int iCurrStride = pcCurrPicYuv->getStride();
3661    Int iRefStride = pcRefPicYuvOrg->getStride();
3662    Int iSumOrgSAD = 0;
3663    Double dThresholdOrgSAD = getIsDepth() ? 0.1 : 0.05;
3664
3665    // Histogram building - luminance
3666    for ( Int y = 0; y < iHeight; y++ )
3667    {
3668      for ( Int x = 0; x < iWidth; x++ )
3669      {
3670        aiCurrHist[pCurrY[x]]++;
3671        aiRefOrgHist[pRefOrgY[x]]++;
3672      }
3673      pCurrY += iCurrStride;
3674      pRefOrgY += iRefStride;
3675    }
3676    // Histogram SAD
3677    for ( Int i = 0; i < iMaxPelValue; i++ )
3678    {
3679      iSumOrgSAD += abs( aiCurrHist[i] - aiRefOrgHist[i] );
3680    }
3681    // Setting
3682    if ( iSumOrgSAD > Int( dThresholdOrgSAD * iWidth * iHeight ) )
3683    {
3684      m_bApplyIC = true;
3685    }
3686    else
3687    {
3688      m_bApplyIC = false;
3689    }
3690  }
3691
3692  xFree( aiCurrHist   );
3693  xFree( aiRefOrgHist );
3694  aiCurrHist = NULL;
3695  aiRefOrgHist = NULL;
3696  }//if(bUseLowLatencyICEnc)
3697}
3698#endif
3699#if H_3D
3700Void TComSlice::setIvPicLists( TComPicLists* m_ivPicLists )
3701{
3702  for (Int i = 0; i < MAX_NUM_LAYERS; i++ )
3703  {     
3704    for ( Int depthId = 0; depthId < 2; depthId++ )
3705    {
3706      m_ivPicsCurrPoc[ depthId ][ i ] = ( i <= m_viewIndex ) ? m_ivPicLists->getPic( i, ( depthId == 1) , getPOC() ) : NULL;
3707    }       
3708  } 
3709}
3710Void TComSlice::setDepthToDisparityLUTs()
3711{ 
3712  Bool setupLUT = false; 
3713  Int layerIdInVPS = getVPS()->getLayerIdInNuh( m_layerId ); 
3714
3715#if H_3D_VSP
3716  setupLUT = setupLUT || getVPS()->getViewSynthesisPredFlag( layerIdInVPS); 
3717#endif
3718
3719#if H_3D_NBDV_REF
3720  setupLUT = setupLUT || getVPS()->getDepthRefinementFlag( layerIdInVPS );
3721#endif
3722
3723#if H_3D_IV_MERGE
3724  setupLUT = setupLUT || ( getVPS()->getIvMvPredFlag(layerIdInVPS ) && getIsDepth() );
3725#endif
3726
3727#if H_3D_DDD
3728  if( getIsDepth() && getViewIndex() > 0 )
3729  {
3730      TComSlice *pcTextSlice = getTexturePic()->getSlice( 0 );
3731      memcpy( m_aiDDDInvScale, pcTextSlice->m_aiDDDInvScale, sizeof( Int ) * getViewIndex() );
3732      memcpy( m_aiDDDInvOffset, pcTextSlice->m_aiDDDInvOffset, sizeof( Int ) * getViewIndex() );
3733      memcpy( m_aiDDDShift, pcTextSlice->m_aiDDDShift, sizeof( Int ) * getViewIndex() );             
3734  } 
3735#endif
3736
3737  if( !setupLUT )
3738    return; 
3739
3740  /// GT: Allocation should be moved to a better place later;
3741  if ( m_depthToDisparityB == NULL )
3742  {
3743    m_depthToDisparityB = new Int*[ getViewIndex() ];
3744    for ( Int i = 0; i < getViewIndex(); i++ )
3745    {
3746      m_depthToDisparityB[ i ] = new Int[ Int(1 << g_bitDepthY) ]; 
3747    }
3748  }
3749
3750  if ( m_depthToDisparityF == NULL )
3751  {
3752    m_depthToDisparityF= new Int*[ getViewIndex() ];
3753    for ( Int i = 0; i < getViewIndex(); i++ )
3754    {
3755      m_depthToDisparityF[ i ] = new Int[ Int(1 << g_bitDepthY) ]; 
3756    }
3757  }
3758
3759  assert( m_depthToDisparityB != NULL ); 
3760  assert( m_depthToDisparityF != NULL ); 
3761
3762  TComVPS* vps = getVPS(); 
3763
3764  Int log2Div = g_bitDepthY - 1 + vps->getCamParPrecision();
3765  Int viewIndex = getViewIndex();
3766
3767  Bool camParaSH = vps->hasCamParInSliceHeader( viewIndex );
3768
3769  Int* codScale     = camParaSH ? m_aaiCodedScale [ 0 ] : vps->getCodedScale    ( viewIndex ); 
3770  Int* codOffset    = camParaSH ? m_aaiCodedOffset[ 0 ] : vps->getCodedOffset   ( viewIndex ); 
3771  Int* invCodScale  = camParaSH ? m_aaiCodedScale [ 1 ] : vps->getInvCodedScale ( viewIndex ); 
3772  Int* invCodOffset = camParaSH ? m_aaiCodedOffset[ 1 ] : vps->getInvCodedOffset( viewIndex ); 
3773
3774  for (Int i = 0; i <= ( getViewIndex() - 1); i++)
3775  {
3776    for ( Int d = 0; d <= ( ( 1 << g_bitDepthY ) - 1 ); d++ )
3777    {
3778      Int offset =    ( codOffset  [ i ] << g_bitDepthY ) + ( ( 1 << log2Div ) >> 1 );         
3779      m_depthToDisparityB[ i ][ d ] = ( codScale [ i ] * d + offset ) >> log2Div; 
3780
3781      Int invOffset = ( invCodOffset[ i ] << g_bitDepthY ) + ( ( 1 << log2Div ) >> 1 );         
3782      m_depthToDisparityF[ i ][ d ] = ( invCodScale[ i ] * d + invOffset ) >> log2Div; 
3783    }
3784
3785#if H_3D_DDD
3786    initializeDDDPara( vps->getCamParPrecision(), codScale[ i ], codOffset[ i ], i );
3787#endif
3788  }
3789}
3790#endif
3791#endif
3792
3793#if H_3D_DDD
3794Void TComSlice::initializeDDDPara( UInt uiCamParsCodedPrecision, Int  iCodedScale,Int  iCodedOffset, Int iBaseViewIdx )
3795{
3796    UInt uiViewId     = getViewIndex();
3797
3798    if( uiViewId == 0 )
3799    {
3800        m_aiDDDInvScale[ iBaseViewIdx ] = m_aiDDDInvOffset[ iBaseViewIdx ] = m_aiDDDShift[ iBaseViewIdx ] = 0;
3801        return;
3802    }
3803
3804
3805    Int iSign = iCodedScale >= 0 ? 1 : -1;
3806    iCodedScale = abs( iCodedScale );
3807
3808    Int iBitWidth = 0;
3809
3810    const Int iInvPres = 9;
3811
3812    while( ((( 1 << iBitWidth ) << 1 ) <= iCodedScale ) )
3813    {
3814        iBitWidth ++;
3815    }
3816    iBitWidth += iInvPres;
3817    Int iTargetValue =  1 << iBitWidth;
3818
3819    Int iMinError = MAX_INT;
3820    Int iBestD = 1 << ( iInvPres - 1 );
3821    for( Int d = 1 << ( iInvPres - 1 ); d < ( 1 << iInvPres ); d++ )
3822    {
3823        Int iError = abs( iCodedScale * d - iTargetValue );
3824        if( iError < iMinError )
3825        {
3826            iMinError = iError;
3827            iBestD = d;
3828        }
3829        if( iMinError == 0 )
3830        {
3831            break;
3832        }
3833    }
3834    Int iRoundingDir = 0;
3835    if( iCodedScale * iBestD > iTargetValue )
3836    {
3837        iRoundingDir = -1;
3838    }
3839    else if( iCodedScale * iBestD < iTargetValue )
3840    {
3841        iRoundingDir = 1;
3842    }
3843    Int iCamPres = uiCamParsCodedPrecision - 1;
3844    m_aiDDDInvScale [ iBaseViewIdx ] = ( iBestD << ( iCamPres + g_bitDepthY )) * iSign;
3845    m_aiDDDInvOffset[ iBaseViewIdx ] = -iSign * iBestD * ( iCodedOffset << g_bitDepthY );
3846    m_aiDDDShift    [ iBaseViewIdx ] = iBitWidth;
3847    m_aiDDDInvOffset[ iBaseViewIdx ] += 1 << ( m_aiDDDShift[ iBaseViewIdx ] - 1 );
3848    m_aiDDDInvOffset[ iBaseViewIdx ] += ( 1 << ( m_aiDDDShift[ iBaseViewIdx ] - 4 ) ) * iRoundingDir;
3849
3850    return;
3851}
3852
3853
3854#endif
3855
3856#if H_MV
3857Void TComSlice::checkCrossLayerBlaFlag()
3858{
3859  // 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.
3860  if ( getLayerId() != 0 || getNalUnitType() != NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )
3861  {
3862    assert( m_crossLayerBlaFlag == 0 ); 
3863  }
3864}
3865
3866Bool TComSlice::inferPocMsbValPresentFlag()
3867{
3868  Bool pocMsbValPresentFlag; 
3869  if( getSliceSegmentHeaderExtensionLength() == 0 ) 
3870  {
3871    pocMsbValPresentFlag = false; 
3872  }
3873  else if ( getPocMsbValRequiredFlag() )
3874  {
3875    pocMsbValPresentFlag = true; 
3876  }
3877  else
3878  {
3879    pocMsbValPresentFlag = false; 
3880  }
3881
3882  return pocMsbValPresentFlag;
3883}
3884
3885
3886#endif
3887
3888#if H_3D_DBBP
3889Int TComSlice::getDepthFromDV( Int iDV, Int iBaseViewIdx )
3890{
3891  return ClipY(( iDV * m_aiDDDInvScale[ iBaseViewIdx ] + m_aiDDDInvOffset[ iBaseViewIdx ] ) >> m_aiDDDShift[ iBaseViewIdx ]);
3892}
3893#endif
3894
3895/** get scaling matrix from RefMatrixID
3896 * \param sizeId size index
3897 * \param Index of input matrix
3898 * \param Index of reference matrix
3899 */
3900Void TComScalingList::processRefMatrix( UInt sizeId, UInt listId , UInt refListId )
3901{
3902  ::memcpy(getScalingListAddress(sizeId, listId),((listId == refListId)? getScalingListDefaultAddress(sizeId, refListId): getScalingListAddress(sizeId, refListId)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
3903}
3904
3905/** parse syntax infomation
3906 *  \param pchFile syntax infomation
3907 *  \returns false if successful
3908 */
3909Bool TComScalingList::xParseScalingList(Char* pchFile)
3910{
3911  FILE *fp;
3912  Char line[1024];
3913  UInt sizeIdc,listIdc;
3914  UInt i,size = 0;
3915  Int *src=0,data;
3916  Char *ret;
3917  UInt  retval;
3918
3919  if((fp = fopen(pchFile,"r")) == (FILE*)NULL)
3920  {
3921    printf("can't open file %s :: set Default Matrix\n",pchFile);
3922    return true;
3923  }
3924
3925  for(sizeIdc = 0; sizeIdc < SCALING_LIST_SIZE_NUM; sizeIdc++)
3926  {
3927    size = min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeIdc]);
3928    for(listIdc = 0; listIdc < g_scalingListNum[sizeIdc]; listIdc++)
3929    {
3930      src = getScalingListAddress(sizeIdc, listIdc);
3931
3932      fseek(fp,0,0);
3933      do 
3934      {
3935        ret = fgets(line, 1024, fp);
3936        if ((ret==NULL)||(strstr(line, MatrixType[sizeIdc][listIdc])==NULL && feof(fp)))
3937        {
3938          printf("Error: can't read Matrix :: set Default Matrix\n");
3939          return true;
3940        }
3941      }
3942      while (strstr(line, MatrixType[sizeIdc][listIdc]) == NULL);
3943      for (i=0; i<size; i++)
3944      {
3945        retval = fscanf(fp, "%d,", &data);
3946        if (retval!=1)
3947        {
3948          printf("Error: can't read Matrix :: set Default Matrix\n");
3949          return true;
3950        }
3951        src[i] = data;
3952      }
3953      //set DC value for default matrix check
3954      setScalingListDC(sizeIdc,listIdc,src[0]);
3955
3956      if(sizeIdc > SCALING_LIST_8x8)
3957      {
3958        fseek(fp,0,0);
3959        do 
3960        {
3961          ret = fgets(line, 1024, fp);
3962          if ((ret==NULL)||(strstr(line, MatrixType_DC[sizeIdc][listIdc])==NULL && feof(fp)))
3963          {
3964            printf("Error: can't read DC :: set Default Matrix\n");
3965            return true;
3966          }
3967        }
3968        while (strstr(line, MatrixType_DC[sizeIdc][listIdc]) == NULL);
3969        retval = fscanf(fp, "%d,", &data);
3970        if (retval!=1)
3971        {
3972          printf("Error: can't read Matrix :: set Default Matrix\n");
3973          return true;
3974        }
3975        //overwrite DC value when size of matrix is larger than 16x16
3976        setScalingListDC(sizeIdc,listIdc,data);
3977      }
3978    }
3979  }
3980  fclose(fp);
3981  return false;
3982}
3983
3984#if H_MV
3985Void TComScalingList::inferFrom( TComScalingList* srcScLi )
3986{
3987  for(Int sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
3988  {
3989    for(Int listId = 0; listId <  g_scalingListNum[sizeId]; listId++)
3990    {
3991      setRefMatrixId  (sizeId,listId, srcScLi->getRefMatrixId  (sizeId,listId));
3992      setScalingListDC(sizeId,listId, srcScLi->getScalingListDC(sizeId,listId));         
3993      ::memcpy(getScalingListAddress(sizeId, listId),srcScLi->getScalingListAddress(sizeId, listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
3994    }
3995  }
3996}
3997#endif
3998/** initialization process of quantization matrix array
3999 */
4000Void TComScalingList::init()
4001{
4002  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
4003  {
4004    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
4005    {
4006      m_scalingListCoef[sizeId][listId] = new Int [min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId])];
4007    }
4008  }
4009  m_scalingListCoef[SCALING_LIST_32x32][3] = m_scalingListCoef[SCALING_LIST_32x32][1]; // copy address for 32x32
4010}
4011
4012/** destroy quantization matrix array
4013 */
4014Void TComScalingList::destroy()
4015{
4016  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
4017  {
4018    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
4019    {
4020      if(m_scalingListCoef[sizeId][listId]) delete [] m_scalingListCoef[sizeId][listId];
4021    }
4022  }
4023}
4024
4025/** get default address of quantization matrix
4026 * \param sizeId size index
4027 * \param listId list index
4028 * \returns pointer of quantization matrix
4029 */
4030Int* TComScalingList::getScalingListDefaultAddress(UInt sizeId, UInt listId)
4031{
4032  Int *src = 0;
4033  switch(sizeId)
4034  {
4035    case SCALING_LIST_4x4:
4036      src = g_quantTSDefault4x4;
4037      break;
4038    case SCALING_LIST_8x8:
4039      src = (listId<3) ? g_quantIntraDefault8x8 : g_quantInterDefault8x8;
4040      break;
4041    case SCALING_LIST_16x16:
4042      src = (listId<3) ? g_quantIntraDefault8x8 : g_quantInterDefault8x8;
4043      break;
4044    case SCALING_LIST_32x32:
4045      src = (listId<1) ? g_quantIntraDefault8x8 : g_quantInterDefault8x8;
4046      break;
4047    default:
4048      assert(0);
4049      src = NULL;
4050      break;
4051  }
4052  return src;
4053}
4054
4055/** process of default matrix
4056 * \param sizeId size index
4057 * \param Index of input matrix
4058 */
4059Void TComScalingList::processDefaultMatrix(UInt sizeId, UInt listId)
4060{
4061  ::memcpy(getScalingListAddress(sizeId, listId),getScalingListDefaultAddress(sizeId,listId),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
4062  setScalingListDC(sizeId,listId,SCALING_LIST_DC);
4063}
4064
4065/** check DC value of matrix for default matrix signaling
4066 */
4067Void TComScalingList::checkDcOfMatrix()
4068{
4069  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
4070  {
4071    for(UInt listId = 0; listId < g_scalingListNum[sizeId]; listId++)
4072    {
4073      //check default matrix?
4074      if(getScalingListDC(sizeId,listId) == 0)
4075      {
4076        processDefaultMatrix(sizeId, listId);
4077      }
4078    }
4079  }
4080}
4081
4082ParameterSetManager::ParameterSetManager()
4083: m_vpsMap(MAX_NUM_VPS)
4084, m_spsMap(MAX_NUM_SPS)
4085, m_ppsMap(MAX_NUM_PPS)
4086, m_activeVPSId(-1)
4087#if !H_MV
4088, m_activeSPSId(-1)
4089, m_activePPSId(-1)
4090{
4091#else
4092{
4093  for (Int i = 0; i < MAX_NUM_LAYERS; i++ )
4094  {
4095    m_activeSPSId[ i ] = -1; 
4096    m_activePPSId[ i ] = -1; 
4097  }
4098#endif
4099}
4100
4101
4102ParameterSetManager::~ParameterSetManager()
4103{
4104}
4105
4106//! activate a SPS from a active parameter sets SEI message
4107//! \returns true, if activation is successful
4108#if H_MV
4109Bool ParameterSetManager::activateSPSWithSEI(Int spsId, Int layerId )
4110#else
4111Bool ParameterSetManager::activateSPSWithSEI(Int spsId)
4112#endif
4113{
4114  TComSPS *sps = m_spsMap.getPS(spsId);
4115  if (sps)
4116  {
4117    Int vpsId = sps->getVPSId();
4118    if (m_vpsMap.getPS(vpsId))
4119    {
4120      m_activeVPSId = vpsId;
4121#if H_MV
4122      m_activeSPSId[ layerId ] = spsId;
4123#else
4124      m_activeSPSId = spsId;
4125#endif
4126      return true;
4127    }
4128    else
4129    {
4130      printf("Warning: tried to activate SPS using an Active parameter sets SEI message. Referenced VPS does not exist.");
4131    }
4132  }
4133  else
4134  {
4135    printf("Warning: tried to activate non-existing SPS using an Active parameter sets SEI message.");
4136  }
4137  return false;
4138}
4139
4140//! activate a PPS and depending on isIDR parameter also SPS and VPS
4141//! \returns true, if activation is successful
4142#if H_MV
4143Bool ParameterSetManager::activatePPS(Int ppsId, Bool isIRAP, Int layerId )
4144#else
4145Bool ParameterSetManager::activatePPS(Int ppsId, Bool isIRAP)
4146#endif
4147{
4148  TComPPS *pps = m_ppsMap.getPS(ppsId);
4149  if (pps)
4150  {
4151    Int spsId = pps->getSPSId();
4152#if H_MV
4153    if (!isIRAP && (spsId != m_activeSPSId[ layerId ]))
4154#else
4155    if (!isIRAP && (spsId != m_activeSPSId))
4156#endif
4157    {
4158      printf("Warning: tried to activate PPS referring to a inactive SPS at non-IRAP.");
4159      return false;
4160    }
4161
4162    TComSPS *sps = m_spsMap.getPS(spsId);
4163    if (sps)
4164    {
4165      Int vpsId = sps->getVPSId();
4166      if (!isIRAP && (vpsId != m_activeVPSId))
4167      {
4168        printf("Warning: tried to activate PPS referring to a inactive VPS at non-IRAP.");
4169        return false;
4170      }
4171      if (m_vpsMap.getPS(vpsId))
4172      {
4173#if H_MV
4174        m_activePPSId[ layerId ] = ppsId;
4175        m_activeVPSId = vpsId;
4176        m_activeSPSId[ layerId ] = spsId;
4177#else
4178        m_activePPSId = ppsId;
4179        m_activeVPSId = vpsId;
4180        m_activeSPSId = spsId;
4181#endif
4182        return true;
4183      }
4184      else
4185      {
4186        printf("Warning: tried to activate PPS that refers to a non-existing VPS.");
4187      }
4188    }
4189    else
4190    {
4191      printf("Warning: tried to activate a PPS that refers to a non-existing SPS.");
4192    }
4193  }
4194  else
4195  {
4196    printf("Warning: tried to activate non-existing PPS.");
4197  }
4198  return false;
4199}
4200
4201ProfileTierLevel::ProfileTierLevel()
4202  : m_profileSpace    (0)
4203  , m_tierFlag        (false)
4204  , m_profileIdc      (0)
4205  , m_levelIdc        (0)
4206, m_progressiveSourceFlag  (false)
4207, m_interlacedSourceFlag   (false)
4208, m_nonPackedConstraintFlag(false)
4209, m_frameOnlyConstraintFlag(false)
4210{
4211  ::memset(m_profileCompatibilityFlag, 0, sizeof(m_profileCompatibilityFlag));
4212}
4213
4214TComPTL::TComPTL()
4215{
4216  ::memset(m_subLayerProfilePresentFlag, 0, sizeof(m_subLayerProfilePresentFlag));
4217  ::memset(m_subLayerLevelPresentFlag,   0, sizeof(m_subLayerLevelPresentFlag  ));
4218}
4219
4220#if H_MV
4221Void TComPTL::copyLevelFrom( TComPTL* source )
4222{
4223  getGeneralPTL()->setLevelIdc( source->getGeneralPTL()->getLevelIdc() );
4224  for( Int subLayer = 0; subLayer < 6; subLayer++ )
4225  {
4226    setSubLayerLevelPresentFlag( subLayer, source->getSubLayerLevelPresentFlag( subLayer ) );
4227    getSubLayerPTL( subLayer )->setLevelIdc( source->getSubLayerPTL( subLayer )->getLevelIdc() );
4228  }
4229}
4230#endif
4231//! \}
4232
4233#if H_MV
4234TComVPSVUI::TComVPSVUI()
4235{
4236  m_crossLayerIrapAlignedFlag = true; 
4237  m_allLayersIdrAlignedFlag   = false; 
4238  m_bitRatePresentVpsFlag = false;
4239  m_picRatePresentVpsFlag = false;
4240  for ( Int i = 0; i < MAX_VPS_OP_SETS_PLUS1; i++)
4241  {   
4242    for ( Int j = 0; j < MAX_TLAYER; j++)
4243    {   
4244      m_bitRatePresentFlag          [i][j] = false;
4245      m_picRatePresentFlag          [i][j] = false;
4246      m_avgBitRate                  [i][j] = -1;
4247      m_maxBitRate                  [i][j] = -1;
4248      m_constantPicRateIdc          [i][j] = -1;
4249      m_avgPicRate                  [i][j] = -1;
4250    }
4251  }
4252
4253  m_ilpRestrictedRefLayersFlag = false;
4254
4255  for ( Int i = 0; i < MAX_NUM_LAYERS; i++)
4256  {         
4257    for ( Int j = 0; j < MAX_NUM_LAYERS; j++)
4258    {   
4259      m_tileBoundariesAlignedFlag   [i][j] = false;
4260      m_minSpatialSegmentOffsetPlus1[i][j] = 0;
4261      m_ctuBasedOffsetEnabledFlag   [i][j] = false;
4262      m_minHorizontalCtuOffsetPlus1 [i][j] = -1;
4263    }
4264    m_baseLayerParameterSetCompatibilityFlag[i] = false;
4265  }
4266  for ( Int i = 0; i < MAX_NUM_VIDEO_SIGNAL_INFO; i++ )
4267  {
4268    m_videoSignalInfo          [i] = NULL;     
4269  }
4270
4271  m_vpsVuiBspHrdPresentFlag = false; 
4272  m_vpsVuiBspHrdParameters  = new TComVpsVuiBspHrdParameters();
4273}
4274
4275TComVPSVUI::~TComVPSVUI()
4276{
4277  for ( Int i = 0; i < MAX_NUM_VIDEO_SIGNAL_INFO; i++ )
4278  {
4279    if (m_videoSignalInfo[ i ] != NULL )      delete m_videoSignalInfo[ i ];   
4280    m_videoSignalInfo    [ i ] = NULL; 
4281  }
4282
4283  if ( m_vpsVuiBspHrdParameters ) delete m_vpsVuiBspHrdParameters;
4284  m_vpsVuiBspHrdParameters = NULL; 
4285}
4286
4287Void TComVPSVUI::inferVpsVui( Bool encoderFlag )
4288{
4289  // inference of syntax elements that differ from default inference (as done in constructor), when VPS VUI is not present
4290  if (!encoderFlag )
4291  {
4292    setCrossLayerIrapAlignedFlag( false ); 
4293  }
4294  else
4295  {
4296    assert( !getCrossLayerIrapAlignedFlag() ); 
4297  }
4298}
4299
4300Void TComRepFormat::inferChromaAndBitDepth( TComRepFormat* prevRepFormat, Bool encoderFlag )
4301{
4302  if ( !encoderFlag )
4303  {
4304    setChromaAndBitDepthVpsPresentFlag( prevRepFormat->getChromaAndBitDepthVpsPresentFlag() );
4305    setSeparateColourPlaneVpsFlag     ( prevRepFormat->getSeparateColourPlaneVpsFlag     () );
4306    setBitDepthVpsLumaMinus8          ( prevRepFormat->getBitDepthVpsLumaMinus8          () );
4307    setBitDepthVpsChromaMinus8        ( prevRepFormat->getBitDepthVpsChromaMinus8        () );
4308  }
4309  else
4310  {
4311    assert( getChromaAndBitDepthVpsPresentFlag() == prevRepFormat->getChromaAndBitDepthVpsPresentFlag() );
4312    assert( getSeparateColourPlaneVpsFlag     () == prevRepFormat->getSeparateColourPlaneVpsFlag     () );
4313    assert( getBitDepthVpsLumaMinus8          () == prevRepFormat->getBitDepthVpsLumaMinus8          () );
4314    assert( getBitDepthVpsChromaMinus8        () == prevRepFormat->getBitDepthVpsChromaMinus8        () );
4315}
4316}
4317
4318Void TComVpsVuiBspHrdParameters::checkLayerInBspFlag( TComVPS* vps, Int h )
4319{
4320  // It is a requirement of bitstream conformance that bitstream partition with index j shall not include
4321  // direct or indirect reference layers of any layers in bitstream partition i for any values of i and j
4322  // in the range of 0 to num_bitstream_partitions[ h ] ?1, inclusive, such that i is less than j.
4323
4324  for ( Int partJ = 0; partJ < getNumBitstreamPartitions( h ); partJ++ )
4325  {       
4326    for ( Int partI = 0; partI < partJ; partI++ )
4327    {
4328      for ( Int layerJ = 0; layerJ < vps->getMaxLayersMinus1(); layerJ++ )
4329      {
4330        if ( m_layerInBspFlag[ h ][partJ][layerJ ] )
4331        {
4332          for ( Int layerI = 0; layerI < vps->getMaxLayersMinus1(); layerI++ )
4333          {
4334            if ( m_layerInBspFlag[ h ][partI][layerI] )
4335            {
4336              assert( !vps->getInDirectDependencyFlag( layerI, layerJ ) ); 
4337            }
4338          }
4339        }
4340      }
4341    }
4342  }
4343
4344  // ---------------
4345  // To be added:
4346  // When vps_base_layer_internal_flag is equal to 0 and layer_in_bsp_flag[ h ][ i ][ 0 ] is equal to 1 for any value of h in the
4347  // range of 1 to vps_num_layer_sets_minus1, inclusive, and any value of i in the range of 0 to num_bitstream_partitions[ h ] - 1,
4348  // inclusive, the value of layer_in_bsp_flag[ h ][ i ][ j ] for at least one value of j in the range of 1 to
4349  // NumLayersInIdList[ h ] - 1, inclusive, shall be equal to 1.
4350  // ---------------
4351
4352
4353  // When num_bitstream_partitions[ h ] is equal to 1 for any value of h in the range 1 to vps_num_layer_set_minus1, inclusive,
4354  // the value of layer_in_bsp_flag[ h ][ 0 ][ j ] should be equal to 0 for at least one value of j in the range 0 to
4355  // NumLayersInIdList[ h ] − 1, inclusive.
4356
4357
4358  if ( getNumBitstreamPartitions( h ) == 1 )
4359  {
4360    Bool atLeastOneZero = false; 
4361    for ( Int j = 0; j <= vps->getNumLayersInIdList( h ) - 1; j++ )
4362    {
4363      atLeastOneZero = atLeastOneZero || !getLayerInBspFlag( h, 0, j ); 
4364    }   
4365    assert( atLeastOneZero ); 
4366  }
4367
4368 
4369  // For any value of h in the range 1 to vps_num_layer_set_minus1, inclusive, the value of layer_in_bsp_flag[ h ][ i ][ j ]
4370  // shall be equal to 1 for at most one value of i in the range of 0 to num_bitstream_partitions[ h ] − 1, inclusive.
4371
4372  for ( Int j = 0; j <= vps->getNumLayersInIdList( h ) - 1; j++ )
4373  {
4374    Int numLayerInBsp = 0; 
4375    for ( Int i = 0; i <= getNumBitstreamPartitions( h ) - 1; i++ )
4376    {
4377      numLayerInBsp += ( getLayerInBspFlag( h, i, j ) ? 1 : 0 ); 
4378    }   
4379    assert( numLayerInBsp <= 1 ); 
4380  }
4381
4382}
4383
4384Void TComVpsVuiBspHrdParameters::checkBspCombHrdAndShedIdx( TComVPS* vps, Int h, Int i, Int j )
4385{
4386  // bsp_comb_hrd_idx
4387  assert( getBspCombSchedIdx(h, i, j ) >= 0 );
4388  assert( getBspCombSchedIdx(h, i, j ) <= getVpsNumBspHrdParametersMinus1() );
4389
4390  // bsp_comb_sched_idx
4391  assert( getBspCombSchedIdx(h, i, j ) >= 0 );
4392
4393  //* This check needs to activated,  when HighestTid is available here   
4394  //  assert(  getBspCombSchedIdx(h, i, j ) <= vps->getHrdParameters( getBspCombHrdIdx( h, i, j ) )->getCpbCntMinus1( highestTid ) );
4395}
4396
4397Void TComVUI::inferVideoSignalInfo( TComVPS* vps, Int layerIdCurr )
4398{
4399  if ( layerIdCurr == 0 || !vps->getVpsVuiPresentFlag() ) 
4400  {
4401    return; 
4402  }
4403
4404  TComVPSVUI* vpsVUI = vps->getVPSVUI(); 
4405  assert( vpsVUI != NULL ); 
4406
4407  TComVideoSignalInfo* videoSignalInfo = vpsVUI->getVideoSignalInfo( vpsVUI->getVpsVideoSignalInfoIdx( vps->getLayerIdInVps( layerIdCurr ) ) ); 
4408  assert( videoSignalInfo != NULL );
4409
4410  setVideoFormat            ( videoSignalInfo->getVideoVpsFormat            () ); 
4411  setVideoFullRangeFlag     ( videoSignalInfo->getVideoFullRangeVpsFlag     () );
4412  setColourPrimaries        ( videoSignalInfo->getColourPrimariesVps        () );
4413  setTransferCharacteristics( videoSignalInfo->getTransferCharacteristicsVps() );
4414  setMatrixCoefficients     ( videoSignalInfo->getMatrixCoeffsVps           () );
4415}
4416
4417TComDpbSize::TComDpbSize()
4418{
4419  for (Int i = 0; i < MAX_VPS_OUTPUTLAYER_SETS; i++ )
4420  {     
4421    m_subLayerFlagInfoPresentFlag[i]  = false;
4422
4423    for (Int j = 0; j < MAX_TLAYER; j++  )
4424    {       
4425      m_subLayerDpbInfoPresentFlag [i][j] = ( j == 0) ;
4426      m_maxVpsNumReorderPics       [i][j] = 0;
4427      m_maxVpsLatencyIncreasePlus1 [i][j] = 0;
4428
4429      for (Int k = 0; k < MAX_NUM_LAYER_IDS; k++ )
4430      {
4431        m_maxVpsDecPicBufferingMinus1[i][k][j] = 0; 
4432      }
4433    }
4434  }
4435}
4436
4437Void Window::scaleOffsets( Int scal )
4438{
4439  if (! m_scaledFlag )
4440  {
4441    m_scaledFlag         = true; 
4442    m_winLeftOffset     *= scal; 
4443    m_winRightOffset    *= scal; 
4444    m_winTopOffset      *= scal; 
4445    m_winBottomOffset   *= scal; 
4446  }
4447}
4448#endif
4449
Note: See TracBrowser for help on using the repository browser.