source: 3DVCSoftware/branches/HTM-16.0-MV-draft-5/source/Lib/TLibEncoder/TEncTop.cpp

Last change on this file was 1390, checked in by tech, 9 years ago

Removed 3D.

  • Property svn:eol-style set to native
File size: 48.9 KB
Line 
1/* The copyright in this software is being made available under the BSD
2 * License, included below. This software may be subject to other third party
3 * and contributor rights, including patent rights, and no such rights are
4 * granted under this license.
5 *
6 * Copyright (c) 2010-2015, ITU/ISO/IEC
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
11 *
12 *  * Redistributions of source code must retain the above copyright notice,
13 *    this list of conditions and the following disclaimer.
14 *  * Redistributions in binary form must reproduce the above copyright notice,
15 *    this list of conditions and the following disclaimer in the documentation
16 *    and/or other materials provided with the distribution.
17 *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
18 *    be used to endorse or promote products derived from this software without
19 *    specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31 * THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34/** \file     TEncTop.cpp
35    \brief    encoder class
36*/
37
38#include "TLibCommon/CommonDef.h"
39#include "TEncTop.h"
40#include "TEncPic.h"
41#include "TLibCommon/TComChromaFormat.h"
42#if FAST_BIT_EST
43#include "TLibCommon/ContextModel.h"
44#endif
45#if NH_MV
46//#include "../../App/TAppEncoder/TAppEncTop.h"
47#endif
48
49//! \ingroup TLibEncoder
50//! \{
51
52// ====================================================================================================================
53// Constructor / destructor / create / destroy
54// ====================================================================================================================
55
56TEncTop::TEncTop()
57{
58  m_iPOCLast          = -1;
59  m_iNumPicRcvd       =  0;
60  m_uiNumAllPicCoded  =  0;
61  m_pppcRDSbacCoder   =  NULL;
62  m_pppcBinCoderCABAC =  NULL;
63  m_cRDGoOnSbacCoder.init( &m_cRDGoOnBinCoderCABAC );
64#if ENC_DEC_TRACE
65  if (g_hTrace == NULL)
66  {
67    g_hTrace = fopen( "TraceEnc.txt", "wb" );
68  }
69  g_bJustDoIt = g_bEncDecTraceDisable;
70  g_nSymbolCounter = 0;
71#endif
72
73  m_iMaxRefPicNum     = 0;
74
75#if FAST_BIT_EST
76  ContextModel::buildNextStateTable();
77#endif
78#if NH_MV
79  m_ivPicLists = NULL;
80#endif
81#if NH_MV
82  m_cCavlcCoder.setEncTop(this); 
83#endif
84
85}
86
87TEncTop::~TEncTop()
88{
89#if ENC_DEC_TRACE
90  if (g_hTrace != stdout)
91  {
92    fclose( g_hTrace );
93  }
94#endif
95}
96
97Void TEncTop::create ()
98{
99#if !NH_MV
100  // initialize global variables
101  initROM();
102#endif
103
104  // create processing unit classes
105  m_cGOPEncoder.        create( );
106  m_cSliceEncoder.      create( getSourceWidth(), getSourceHeight(), m_chromaFormatIDC, m_maxCUWidth, m_maxCUHeight, m_maxTotalCUDepth );
107  m_cCuEncoder.         create( m_maxTotalCUDepth, m_maxCUWidth, m_maxCUHeight, m_chromaFormatIDC );
108  if (m_bUseSAO)
109  {
110    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), m_chromaFormatIDC, m_maxCUWidth, m_maxCUHeight, m_maxTotalCUDepth, m_log2SaoOffsetScale[CHANNEL_TYPE_LUMA], m_log2SaoOffsetScale[CHANNEL_TYPE_CHROMA] );
111    m_cEncSAO.createEncData(getSaoCtuBoundary());
112  }
113#if ADAPTIVE_QP_SELECTION
114  if (m_bUseAdaptQpSelect)
115  {
116    m_cTrQuant.initSliceQpDelta();
117  }
118#endif
119
120  m_cLoopFilter.create( m_maxTotalCUDepth );
121
122  if ( m_RCEnableRateControl )
123  {
124    m_cRateCtrl.init( m_framesToBeEncoded, m_RCTargetBitrate, m_iFrameRate, m_iGOPSize, m_iSourceWidth, m_iSourceHeight,
125        m_maxCUWidth, m_maxCUHeight, m_RCKeepHierarchicalBit, m_RCUseLCUSeparateModel, m_GOPList );
126  }
127
128  m_pppcRDSbacCoder = new TEncSbac** [m_maxTotalCUDepth+1];
129#if FAST_BIT_EST
130  m_pppcBinCoderCABAC = new TEncBinCABACCounter** [m_maxTotalCUDepth+1];
131#else
132  m_pppcBinCoderCABAC = new TEncBinCABAC** [m_maxTotalCUDepth+1];
133#endif
134
135  for ( Int iDepth = 0; iDepth < m_maxTotalCUDepth+1; iDepth++ )
136  {
137    m_pppcRDSbacCoder[iDepth] = new TEncSbac* [CI_NUM];
138#if FAST_BIT_EST
139    m_pppcBinCoderCABAC[iDepth] = new TEncBinCABACCounter* [CI_NUM];
140#else
141    m_pppcBinCoderCABAC[iDepth] = new TEncBinCABAC* [CI_NUM];
142#endif
143
144    for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
145    {
146      m_pppcRDSbacCoder[iDepth][iCIIdx] = new TEncSbac;
147#if FAST_BIT_EST
148      m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABACCounter;
149#else
150      m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABAC;
151#endif
152      m_pppcRDSbacCoder   [iDepth][iCIIdx]->init( m_pppcBinCoderCABAC [iDepth][iCIIdx] );
153    }
154  }
155}
156
157Void TEncTop::destroy ()
158{
159  // destroy processing unit classes
160  m_cGOPEncoder.        destroy();
161  m_cSliceEncoder.      destroy();
162  m_cCuEncoder.         destroy();
163  m_cEncSAO.            destroyEncData();
164  m_cEncSAO.            destroy();
165  m_cLoopFilter.        destroy();
166  m_cRateCtrl.          destroy();
167  m_cSearch.            destroy();
168  Int iDepth;
169  for ( iDepth = 0; iDepth < m_maxTotalCUDepth+1; iDepth++ )
170  {
171    for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
172    {
173      delete m_pppcRDSbacCoder[iDepth][iCIIdx];
174      delete m_pppcBinCoderCABAC[iDepth][iCIIdx];
175    }
176  }
177
178  for ( iDepth = 0; iDepth < m_maxTotalCUDepth+1; iDepth++ )
179  {
180    delete [] m_pppcRDSbacCoder[iDepth];
181    delete [] m_pppcBinCoderCABAC[iDepth];
182  }
183
184  delete [] m_pppcRDSbacCoder;
185  delete [] m_pppcBinCoderCABAC;
186
187#if !NH_MV
188  // destroy ROM
189  destroyROM();
190#endif
191
192  return;
193}
194
195Void TEncTop::init(Bool isFieldCoding)
196{
197  // initialize SPS
198  xInitSPS();
199  xInitVPS();
200
201#if U0132_TARGET_BITS_SATURATION
202  if (m_RCCpbSaturationEnabled)
203  {
204    m_cRateCtrl.initHrdParam(m_cSPS.getVuiParameters()->getHrdParameters(), m_iFrameRate, m_RCInitialCpbFullness);
205  }
206#endif
207  m_cRdCost.setCostMode(m_costMode);
208
209#if NH_MV
210  // This seems to be incorrect, but irrelevant for the MV-HEVC
211  *(m_cVPS->getPTL()) = *m_cSPS.getPTL();
212  m_cVPS->getTimingInfo()->setTimingInfoPresentFlag       ( false );
213#endif
214  // initialize PPS
215  xInitPPS();
216  xInitRPS(isFieldCoding);
217
218  xInitPPSforTiles();
219
220  // initialize processing unit classes
221  m_cGOPEncoder.  init( this );
222  m_cSliceEncoder.init( this );
223  m_cCuEncoder.   init( this );
224
225  // initialize transform & quantization class
226  m_pcCavlcCoder = getCavlcCoder();
227
228  m_cTrQuant.init( 1 << m_uiQuadtreeTULog2MaxSize,
229                   m_useRDOQ,
230                   m_useRDOQTS,
231#if T0196_SELECTIVE_RDOQ
232                   m_useSelectiveRDOQ,
233#endif
234                   true
235                  ,m_useTransformSkipFast
236#if ADAPTIVE_QP_SELECTION
237                  ,m_bUseAdaptQpSelect
238#endif
239                  );
240
241  // initialize encoder search class
242  m_cSearch.init( this, &m_cTrQuant, m_iSearchRange, m_bipredSearchRange, m_motionEstimationSearchMethod, m_maxCUWidth, m_maxCUHeight, m_maxTotalCUDepth, &m_cEntropyCoder, &m_cRdCost, getRDSbacCoder(), getRDGoOnSbacCoder() );
243
244  m_iMaxRefPicNum = 0;
245
246  xInitScalingLists();
247}
248
249Void TEncTop::xInitScalingLists()
250{
251  // Initialise scaling lists
252  // The encoder will only use the SPS scaling lists. The PPS will never be marked present.
253  const Int maxLog2TrDynamicRange[MAX_NUM_CHANNEL_TYPE] =
254  {
255      m_cSPS.getMaxLog2TrDynamicRange(CHANNEL_TYPE_LUMA),
256      m_cSPS.getMaxLog2TrDynamicRange(CHANNEL_TYPE_CHROMA)
257  };
258  if(getUseScalingListId() == SCALING_LIST_OFF)
259  {
260    getTrQuant()->setFlatScalingList(maxLog2TrDynamicRange, m_cSPS.getBitDepths());
261    getTrQuant()->setUseScalingList(false);
262    m_cSPS.setScalingListPresentFlag(false);
263    m_cPPS.setScalingListPresentFlag(false);
264  }
265  else if(getUseScalingListId() == SCALING_LIST_DEFAULT)
266  {
267    m_cSPS.getScalingList().setDefaultScalingList ();
268    m_cSPS.setScalingListPresentFlag(false);
269    m_cPPS.setScalingListPresentFlag(false);
270
271    getTrQuant()->setScalingList(&(m_cSPS.getScalingList()), maxLog2TrDynamicRange, m_cSPS.getBitDepths());
272    getTrQuant()->setUseScalingList(true);
273  }
274  else if(getUseScalingListId() == SCALING_LIST_FILE_READ)
275  {
276    m_cSPS.getScalingList().setDefaultScalingList ();
277    if(m_cSPS.getScalingList().xParseScalingList(getScalingListFileName()))
278    {
279      Bool bParsedScalingList=false; // Use of boolean so that assertion outputs useful string
280      assert(bParsedScalingList);
281      exit(1);
282    }
283    m_cSPS.getScalingList().checkDcOfMatrix();
284    m_cSPS.setScalingListPresentFlag(m_cSPS.getScalingList().checkDefaultScalingList());
285    m_cPPS.setScalingListPresentFlag(false);
286    getTrQuant()->setScalingList(&(m_cSPS.getScalingList()), maxLog2TrDynamicRange, m_cSPS.getBitDepths());
287    getTrQuant()->setUseScalingList(true);
288  }
289  else
290  {
291    printf("error : ScalingList == %d not supported\n",getUseScalingListId());
292    assert(0);
293  }
294
295  if (getUseScalingListId() != SCALING_LIST_OFF)
296  { 
297    // Prepare delta's:
298  for(UInt sizeId = 0; sizeId < SCALING_LIST_SIZE_NUM; sizeId++)
299  {
300    const Int predListStep = (sizeId == SCALING_LIST_32x32? (SCALING_LIST_NUM/NUMBER_OF_PREDICTION_MODES) : 1); // if 32x32, skip over chroma entries.
301
302    for(UInt listId = 0; listId < SCALING_LIST_NUM; listId+=predListStep)
303    {
304      m_cSPS.getScalingList().checkPredMode( sizeId, listId );
305    }
306  }
307  }
308}
309
310// ====================================================================================================================
311// Public member functions
312// ====================================================================================================================
313
314#if NH_MV
315Void TEncTop::initNewPic( TComPicYuv* pcPicYuvOrg )
316{
317  TComPic* pcPicCurr = NULL;
318
319  // get original YUV
320  xGetNewPicBuffer( pcPicCurr );
321  pcPicYuvOrg->copyToPic( pcPicCurr->getPicYuvOrg() );
322
323  // compute image characteristics
324  if ( getUseAdaptiveQP() )
325  {
326    m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcPicCurr ) );
327  }
328  pcPicCurr->setLayerId( getLayerId()); 
329}
330#endif
331
332Void TEncTop::deletePicBuffer()
333{
334
335#if !NH_MV
336  TComList<TComPic*>::iterator iterPic = m_cListPic.begin();
337  Int iSize = Int( m_cListPic.size() );
338  for ( Int i = 0; i < iSize; i++ )
339  {
340    TComPic* pcPic = *(iterPic++);
341
342    pcPic->destroy();
343    delete pcPic;
344    pcPic = NULL;
345  }
346#endif
347}
348
349/**
350 - Application has picture buffer list with size of GOP + 1
351 - Picture buffer list acts like as ring buffer
352 - End of the list has the latest picture
353 .
354 \param   flush               cause encoder to encode a partial GOP
355 \param   pcPicYuvOrg         original YUV picture
356 \param   pcPicYuvTrueOrg     
357 \param   snrCSC
358 \retval  rcListPicYuvRecOut  list of reconstruction YUV pictures
359 \retval  accessUnitsOut      list of output access units
360 \retval  iNumEncoded         number of encoded pictures
361 */
362#if NH_MV
363Void TEncTop::encode( Bool flush, TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvTrueOrg, const InputColourSpaceConversion snrCSC, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, Int gopId )
364{
365#else
366Void TEncTop::encode( Bool flush, TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvTrueOrg, const InputColourSpaceConversion snrCSC, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded )
367{
368#endif
369#if NH_MV
370  if( gopId == 0)
371  {
372    m_cGOPEncoder.initGOP(m_iPOCLast, m_iNumPicRcvd, *(m_ivPicLists->getSubDpb( getLayerId(), false )), rcListPicYuvRecOut, accessUnitsOut); 
373#else
374  if (pcPicYuvOrg != NULL)
375  {
376    // get original YUV
377    TComPic* pcPicCurr = NULL;
378
379    xGetNewPicBuffer( pcPicCurr );
380    pcPicYuvOrg->copyToPic( pcPicCurr->getPicYuvOrg() );
381    pcPicYuvTrueOrg->copyToPic( pcPicCurr->getPicYuvTrueOrg() );
382
383    // compute image characteristics
384    if ( getUseAdaptiveQP() )
385    {
386      m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcPicCurr ) );
387    }
388  }
389
390  if ((m_iNumPicRcvd == 0) || (!flush && (m_iPOCLast != 0) && (m_iNumPicRcvd != m_iGOPSize) && (m_iGOPSize != 0)))
391  {
392    iNumEncoded = 0;
393    return;
394  }
395#endif
396  if ( m_RCEnableRateControl )
397  {
398    m_cRateCtrl.initRCGOP( m_iNumPicRcvd );
399  }
400#if NH_MV
401  }
402  m_cGOPEncoder.compressPicInGOP(m_iPOCLast, m_iNumPicRcvd, *(m_ivPicLists->getSubDpb(getLayerId(), false) ), rcListPicYuvRecOut, accessUnitsOut, false, false, snrCSC, m_printFrameMSE, gopId);
403
404  if( gopId + 1 == m_cGOPEncoder.getGOPSize() )
405  {
406#else
407  // compress GOP
408  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false, snrCSC, m_printFrameMSE);
409#endif
410  if ( m_RCEnableRateControl )
411  {
412    m_cRateCtrl.destroyRCGOP();
413  }
414
415  iNumEncoded         = m_iNumPicRcvd;
416  m_iNumPicRcvd       = 0;
417  m_uiNumAllPicCoded += iNumEncoded;
418#if NH_MV
419}
420#endif
421}
422
423/**------------------------------------------------
424 Separate interlaced frame into two fields
425 -------------------------------------------------**/
426Void separateFields(Pel* org, Pel* dstField, UInt stride, UInt width, UInt height, Bool isTop)
427{
428  if (!isTop)
429  {
430    org += stride;
431  }
432  for (Int y = 0; y < height>>1; y++)
433  {
434    for (Int x = 0; x < width; x++)
435    {
436      dstField[x] = org[x];
437    }
438
439    dstField += stride;
440    org += stride*2;
441  }
442
443}
444#if NH_MV
445Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvTrueOrg, const InputColourSpaceConversion snrCSC, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, Bool isTff, Int gopId )
446{
447  assert( 0 ); // Field coding and multiview need to be further harmonized.
448}
449#else
450Void TEncTop::encode(Bool flush, TComPicYuv* pcPicYuvOrg, TComPicYuv* pcPicYuvTrueOrg, const InputColourSpaceConversion snrCSC, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, Bool isTff)
451{
452  iNumEncoded = 0;
453
454  for (Int fieldNum=0; fieldNum<2; fieldNum++)
455  {
456    if (pcPicYuvOrg)
457    {
458
459      /* -- field initialization -- */
460      const Bool isTopField=isTff==(fieldNum==0);
461
462      TComPic *pcField;
463      xGetNewPicBuffer( pcField );
464      pcField->setReconMark (false);                     // where is this normally?
465
466      if (fieldNum==1)                                   // where is this normally?
467      {
468        TComPicYuv* rpcPicYuvRec;
469
470        // org. buffer
471        if ( rcListPicYuvRecOut.size() >= (UInt)m_iGOPSize+1 ) // need to maintain field 0 in list of RecOuts while processing field 1. Hence +1 on m_iGOPSize.
472        {
473          rpcPicYuvRec = rcListPicYuvRecOut.popFront();
474        }
475        else
476        {
477          rpcPicYuvRec = new TComPicYuv;
478          rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, m_chromaFormatIDC, m_maxCUWidth, m_maxCUHeight, m_maxTotalCUDepth, true);
479        }
480        rcListPicYuvRecOut.pushBack( rpcPicYuvRec );
481      }
482
483      pcField->getSlice(0)->setPOC( m_iPOCLast );        // superfluous?
484      pcField->getPicYuvRec()->setBorderExtension(false);// where is this normally?
485
486      pcField->setTopField(isTopField);                  // interlaced requirement
487
488      for (UInt componentIndex = 0; componentIndex < pcPicYuvOrg->getNumberValidComponents(); componentIndex++)
489      {
490        const ComponentID component = ComponentID(componentIndex);
491        const UInt stride = pcPicYuvOrg->getStride(component);
492
493        separateFields((pcPicYuvOrg->getBuf(component) + pcPicYuvOrg->getMarginX(component) + (pcPicYuvOrg->getMarginY(component) * stride)),
494                       pcField->getPicYuvOrg()->getAddr(component),
495                       pcPicYuvOrg->getStride(component),
496                       pcPicYuvOrg->getWidth(component),
497                       pcPicYuvOrg->getHeight(component),
498                       isTopField);
499
500        separateFields((pcPicYuvTrueOrg->getBuf(component) + pcPicYuvTrueOrg->getMarginX(component) + (pcPicYuvTrueOrg->getMarginY(component) * stride)),
501                       pcField->getPicYuvTrueOrg()->getAddr(component),
502                       pcPicYuvTrueOrg->getStride(component),
503                       pcPicYuvTrueOrg->getWidth(component),
504                       pcPicYuvTrueOrg->getHeight(component),
505                       isTopField);
506      }
507
508      // compute image characteristics
509      if ( getUseAdaptiveQP() )
510      {
511        m_cPreanalyzer.xPreanalyze( dynamic_cast<TEncPic*>( pcField ) );
512      }
513    }
514
515    if ( m_iNumPicRcvd && ((flush&&fieldNum==1) || (m_iPOCLast/2)==0 || m_iNumPicRcvd==m_iGOPSize ) )
516    {
517      // compress GOP
518      m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff, snrCSC, m_printFrameMSE);
519
520      iNumEncoded += m_iNumPicRcvd;
521      m_uiNumAllPicCoded += m_iNumPicRcvd;
522      m_iNumPicRcvd = 0;
523    }
524  }
525}
526#endif
527// ====================================================================================================================
528// Protected member functions
529// ====================================================================================================================
530
531/**
532 - Application has picture buffer list with size of GOP + 1
533 - Picture buffer list acts like as ring buffer
534 - End of the list has the latest picture
535 .
536 \retval rpcPic obtained picture buffer
537 */
538Void TEncTop::xGetNewPicBuffer ( TComPic*& rpcPic )
539{
540  // At this point, the SPS and PPS can be considered activated - they are copied to the new TComPic.
541
542#if NH_MV
543  TComList<TComPic*>& cListPic = *(m_ivPicLists->getSubDpb(getLayerId(), false) );
544  TComSlice::sortPicList(cListPic);
545#else
546  TComSlice::sortPicList(m_cListPic);
547#endif
548
549
550#if NH_MV
551  if (cListPic.size() >= (UInt)(m_iGOPSize + getMaxDecPicBuffering(MAX_TLAYER-1) + 2) )
552  {
553    TComList<TComPic*>::iterator iterPic  = cListPic.begin();
554    Int iSize = Int( cListPic.size() );
555#else
556  if (m_cListPic.size() >= (UInt)(m_iGOPSize + getMaxDecPicBuffering(MAX_TLAYER-1) + 2) )
557  {
558    TComList<TComPic*>::iterator iterPic  = m_cListPic.begin();
559    Int iSize = Int( m_cListPic.size() );
560#endif
561    for ( Int i = 0; i < iSize; i++ )
562    {
563      rpcPic = *(iterPic++);
564      if(rpcPic->getSlice(0)->isReferenced() == false)
565      {
566        break;
567      }
568    }
569  }
570  else
571  {
572    if ( getUseAdaptiveQP() )
573    {
574      TEncPic* pcEPic = new TEncPic;
575      pcEPic->create( m_cSPS, m_cPPS, m_cPPS.getMaxCuDQPDepth()+1, false);
576      rpcPic = pcEPic;
577    }
578    else
579    {
580      rpcPic = new TComPic;
581      rpcPic->create( m_cSPS, m_cPPS, false );
582    }
583
584#if NH_MV
585    cListPic.pushBack( rpcPic );
586#else
587    m_cListPic.pushBack( rpcPic );
588#endif
589  }
590  rpcPic->setReconMark (false);
591
592  m_iPOCLast++;
593  m_iNumPicRcvd++;
594
595  rpcPic->getSlice(0)->setPOC( m_iPOCLast );
596  // mark it should be extended
597  rpcPic->getPicYuvRec()->setBorderExtension(false);
598#if NH_MV
599  rpcPic->getPicYuvOrg()->setBorderExtension(false);
600#endif
601
602}
603
604Void TEncTop::xInitVPS()
605{
606  // The SPS must have already been set up.
607  // set the VPS profile information.
608#if NH_MV
609  // Do initialization in TAppEncTop
610#else
611  *m_cVPS.getPTL() = *m_cSPS.getPTL();
612  m_cVPS.setMaxOpSets(1);
613  m_cVPS.getTimingInfo()->setTimingInfoPresentFlag       ( false );
614  m_cVPS.setNumHrdParameters( 0 );
615
616  m_cVPS.createHrdParamBuffer();
617  for( UInt i = 0; i < m_cVPS.getNumHrdParameters(); i ++ )
618  {
619    m_cVPS.setHrdOpSetIdx( 0, i );
620    m_cVPS.setCprmsPresentFlag( false, i );
621    // Set up HrdParameters here.
622  }
623#endif
624}
625
626Void TEncTop::xInitSPS()
627{
628#if NH_MV
629  m_cSPS.setSPSId( getLayerIdInVps() );
630  m_cSPS.setLayerId( getLayerId() );
631 // Code below needs to be moved to VPS
632#endif
633  ProfileTierLevel& profileTierLevel = *m_cSPS.getPTL()->getGeneralPTL();
634  profileTierLevel.setLevelIdc(m_level);
635  profileTierLevel.setTierFlag(m_levelTier);
636  profileTierLevel.setProfileIdc(m_profile);
637  profileTierLevel.setProfileCompatibilityFlag(m_profile, 1);
638  profileTierLevel.setProgressiveSourceFlag(m_progressiveSourceFlag);
639  profileTierLevel.setInterlacedSourceFlag(m_interlacedSourceFlag);
640  profileTierLevel.setNonPackedConstraintFlag(m_nonPackedConstraintFlag);
641  profileTierLevel.setFrameOnlyConstraintFlag(m_frameOnlyConstraintFlag);
642  profileTierLevel.setBitDepthConstraint(m_bitDepthConstraintValue);
643  profileTierLevel.setChromaFormatConstraint(m_chromaFormatConstraintValue);
644  profileTierLevel.setIntraConstraintFlag(m_intraConstraintFlag);
645  profileTierLevel.setOnePictureOnlyConstraintFlag(m_onePictureOnlyConstraintFlag);
646  profileTierLevel.setLowerBitRateConstraintFlag(m_lowerBitRateConstraintFlag);
647
648  if ((m_profile == Profile::MAIN10) && (m_bitDepth[CHANNEL_TYPE_LUMA] == 8) && (m_bitDepth[CHANNEL_TYPE_CHROMA] == 8))
649  {
650    /* The above constraint is equal to Profile::MAIN */
651    profileTierLevel.setProfileCompatibilityFlag(Profile::MAIN, 1);
652  }
653  if (m_profile == Profile::MAIN)
654  {
655    /* A Profile::MAIN10 decoder can always decode Profile::MAIN */
656    profileTierLevel.setProfileCompatibilityFlag(Profile::MAIN10, 1);
657  }
658  /* XXX: should Main be marked as compatible with still picture? */
659  /* XXX: may be a good idea to refactor the above into a function
660   * that chooses the actual compatibility based upon options */
661#if NH_MV 
662  m_cSPS.setUpdateRepFormatFlag           ( false );   
663  Bool multiLayerExtensionFlag  = ( getLayerId() > 0 ) && ( m_cVPS->getNumRefLayers( getLayerId() ) > 0 ); 
664 
665  m_cSPS.setSpsExtOrMaxSubLayersMinus1( multiLayerExtensionFlag ? 7 : m_maxTempLayer - 1 );
666  if ( multiLayerExtensionFlag )
667  {
668    m_cSPS.setSpsInferScalingListFlag   ( true ); 
669    m_cSPS.setSpsScalingListRefLayerId( m_cVPS->getIdRefLayer( getLayerId(), 0 ) ); 
670#if NH_MV
671    if ( m_bUseDisparitySearchRangeRestriction )
672    {
673      m_cSPS.setInterViewMvVertConstraintFlag ( true ) ;
674    }
675#endif
676  } 
677  m_cSPS.setSpsExtensionPresentFlag       ( true ); 
678  m_cSPS.setSpsMultilayerExtensionFlag    ( true ); 
679#endif
680
681  m_cSPS.setPicWidthInLumaSamples  ( m_iSourceWidth      );
682  m_cSPS.setPicHeightInLumaSamples ( m_iSourceHeight     );
683  m_cSPS.setConformanceWindow      ( m_conformanceWindow );
684  m_cSPS.setMaxCUWidth             ( m_maxCUWidth        );
685  m_cSPS.setMaxCUHeight            ( m_maxCUHeight       );
686  m_cSPS.setMaxTotalCUDepth        ( m_maxTotalCUDepth   );
687  m_cSPS.setChromaFormatIdc( m_chromaFormatIDC);
688  m_cSPS.setLog2DiffMaxMinCodingBlockSize(m_log2DiffMaxMinCodingBlockSize);
689
690  Int minCUSize = m_cSPS.getMaxCUWidth() >> ( m_cSPS.getLog2DiffMaxMinCodingBlockSize() );
691  Int log2MinCUSize = 0;
692  while(minCUSize > 1)
693  {
694    minCUSize >>= 1;
695    log2MinCUSize++;
696  }
697
698  m_cSPS.setLog2MinCodingBlockSize(log2MinCUSize);
699
700  m_cSPS.setPCMLog2MinSize (m_uiPCMLog2MinSize);
701  m_cSPS.setUsePCM        ( m_usePCM           );
702  m_cSPS.setPCMLog2MaxSize( m_pcmLog2MaxSize  );
703
704  m_cSPS.setQuadtreeTULog2MaxSize( m_uiQuadtreeTULog2MaxSize );
705  m_cSPS.setQuadtreeTULog2MinSize( m_uiQuadtreeTULog2MinSize );
706  m_cSPS.setQuadtreeTUMaxDepthInter( m_uiQuadtreeTUMaxDepthInter    );
707  m_cSPS.setQuadtreeTUMaxDepthIntra( m_uiQuadtreeTUMaxDepthIntra    );
708
709  m_cSPS.setTMVPFlagsPresent((getTMVPModeId() == 2 || getTMVPModeId() == 1));
710
711  m_cSPS.setMaxTrSize   ( 1 << m_uiQuadtreeTULog2MaxSize );
712
713  m_cSPS.setUseAMP ( m_useAMP );
714
715  for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
716  {
717    m_cSPS.setBitDepth      (ChannelType(channelType), m_bitDepth[channelType] );
718#if O0043_BEST_EFFORT_DECODING
719    m_cSPS.setStreamBitDepth(ChannelType(channelType), m_bitDepth[channelType] );
720#endif
721    m_cSPS.setQpBDOffset  (ChannelType(channelType), (6 * (m_bitDepth[channelType] - 8)));
722    m_cSPS.setPCMBitDepth (ChannelType(channelType), m_PCMBitDepth[channelType]         );
723  }
724#if NH_MV
725  m_cSPS.inferRepFormat( m_cVPS, getLayerId(), true ); 
726#endif
727m_cSPS.setUseSAO( m_bUseSAO );
728
729  m_cSPS.setMaxTLayers( m_maxTempLayer );
730  m_cSPS.setTemporalIdNestingFlag( ( m_maxTempLayer == 1 ) ? true : false );
731
732  for (Int i = 0; i < min(m_cSPS.getMaxTLayers(),(UInt) MAX_TLAYER); i++ )
733  {
734    m_cSPS.setMaxDecPicBuffering(m_maxDecPicBuffering[i], i);
735    m_cSPS.setNumReorderPics(m_numReorderPics[i], i);
736  }
737#if NH_MV
738  for ( Int ols = 0; ols < m_cVPS->getNumOutputLayerSets(); ols++)
739  {
740    // Check MaxDecPicBuffering
741    const std::vector<Int>& targetDecLayerIdList = m_cVPS->getTargetDecLayerIdList( m_cVPS->olsIdxToLsIdx( ols )); 
742    for( Int is = 0; is < targetDecLayerIdList.size(); is++  )
743    {
744      if ( m_cVPS->getNecessaryLayerFlag( ols, is ) )
745      {     
746        m_cSPS.inferSpsMaxDecPicBufferingMinus1( m_cVPS, ols, targetDecLayerIdList[is], true );       
747      }
748    }
749  }
750#endif
751
752
753  m_cSPS.setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag );
754  m_cSPS.setScalingListFlag ( (m_useScalingListId == SCALING_LIST_OFF) ? 0 : 1 );
755  m_cSPS.setUseStrongIntraSmoothing( m_useStrongIntraSmoothing );
756  m_cSPS.setVuiParametersPresentFlag(getVuiParametersPresentFlag());
757
758  if (m_cSPS.getVuiParametersPresentFlag())
759  {
760    TComVUI* pcVUI = m_cSPS.getVuiParameters();
761    pcVUI->setAspectRatioInfoPresentFlag(getAspectRatioInfoPresentFlag());
762    pcVUI->setAspectRatioIdc(getAspectRatioIdc());
763    pcVUI->setSarWidth(getSarWidth());
764    pcVUI->setSarHeight(getSarHeight());
765    pcVUI->setOverscanInfoPresentFlag(getOverscanInfoPresentFlag());
766    pcVUI->setOverscanAppropriateFlag(getOverscanAppropriateFlag());
767#if NH_MV
768    pcVUI->setVideoSignalTypePresentFlag(getVideoSignalTypePresentFlag() && getLayerId() == 0 );
769#else
770    pcVUI->setVideoSignalTypePresentFlag(getVideoSignalTypePresentFlag());
771#endif
772    pcVUI->setVideoFormat(getVideoFormat());
773    pcVUI->setVideoFullRangeFlag(getVideoFullRangeFlag());
774    pcVUI->setColourDescriptionPresentFlag(getColourDescriptionPresentFlag());
775    pcVUI->setColourPrimaries(getColourPrimaries());
776    pcVUI->setTransferCharacteristics(getTransferCharacteristics());
777    pcVUI->setMatrixCoefficients(getMatrixCoefficients());
778    pcVUI->setChromaLocInfoPresentFlag(getChromaLocInfoPresentFlag());
779    pcVUI->setChromaSampleLocTypeTopField(getChromaSampleLocTypeTopField());
780    pcVUI->setChromaSampleLocTypeBottomField(getChromaSampleLocTypeBottomField());
781    pcVUI->setNeutralChromaIndicationFlag(getNeutralChromaIndicationFlag());
782    pcVUI->setDefaultDisplayWindow(getDefaultDisplayWindow());
783    pcVUI->setFrameFieldInfoPresentFlag(getFrameFieldInfoPresentFlag());
784    pcVUI->setFieldSeqFlag(false);
785    pcVUI->setHrdParametersPresentFlag(false);
786    pcVUI->getTimingInfo()->setPocProportionalToTimingFlag(getPocProportionalToTimingFlag());
787    pcVUI->getTimingInfo()->setNumTicksPocDiffOneMinus1   (getNumTicksPocDiffOneMinus1()   );
788    pcVUI->setBitstreamRestrictionFlag(getBitstreamRestrictionFlag());
789    pcVUI->setTilesFixedStructureFlag(getTilesFixedStructureFlag());
790    pcVUI->setMotionVectorsOverPicBoundariesFlag(getMotionVectorsOverPicBoundariesFlag());
791    pcVUI->setMinSpatialSegmentationIdc(getMinSpatialSegmentationIdc());
792    pcVUI->setMaxBytesPerPicDenom(getMaxBytesPerPicDenom());
793    pcVUI->setMaxBitsPerMinCuDenom(getMaxBitsPerMinCuDenom());
794    pcVUI->setLog2MaxMvLengthHorizontal(getLog2MaxMvLengthHorizontal());
795    pcVUI->setLog2MaxMvLengthVertical(getLog2MaxMvLengthVertical());
796  }
797  m_cSPS.setNumLongTermRefPicSPS(NUM_LONG_TERM_REF_PIC_SPS);
798  assert (NUM_LONG_TERM_REF_PIC_SPS <= MAX_NUM_LONG_TERM_REF_PICS);
799  for (Int k = 0; k < NUM_LONG_TERM_REF_PIC_SPS; k++)
800  {
801    m_cSPS.setLtRefPicPocLsbSps(k, 0);
802    m_cSPS.setUsedByCurrPicLtSPSFlag(k, 0);
803  }
804
805#if U0132_TARGET_BITS_SATURATION
806  if( getPictureTimingSEIEnabled() || getDecodingUnitInfoSEIEnabled() || getCpbSaturationEnabled() )
807#else
808  if( getPictureTimingSEIEnabled() || getDecodingUnitInfoSEIEnabled() )
809#endif
810  {
811    xInitHrdParameters();
812  }
813  if( getBufferingPeriodSEIEnabled() || getPictureTimingSEIEnabled() || getDecodingUnitInfoSEIEnabled() )
814  {
815    m_cSPS.getVuiParameters()->setHrdParametersPresentFlag( true );
816  }
817
818  // Set up SPS range extension settings
819  m_cSPS.getSpsRangeExtension().setTransformSkipRotationEnabledFlag(m_transformSkipRotationEnabledFlag);
820  m_cSPS.getSpsRangeExtension().setTransformSkipContextEnabledFlag(m_transformSkipContextEnabledFlag);
821  for (UInt signallingModeIndex = 0; signallingModeIndex < NUMBER_OF_RDPCM_SIGNALLING_MODES; signallingModeIndex++)
822  {
823    m_cSPS.getSpsRangeExtension().setRdpcmEnabledFlag(RDPCMSignallingMode(signallingModeIndex), m_rdpcmEnabledFlag[signallingModeIndex]);
824  }
825  m_cSPS.getSpsRangeExtension().setExtendedPrecisionProcessingFlag(m_extendedPrecisionProcessingFlag);
826  m_cSPS.getSpsRangeExtension().setIntraSmoothingDisabledFlag( m_intraSmoothingDisabledFlag );
827  m_cSPS.getSpsRangeExtension().setHighPrecisionOffsetsEnabledFlag(m_highPrecisionOffsetsEnabledFlag);
828  m_cSPS.getSpsRangeExtension().setPersistentRiceAdaptationEnabledFlag(m_persistentRiceAdaptationEnabledFlag);
829  m_cSPS.getSpsRangeExtension().setCabacBypassAlignmentEnabledFlag(m_cabacBypassAlignmentEnabledFlag);
830#if NH_MV
831  m_cSPS.setSpsRangeExtensionsFlag( m_cSPS.getSpsRangeExtension().settingsDifferFromDefaults() );
832#endif
833}
834#if U0132_TARGET_BITS_SATURATION
835// calculate scale value of bitrate and initial delay
836Int calcScale(Int x)
837{
838  UInt iMask = 0xffffffff;
839  Int ScaleValue = 32;
840
841  while ((x&iMask) != 0)
842  {
843    ScaleValue--;
844    iMask = (iMask >> 1);
845}
846
847  return ScaleValue;
848}
849#endif
850Void TEncTop::xInitHrdParameters()
851{
852  Bool useSubCpbParams = (getSliceMode() > 0) || (getSliceSegmentMode() > 0);
853  Int  bitRate         = getTargetBitrate();
854  Bool isRandomAccess  = getIntraPeriod() > 0;
855# if U0132_TARGET_BITS_SATURATION
856  Int cpbSize          = getCpbSize();
857
858  if( !getVuiParametersPresentFlag() && !getCpbSaturationEnabled() )
859#else
860  if( !getVuiParametersPresentFlag() )
861#endif
862  {
863    return;
864  }
865
866  TComVUI *vui = m_cSPS.getVuiParameters();
867  TComHRD *hrd = vui->getHrdParameters();
868
869  TimingInfo *timingInfo = vui->getTimingInfo();
870  timingInfo->setTimingInfoPresentFlag( true );
871  switch( getFrameRate() )
872  {
873  case 24:
874    timingInfo->setNumUnitsInTick( 1125000 );    timingInfo->setTimeScale    ( 27000000 );
875    break;
876  case 25:
877    timingInfo->setNumUnitsInTick( 1080000 );    timingInfo->setTimeScale    ( 27000000 );
878    break;
879  case 30:
880    timingInfo->setNumUnitsInTick( 900900 );     timingInfo->setTimeScale    ( 27000000 );
881    break;
882  case 50:
883    timingInfo->setNumUnitsInTick( 540000 );     timingInfo->setTimeScale    ( 27000000 );
884    break;
885  case 60:
886    timingInfo->setNumUnitsInTick( 450450 );     timingInfo->setTimeScale    ( 27000000 );
887    break;
888  default:
889    timingInfo->setNumUnitsInTick( 1001 );       timingInfo->setTimeScale    ( 60000 );
890    break;
891  }
892
893  Bool rateCnt = ( bitRate > 0 );
894  hrd->setNalHrdParametersPresentFlag( rateCnt );
895  hrd->setVclHrdParametersPresentFlag( rateCnt );
896
897  hrd->setSubPicCpbParamsPresentFlag( useSubCpbParams );
898
899  if( hrd->getSubPicCpbParamsPresentFlag() )
900  {
901    hrd->setTickDivisorMinus2( 100 - 2 );                          //
902    hrd->setDuCpbRemovalDelayLengthMinus1( 7 );                    // 8-bit precision ( plus 1 for last DU in AU )
903    hrd->setSubPicCpbParamsInPicTimingSEIFlag( true );
904    hrd->setDpbOutputDelayDuLengthMinus1( 5 + 7 );                 // With sub-clock tick factor of 100, at least 7 bits to have the same value as AU dpb delay
905  }
906  else
907  {
908    hrd->setSubPicCpbParamsInPicTimingSEIFlag( false );
909  }
910
911#if U0132_TARGET_BITS_SATURATION
912  if (calcScale(bitRate) <= 6)
913  {
914    hrd->setBitRateScale(0);
915  }
916  else
917  {
918    hrd->setBitRateScale(calcScale(bitRate) - 6);
919  }
920
921  if (calcScale(cpbSize) <= 4)
922  {
923    hrd->setCpbSizeScale(0);
924  }
925  else
926  {
927    hrd->setCpbSizeScale(calcScale(cpbSize) - 4);
928  }
929#else
930  hrd->setBitRateScale( 4 );                                       // in units of 2^( 6 + 4 ) = 1,024 bps
931  hrd->setCpbSizeScale( 6 );                                       // in units of 2^( 4 + 6 ) = 1,024 bit
932#endif
933
934  hrd->setDuCpbSizeScale( 6 );                                     // in units of 2^( 4 + 6 ) = 1,024 bit
935
936  hrd->setInitialCpbRemovalDelayLengthMinus1(15);                  // assuming 0.5 sec, log2( 90,000 * 0.5 ) = 16-bit
937  if( isRandomAccess )
938  {
939    hrd->setCpbRemovalDelayLengthMinus1(5);                        // 32 = 2^5 (plus 1)
940    hrd->setDpbOutputDelayLengthMinus1 (5);                        // 32 + 3 = 2^6
941  }
942  else
943  {
944    hrd->setCpbRemovalDelayLengthMinus1(9);                        // max. 2^10
945    hrd->setDpbOutputDelayLengthMinus1 (9);                        // max. 2^10
946  }
947
948  // Note: parameters for all temporal layers are initialized with the same values
949  Int i, j;
950  UInt bitrateValue, cpbSizeValue;
951  UInt duCpbSizeValue;
952  UInt duBitRateValue = 0;
953
954  for( i = 0; i < MAX_TLAYER; i ++ )
955  {
956    hrd->setFixedPicRateFlag( i, 1 );
957    hrd->setPicDurationInTcMinus1( i, 0 );
958    hrd->setLowDelayHrdFlag( i, 0 );
959    hrd->setCpbCntMinus1( i, 0 );
960
961    //! \todo check for possible PTL violations
962    // BitRate[ i ] = ( bit_rate_value_minus1[ i ] + 1 ) * 2^( 6 + bit_rate_scale )
963    bitrateValue = bitRate / (1 << (6 + hrd->getBitRateScale()) );      // bitRate is in bits, so it needs to be scaled down
964    // CpbSize[ i ] = ( cpb_size_value_minus1[ i ] + 1 ) * 2^( 4 + cpb_size_scale )
965#if U0132_TARGET_BITS_SATURATION
966    cpbSizeValue = cpbSize / (1 << (4 + hrd->getCpbSizeScale()) );      // using bitRate results in 1 second CPB size
967#else
968    cpbSizeValue = bitRate / (1 << (4 + hrd->getCpbSizeScale()) );      // using bitRate results in 1 second CPB size
969#endif
970
971
972    // DU CPB size could be smaller (i.e. bitrateValue / number of DUs), but we don't know
973    // in how many DUs the slice segment settings will result
974    duCpbSizeValue = bitrateValue;
975    duBitRateValue = cpbSizeValue;
976
977    for( j = 0; j < ( hrd->getCpbCntMinus1( i ) + 1 ); j ++ )
978    {
979      hrd->setBitRateValueMinus1( i, j, 0, ( bitrateValue - 1 ) );
980      hrd->setCpbSizeValueMinus1( i, j, 0, ( cpbSizeValue - 1 ) );
981      hrd->setDuCpbSizeValueMinus1( i, j, 0, ( duCpbSizeValue - 1 ) );
982      hrd->setDuBitRateValueMinus1( i, j, 0, ( duBitRateValue - 1 ) );
983      hrd->setCbrFlag( i, j, 0, false );
984
985      hrd->setBitRateValueMinus1( i, j, 1, ( bitrateValue - 1) );
986      hrd->setCpbSizeValueMinus1( i, j, 1, ( cpbSizeValue - 1 ) );
987      hrd->setDuCpbSizeValueMinus1( i, j, 1, ( duCpbSizeValue - 1 ) );
988      hrd->setDuBitRateValueMinus1( i, j, 1, ( duBitRateValue - 1 ) );
989      hrd->setCbrFlag( i, j, 1, false );
990    }
991  }
992}
993
994
995Void TEncTop::xInitPPS()
996{
997#if NH_MV
998  m_cPPS.setLayerId( getLayerId() );
999  if( getVPS()->getNumDirectRefLayers( getLayerId() ) > 0 )
1000  {
1001    m_cPPS.setListsModificationPresentFlag( true );
1002  }
1003  m_cPPS.setPPSId( getLayerIdInVps() );
1004  m_cPPS.setSPSId( getLayerIdInVps() );
1005  m_cPPS.setPpsMultilayerExtensionFlag    ( true ); 
1006#endif
1007
1008
1009  m_cPPS.setConstrainedIntraPred( m_bUseConstrainedIntraPred );
1010  Bool bUseDQP = (getMaxCuDQPDepth() > 0)? true : false;
1011
1012  if((getMaxDeltaQP() != 0 )|| getUseAdaptiveQP())
1013  {
1014    bUseDQP = true;
1015  }
1016
1017  if (m_costMode==COST_SEQUENCE_LEVEL_LOSSLESS || m_costMode==COST_LOSSLESS_CODING)
1018  {
1019    bUseDQP=false;
1020  }
1021
1022
1023  if ( m_RCEnableRateControl )
1024  {
1025    m_cPPS.setUseDQP(true);
1026    m_cPPS.setMaxCuDQPDepth( 0 );
1027  }
1028  else if(bUseDQP)
1029  {
1030    m_cPPS.setUseDQP(true);
1031    m_cPPS.setMaxCuDQPDepth( m_iMaxCuDQPDepth );
1032  }
1033  else
1034  {
1035    m_cPPS.setUseDQP(false);
1036    m_cPPS.setMaxCuDQPDepth( 0 );
1037  }
1038
1039  if ( m_diffCuChromaQpOffsetDepth >= 0 )
1040  {
1041    m_cPPS.getPpsRangeExtension().setDiffCuChromaQpOffsetDepth(m_diffCuChromaQpOffsetDepth);
1042    m_cPPS.getPpsRangeExtension().clearChromaQpOffsetList();
1043    m_cPPS.getPpsRangeExtension().setChromaQpOffsetListEntry(1, 6, 6);
1044    /* todo, insert table entries from command line (NB, 0 should not be touched) */
1045  }
1046  else
1047  {
1048    m_cPPS.getPpsRangeExtension().setDiffCuChromaQpOffsetDepth(0);
1049    m_cPPS.getPpsRangeExtension().clearChromaQpOffsetList();
1050  }
1051  m_cPPS.getPpsRangeExtension().setCrossComponentPredictionEnabledFlag(m_crossComponentPredictionEnabledFlag);
1052  m_cPPS.getPpsRangeExtension().setLog2SaoOffsetScale(CHANNEL_TYPE_LUMA,   m_log2SaoOffsetScale[CHANNEL_TYPE_LUMA  ]);
1053  m_cPPS.getPpsRangeExtension().setLog2SaoOffsetScale(CHANNEL_TYPE_CHROMA, m_log2SaoOffsetScale[CHANNEL_TYPE_CHROMA]);
1054
1055  m_cPPS.setQpOffset(COMPONENT_Cb, m_chromaCbQpOffset );
1056  m_cPPS.setQpOffset(COMPONENT_Cr, m_chromaCrQpOffset );
1057
1058  m_cPPS.setEntropyCodingSyncEnabledFlag( m_entropyCodingSyncEnabledFlag );
1059  m_cPPS.setTilesEnabledFlag( (m_iNumColumnsMinus1 > 0 || m_iNumRowsMinus1 > 0) );
1060  m_cPPS.setUseWP( m_useWeightedPred );
1061  m_cPPS.setWPBiPred( m_useWeightedBiPred );
1062  m_cPPS.setOutputFlagPresentFlag( false );
1063#if NH_MV
1064  m_cPPS.setNumExtraSliceHeaderBits( 2 ); 
1065#endif
1066  m_cPPS.setSignHideFlag(getSignHideFlag());
1067  if ( getDeblockingFilterMetric() )
1068  {
1069    m_cPPS.setDeblockingFilterOverrideEnabledFlag(true);
1070    m_cPPS.setPicDisableDeblockingFilterFlag(false);
1071  }
1072  else
1073  {
1074      m_cPPS.setDeblockingFilterOverrideEnabledFlag( !getLoopFilterOffsetInPPS() );
1075      m_cPPS.setPicDisableDeblockingFilterFlag( getLoopFilterDisable() );
1076    }
1077
1078  if (! m_cPPS.getPicDisableDeblockingFilterFlag())
1079  {
1080    m_cPPS.setDeblockingFilterBetaOffsetDiv2( getLoopFilterBetaOffset() );
1081    m_cPPS.setDeblockingFilterTcOffsetDiv2( getLoopFilterTcOffset() );
1082  }
1083  else
1084  {
1085    m_cPPS.setDeblockingFilterBetaOffsetDiv2(0);
1086    m_cPPS.setDeblockingFilterTcOffsetDiv2(0);
1087  }
1088
1089  // deblockingFilterControlPresentFlag is true if any of the settings differ from the inferred values:
1090  const Bool deblockingFilterControlPresentFlag = m_cPPS.getDeblockingFilterOverrideEnabledFlag() ||
1091                                                  m_cPPS.getPicDisableDeblockingFilterFlag()      ||
1092                                                  m_cPPS.getDeblockingFilterBetaOffsetDiv2() != 0 ||
1093                                                  m_cPPS.getDeblockingFilterTcOffsetDiv2() != 0;
1094
1095  m_cPPS.setDeblockingFilterControlPresentFlag(deblockingFilterControlPresentFlag);
1096
1097  m_cPPS.setLog2ParallelMergeLevelMinus2   (m_log2ParallelMergeLevelMinus2 );
1098  m_cPPS.setCabacInitPresentFlag(CABAC_INIT_PRESENT_FLAG);
1099  m_cPPS.setLoopFilterAcrossSlicesEnabledFlag( m_bLFCrossSliceBoundaryFlag );
1100
1101
1102  Int histogram[MAX_NUM_REF + 1];
1103  for( Int i = 0; i <= MAX_NUM_REF; i++ )
1104  {
1105    histogram[i]=0;
1106  }
1107  for( Int i = 0; i < getGOPSize(); i++)
1108  {
1109    assert(getGOPEntry(i).m_numRefPicsActive >= 0 && getGOPEntry(i).m_numRefPicsActive <= MAX_NUM_REF);
1110    histogram[getGOPEntry(i).m_numRefPicsActive]++;
1111  }
1112
1113  Int maxHist=-1;
1114  Int bestPos=0;
1115  for( Int i = 0; i <= MAX_NUM_REF; i++ )
1116  {
1117    if(histogram[i]>maxHist)
1118    {
1119      maxHist=histogram[i];
1120      bestPos=i;
1121    }
1122  }
1123  assert(bestPos <= 15);
1124  m_cPPS.setNumRefIdxL0DefaultActive(bestPos);
1125  m_cPPS.setNumRefIdxL1DefaultActive(bestPos);
1126  m_cPPS.setTransquantBypassEnableFlag(getTransquantBypassEnableFlag());
1127  m_cPPS.setUseTransformSkip( m_useTransformSkip );
1128  m_cPPS.getPpsRangeExtension().setLog2MaxTransformSkipBlockSize( m_log2MaxTransformSkipBlockSize  );
1129
1130  if (m_sliceSegmentMode != NO_SLICES)
1131  {
1132    m_cPPS.setDependentSliceSegmentsEnabledFlag( true );
1133  }
1134}
1135
1136//Function for initializing m_RPSList, a list of TComReferencePictureSet, based on the GOPEntry objects read from the config file.
1137Void TEncTop::xInitRPS(Bool isFieldCoding)
1138{
1139  TComReferencePictureSet*      rps;
1140
1141  m_cSPS.createRPSList(getGOPSize() + m_extraRPSs + 1);
1142  TComRPSList* rpsList = m_cSPS.getRPSList();
1143
1144  for( Int i = 0; i < getGOPSize()+m_extraRPSs; i++)
1145  {
1146    GOPEntry ge = getGOPEntry(i);
1147    rps = rpsList->getReferencePictureSet(i);
1148    rps->setNumberOfPictures(ge.m_numRefPics);
1149    rps->setNumRefIdc(ge.m_numRefIdc);
1150    Int numNeg = 0;
1151    Int numPos = 0;
1152    for( Int j = 0; j < ge.m_numRefPics; j++)
1153    {
1154      rps->setDeltaPOC(j,ge.m_referencePics[j]);
1155      rps->setUsed(j,ge.m_usedByCurrPic[j]);
1156      if(ge.m_referencePics[j]>0)
1157      {
1158        numPos++;
1159      }
1160      else
1161      {
1162        numNeg++;
1163      }
1164    }
1165    rps->setNumberOfNegativePictures(numNeg);
1166    rps->setNumberOfPositivePictures(numPos);
1167
1168    // handle inter RPS intialization from the config file.
1169    rps->setInterRPSPrediction(ge.m_interRPSPrediction > 0);  // not very clean, converting anything > 0 to true.
1170    rps->setDeltaRIdxMinus1(0);                               // index to the Reference RPS is always the previous one.
1171    TComReferencePictureSet*     RPSRef = i>0 ? rpsList->getReferencePictureSet(i-1): NULL;  // get the reference RPS
1172
1173    if (ge.m_interRPSPrediction == 2)  // Automatic generation of the inter RPS idc based on the RIdx provided.
1174    {
1175      assert (RPSRef!=NULL);
1176      Int deltaRPS = getGOPEntry(i-1).m_POC - ge.m_POC;  // the ref POC - current POC
1177      Int numRefDeltaPOC = RPSRef->getNumberOfPictures();
1178
1179      rps->setDeltaRPS(deltaRPS);           // set delta RPS
1180      rps->setNumRefIdc(numRefDeltaPOC+1);  // set the numRefIdc to the number of pictures in the reference RPS + 1.
1181      Int count=0;
1182      for (Int j = 0; j <= numRefDeltaPOC; j++ ) // cycle through pics in reference RPS.
1183      {
1184        Int RefDeltaPOC = (j<numRefDeltaPOC)? RPSRef->getDeltaPOC(j): 0;  // if it is the last decoded picture, set RefDeltaPOC = 0
1185        rps->setRefIdc(j, 0);
1186        for (Int k = 0; k < rps->getNumberOfPictures(); k++ )  // cycle through pics in current RPS.
1187        {
1188          if (rps->getDeltaPOC(k) == ( RefDeltaPOC + deltaRPS))  // if the current RPS has a same picture as the reference RPS.
1189          {
1190              rps->setRefIdc(j, (rps->getUsed(k)?1:2));
1191              count++;
1192              break;
1193          }
1194        }
1195      }
1196      if (count != rps->getNumberOfPictures())
1197      {
1198        printf("Warning: Unable fully predict all delta POCs using the reference RPS index given in the config file.  Setting Inter RPS to false for this RPS.\n");
1199        rps->setInterRPSPrediction(0);
1200      }
1201    }
1202    else if (ge.m_interRPSPrediction == 1)  // inter RPS idc based on the RefIdc values provided in config file.
1203    {
1204      assert (RPSRef!=NULL);
1205      rps->setDeltaRPS(ge.m_deltaRPS);
1206      rps->setNumRefIdc(ge.m_numRefIdc);
1207      for (Int j = 0; j < ge.m_numRefIdc; j++ )
1208      {
1209        rps->setRefIdc(j, ge.m_refIdc[j]);
1210      }
1211      // the following code overwrite the deltaPOC and Used by current values read from the config file with the ones
1212      // computed from the RefIdc.  A warning is printed if they are not identical.
1213      numNeg = 0;
1214      numPos = 0;
1215      TComReferencePictureSet      RPSTemp;  // temporary variable
1216
1217      for (Int j = 0; j < ge.m_numRefIdc; j++ )
1218      {
1219        if (ge.m_refIdc[j])
1220        {
1221          Int deltaPOC = ge.m_deltaRPS + ((j < RPSRef->getNumberOfPictures())? RPSRef->getDeltaPOC(j) : 0);
1222          RPSTemp.setDeltaPOC((numNeg+numPos),deltaPOC);
1223          RPSTemp.setUsed((numNeg+numPos),ge.m_refIdc[j]==1?1:0);
1224          if (deltaPOC<0)
1225          {
1226            numNeg++;
1227          }
1228          else
1229          {
1230            numPos++;
1231          }
1232        }
1233      }
1234      if (numNeg != rps->getNumberOfNegativePictures())
1235      {
1236        printf("Warning: number of negative pictures in RPS is different between intra and inter RPS specified in the config file.\n");
1237        rps->setNumberOfNegativePictures(numNeg);
1238        rps->setNumberOfPictures(numNeg+numPos);
1239      }
1240      if (numPos != rps->getNumberOfPositivePictures())
1241      {
1242        printf("Warning: number of positive pictures in RPS is different between intra and inter RPS specified in the config file.\n");
1243        rps->setNumberOfPositivePictures(numPos);
1244        rps->setNumberOfPictures(numNeg+numPos);
1245      }
1246      RPSTemp.setNumberOfPictures(numNeg+numPos);
1247      RPSTemp.setNumberOfNegativePictures(numNeg);
1248      RPSTemp.sortDeltaPOC();     // sort the created delta POC before comparing
1249      // check if Delta POC and Used are the same
1250      // print warning if they are not.
1251      for (Int j = 0; j < ge.m_numRefIdc; j++ )
1252      {
1253        if (RPSTemp.getDeltaPOC(j) != rps->getDeltaPOC(j))
1254        {
1255          printf("Warning: delta POC is different between intra RPS and inter RPS specified in the config file.\n");
1256          rps->setDeltaPOC(j,RPSTemp.getDeltaPOC(j));
1257        }
1258        if (RPSTemp.getUsed(j) != rps->getUsed(j))
1259        {
1260          printf("Warning: Used by Current in RPS is different between intra and inter RPS specified in the config file.\n");
1261          rps->setUsed(j,RPSTemp.getUsed(j));
1262        }
1263      }
1264    }
1265  }
1266  //In case of field coding, we need to set special parameters for the first bottom field of the sequence, since it is not specified in the cfg file.
1267  //The position = GOPSize + extraRPSs which is (a priori) unused is reserved for this field in the RPS.
1268  if (isFieldCoding)
1269  {
1270    rps = rpsList->getReferencePictureSet(getGOPSize()+m_extraRPSs);
1271    rps->setNumberOfPictures(1);
1272    rps->setNumberOfNegativePictures(1);
1273    rps->setNumberOfPositivePictures(0);
1274    rps->setNumberOfLongtermPictures(0);
1275    rps->setDeltaPOC(0,-1);
1276    rps->setPOC(0,0);
1277    rps->setUsed(0,true);
1278    rps->setInterRPSPrediction(false);
1279    rps->setDeltaRIdxMinus1(0);
1280    rps->setDeltaRPS(0);
1281    rps->setNumRefIdc(0);
1282  }
1283}
1284
1285   // This is a function that
1286   // determines what Reference Picture Set to use
1287   // for a specific slice (with POC = POCCurr)
1288Void TEncTop::selectReferencePictureSet(TComSlice* slice, Int POCCurr, Int GOPid )
1289{
1290#if NH_MV
1291  if( slice->getRapPicFlag() == true && getLayerId() > 0 && POCCurr == 0 )
1292  {
1293    TComReferencePictureSet* rps = slice->getLocalRPS();
1294    rps->setNumberOfNegativePictures(0);
1295    rps->setNumberOfPositivePictures(0);
1296    rps->setNumberOfLongtermPictures(0);
1297    rps->setNumberOfPictures(0);
1298    slice->setRPS(rps);
1299  }
1300  else
1301  {
1302#endif
1303  slice->setRPSidx(GOPid);
1304
1305  for(Int extraNum=m_iGOPSize; extraNum<m_extraRPSs+m_iGOPSize; extraNum++)
1306  {
1307    if(m_uiIntraPeriod > 0 && getDecodingRefreshType() > 0)
1308    {
1309      Int POCIndex = POCCurr%m_uiIntraPeriod;
1310      if(POCIndex == 0)
1311      {
1312        POCIndex = m_uiIntraPeriod;
1313      }
1314      if(POCIndex == m_GOPList[extraNum].m_POC)
1315      {
1316        slice->setRPSidx(extraNum);
1317      }
1318    }
1319    else
1320    {
1321      if(POCCurr==m_GOPList[extraNum].m_POC)
1322      {
1323        slice->setRPSidx(extraNum);
1324      }
1325    }
1326  }
1327
1328  if(POCCurr == 1 && slice->getPic()->isField())
1329  {
1330    slice->setRPSidx(m_iGOPSize+m_extraRPSs);
1331  }
1332
1333  const TComReferencePictureSet *rps = (slice->getSPS()->getRPSList()->getReferencePictureSet(slice->getRPSidx()));
1334  slice->setRPS(rps);
1335#if NH_MV
1336  }
1337#endif
1338
1339}
1340
1341Int TEncTop::getReferencePictureSetIdxForSOP(Int POCCurr, Int GOPid )
1342{
1343  Int rpsIdx = GOPid;
1344
1345  for(Int extraNum=m_iGOPSize; extraNum<m_extraRPSs+m_iGOPSize; extraNum++)
1346  {
1347    if(m_uiIntraPeriod > 0 && getDecodingRefreshType() > 0)
1348    {
1349      Int POCIndex = POCCurr%m_uiIntraPeriod;
1350      if(POCIndex == 0)
1351      {
1352        POCIndex = m_uiIntraPeriod;
1353      }
1354      if(POCIndex == m_GOPList[extraNum].m_POC)
1355      {
1356        rpsIdx = extraNum;
1357      }
1358    }
1359    else
1360    {
1361      if(POCCurr==m_GOPList[extraNum].m_POC)
1362      {
1363        rpsIdx = extraNum;
1364      }
1365    }
1366  }
1367
1368  return rpsIdx;
1369}
1370
1371Void  TEncTop::xInitPPSforTiles()
1372{
1373  m_cPPS.setTileUniformSpacingFlag( m_tileUniformSpacingFlag );
1374  m_cPPS.setNumTileColumnsMinus1( m_iNumColumnsMinus1 );
1375  m_cPPS.setNumTileRowsMinus1( m_iNumRowsMinus1 );
1376  if( !m_tileUniformSpacingFlag )
1377  {
1378    m_cPPS.setTileColumnWidth( m_tileColumnWidth );
1379    m_cPPS.setTileRowHeight( m_tileRowHeight );
1380  }
1381  m_cPPS.setLoopFilterAcrossTilesEnabledFlag( m_loopFilterAcrossTilesEnabledFlag );
1382
1383  // # substreams is "per tile" when tiles are independent.
1384}
1385
1386Void  TEncCfg::xCheckGSParameters()
1387{
1388  Int   iWidthInCU = ( m_iSourceWidth%m_maxCUWidth ) ? m_iSourceWidth/m_maxCUWidth + 1 : m_iSourceWidth/m_maxCUWidth;
1389  Int   iHeightInCU = ( m_iSourceHeight%m_maxCUHeight ) ? m_iSourceHeight/m_maxCUHeight + 1 : m_iSourceHeight/m_maxCUHeight;
1390  UInt  uiCummulativeColumnWidth = 0;
1391  UInt  uiCummulativeRowHeight = 0;
1392
1393  //check the column relative parameters
1394  if( m_iNumColumnsMinus1 >= (1<<(LOG2_MAX_NUM_COLUMNS_MINUS1+1)) )
1395  {
1396    printf( "The number of columns is larger than the maximum allowed number of columns.\n" );
1397    exit( EXIT_FAILURE );
1398  }
1399
1400  if( m_iNumColumnsMinus1 >= iWidthInCU )
1401  {
1402    printf( "The current picture can not have so many columns.\n" );
1403    exit( EXIT_FAILURE );
1404  }
1405
1406  if( m_iNumColumnsMinus1 && !m_tileUniformSpacingFlag )
1407  {
1408    for(Int i=0; i<m_iNumColumnsMinus1; i++)
1409    {
1410      uiCummulativeColumnWidth += m_tileColumnWidth[i];
1411    }
1412
1413    if( uiCummulativeColumnWidth >= iWidthInCU )
1414    {
1415      printf( "The width of the column is too large.\n" );
1416      exit( EXIT_FAILURE );
1417    }
1418  }
1419
1420  //check the row relative parameters
1421  if( m_iNumRowsMinus1 >= (1<<(LOG2_MAX_NUM_ROWS_MINUS1+1)) )
1422  {
1423    printf( "The number of rows is larger than the maximum allowed number of rows.\n" );
1424    exit( EXIT_FAILURE );
1425  }
1426
1427  if( m_iNumRowsMinus1 >= iHeightInCU )
1428  {
1429    printf( "The current picture can not have so many rows.\n" );
1430    exit( EXIT_FAILURE );
1431  }
1432
1433  if( m_iNumRowsMinus1 && !m_tileUniformSpacingFlag )
1434  {
1435    for(Int i=0; i<m_iNumRowsMinus1; i++)
1436    {
1437      uiCummulativeRowHeight += m_tileRowHeight[i];
1438    }
1439
1440    if( uiCummulativeRowHeight >= iHeightInCU )
1441    {
1442      printf( "The height of the row is too large.\n" );
1443      exit( EXIT_FAILURE );
1444    }
1445  }
1446}
1447
1448#if NH_MV
1449Int TEncTop::getFrameId(Int iGOPid) 
1450{
1451  if(m_iPOCLast == 0)
1452  {
1453    return(0 );
1454  }
1455  else
1456  {
1457    return m_iPOCLast -m_iNumPicRcvd+ getGOPEntry(iGOPid).m_POC ;
1458  }
1459}
1460
1461TComPic* TEncTop::getPic( Int poc )
1462{
1463  TComList<TComPic*>* listPic = getListPic();
1464  TComPic* pcPic = NULL;
1465  for(TComList<TComPic*>::iterator it=listPic->begin(); it!=listPic->end(); it++)
1466  {
1467    if( (*it)->getPOC() == poc )
1468    {
1469      pcPic = *it ;
1470      break ;
1471    }
1472  }
1473  return pcPic;
1474}
1475
1476#endif
1477
1478
1479//! \}
Note: See TracBrowser for help on using the repository browser.