source: 3DVCSoftware/branches/HTM-DEV-0.1-dev/source/App/TAppEncoder/TAppEncCfg.cpp @ 363

Last change on this file since 363 was 363, checked in by tech, 12 years ago

Fixed wrongly merged parts.

  • Property svn:eol-style set to native
File size: 97.2 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-2013, 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     TAppEncCfg.cpp
35    \brief    Handle encoder configuration parameters
36*/
37
38#include <stdlib.h>
39#include <cassert>
40#include <cstring>
41#include <string>
42#include "TLibCommon/TComRom.h"
43#include "TAppEncCfg.h"
44
45static istream& operator>>(istream &, Level::Name &);
46static istream& operator>>(istream &, Level::Tier &);
47static istream& operator>>(istream &, Profile::Name &);
48
49#include "TAppCommon/program_options_lite.h"
50#include "TLibEncoder/TEncRateCtrl.h"
51#ifdef WIN32
52#define strdup _strdup
53#endif
54
55using namespace std;
56namespace po = df::program_options_lite;
57
58//! \ingroup TAppEncoder
59//! \{
60
61// ====================================================================================================================
62// Constructor / destructor / initialization / destroy
63// ====================================================================================================================
64
65TAppEncCfg::TAppEncCfg()
66#if H_MV
67: m_pchBitstreamFile()
68#else
69: m_pchInputFile()
70, m_pchBitstreamFile()
71, m_pchReconFile()
72#endif
73, m_pchdQPFile()
74, m_pColumnWidth()
75, m_pRowHeight()
76, m_scalingListFile()
77{
78#if !H_MV
79  m_aidQP = NULL;
80#endif
81#if J0149_TONE_MAPPING_SEI
82  m_startOfCodedInterval = NULL;
83  m_codedPivotValue = NULL;
84  m_targetPivotValue = NULL;
85#endif
86}
87
88TAppEncCfg::~TAppEncCfg()
89{
90#if H_MV
91  for( Int layer = 0; layer < m_aidQP.size(); layer++ )
92  {
93    if ( m_aidQP[layer] != NULL )
94    {
95      delete[] m_aidQP[layer];
96      m_aidQP[layer] = NULL;
97    }
98  }
99  for(Int i = 0; i< m_pchInputFileList.size(); i++ )
100  {
101    if ( m_pchInputFileList[i] != NULL )
102      free (m_pchInputFileList[i]);
103  }
104#else
105  if ( m_aidQP )
106  {
107    delete[] m_aidQP;
108  }
109  free(m_pchInputFile);
110#endif
111#if J0149_TONE_MAPPING_SEI
112  if ( m_startOfCodedInterval )
113  {
114    delete[] m_startOfCodedInterval;
115    m_startOfCodedInterval = NULL;
116  }
117   if ( m_codedPivotValue )
118  {
119    delete[] m_codedPivotValue;
120    m_codedPivotValue = NULL;
121  }
122  if ( m_targetPivotValue )
123  {
124    delete[] m_targetPivotValue;
125    m_targetPivotValue = NULL;
126  }
127#endif
128  free(m_pchBitstreamFile);
129
130#if H_MV
131  for(Int i = 0; i< m_pchReconFileList.size(); i++ )
132  {
133    if ( m_pchReconFileList[i] != NULL )
134      free (m_pchReconFileList[i]);
135  }
136#else
137  free(m_pchReconFile);
138#endif
139
140  free(m_pchdQPFile);
141  free(m_pColumnWidth);
142  free(m_pRowHeight);
143  free(m_scalingListFile);
144
145#if H_MV
146  for( Int i = 0; i < m_GOPListMvc.size(); i++ )
147  {
148    if( m_GOPListMvc[i] )
149    {
150      delete[] m_GOPListMvc[i];
151      m_GOPListMvc[i] = NULL;
152    }
153  }
154#endif
155}
156
157Void TAppEncCfg::create()
158{
159}
160
161Void TAppEncCfg::destroy()
162{
163}
164
165std::istringstream &operator>>(std::istringstream &in, GOPEntry &entry)     //input
166{
167  in>>entry.m_sliceType;
168  in>>entry.m_POC;
169  in>>entry.m_QPOffset;
170  in>>entry.m_QPFactor;
171  in>>entry.m_tcOffsetDiv2;
172  in>>entry.m_betaOffsetDiv2;
173  in>>entry.m_temporalId;
174  in>>entry.m_numRefPicsActive;
175  in>>entry.m_numRefPics;
176  for ( Int i = 0; i < entry.m_numRefPics; i++ )
177  {
178    in>>entry.m_referencePics[i];
179  }
180  in>>entry.m_interRPSPrediction;
181#if AUTO_INTER_RPS
182  if (entry.m_interRPSPrediction==1)
183  {
184    in>>entry.m_deltaRPS;
185    in>>entry.m_numRefIdc;
186    for ( Int i = 0; i < entry.m_numRefIdc; i++ )
187    {
188      in>>entry.m_refIdc[i];
189    }
190  }
191  else if (entry.m_interRPSPrediction==2)
192  {
193    in>>entry.m_deltaRPS;
194  }
195#else
196  if (entry.m_interRPSPrediction)
197  {
198    in>>entry.m_deltaRPS;
199    in>>entry.m_numRefIdc;
200    for ( Int i = 0; i < entry.m_numRefIdc; i++ )
201    {
202      in>>entry.m_refIdc[i];
203    }
204  }
205#endif
206#if H_MV
207  in>>entry.m_numInterViewRefPics;
208  for( Int i = 0; i < entry.m_numInterViewRefPics; i++ )
209  {
210    in>>entry.m_interViewRefs[i];
211  }
212  for( Int i = 0; i < entry.m_numInterViewRefPics; i++ )
213  {
214    in>>entry.m_interViewRefPosL[0][i];
215  }
216  for( Int i = 0; i < entry.m_numInterViewRefPics; i++ )
217  {
218    in>>entry.m_interViewRefPosL[1][i];
219  }
220#endif
221  return in;
222}
223
224static const struct MapStrToProfile {
225  const Char* str;
226  Profile::Name value;
227} strToProfile[] = {
228  {"none", Profile::NONE},
229  {"main", Profile::MAIN},
230  {"main10", Profile::MAIN10},
231  {"main-still-picture", Profile::MAINSTILLPICTURE},
232#if H_MV
233  {"main-stereo",    Profile::MAINSTEREO},
234  {"main-multiview", Profile::MAINMULTIVIEW},
235#if H_3D
236  {"main-3d"    , Profile::MAIN3D},
237#endif
238#endif
239};
240
241static const struct MapStrToTier {
242  const Char* str;
243  Level::Tier value;
244} strToTier[] = {
245  {"main", Level::MAIN},
246  {"high", Level::HIGH},
247};
248
249static const struct MapStrToLevel {
250  const Char* str;
251  Level::Name value;
252} strToLevel[] = {
253  {"none",Level::NONE},
254  {"1",   Level::LEVEL1},
255  {"2",   Level::LEVEL2},
256  {"2.1", Level::LEVEL2_1},
257  {"3",   Level::LEVEL3},
258  {"3.1", Level::LEVEL3_1},
259  {"4",   Level::LEVEL4},
260  {"4.1", Level::LEVEL4_1},
261  {"5",   Level::LEVEL5},
262  {"5.1", Level::LEVEL5_1},
263  {"5.2", Level::LEVEL5_2},
264  {"6",   Level::LEVEL6},
265  {"6.1", Level::LEVEL6_1},
266  {"6.2", Level::LEVEL6_2},
267};
268
269template<typename T, typename P>
270static istream& readStrToEnum(P map[], unsigned long mapLen, istream &in, T &val)
271{
272  string str;
273  in >> str;
274
275  for (Int i = 0; i < mapLen; i++)
276  {
277    if (str == map[i].str)
278    {
279      val = map[i].value;
280      goto found;
281    }
282  }
283  /* not found */
284  in.setstate(ios::failbit);
285found:
286  return in;
287}
288
289static istream& operator>>(istream &in, Profile::Name &profile)
290{
291  return readStrToEnum(strToProfile, sizeof(strToProfile)/sizeof(*strToProfile), in, profile);
292}
293
294static istream& operator>>(istream &in, Level::Tier &tier)
295{
296  return readStrToEnum(strToTier, sizeof(strToTier)/sizeof(*strToTier), in, tier);
297}
298
299static istream& operator>>(istream &in, Level::Name &level)
300{
301  return readStrToEnum(strToLevel, sizeof(strToLevel)/sizeof(*strToLevel), in, level);
302}
303
304#if SIGNAL_BITRATE_PICRATE_IN_VPS
305Void readBoolString(const string inpString, const Int numEntries, Bool* &memberArray, const char *elementName);
306Void readIntString(const string inpString, const Int numEntries, Int* &memberArray, const char *elementName);
307#endif
308// ====================================================================================================================
309// Public member functions
310// ====================================================================================================================
311
312/** \param  argc        number of arguments
313    \param  argv        array of arguments
314    \retval             true when success
315 */
316Bool TAppEncCfg::parseCfg( Int argc, Char* argv[] )
317{
318  Bool do_help = false;
319 
320#if !H_MV
321  string cfg_InputFile;
322#endif
323
324  string cfg_BitstreamFile;
325
326#if !H_MV
327  string cfg_ReconFile;
328#endif
329
330#if H_MV
331  vector<Int>   cfg_dimensionLength; 
332#if H_3D
333  cfg_dimensionLength.push_back( 2  );  // depth
334  cfg_dimensionLength.push_back( 32 );  // texture
335#else
336  cfg_dimensionLength.push_back( 64 ); 
337#endif
338#endif
339
340  string cfg_dQPFile;
341  string cfg_ColumnWidth;
342  string cfg_RowHeight;
343  string cfg_ScalingListFile;
344#if J0149_TONE_MAPPING_SEI
345  string cfg_startOfCodedInterval;
346  string cfg_codedPivotValue;
347  string cfg_targetPivotValue;
348#endif
349#if SIGNAL_BITRATE_PICRATE_IN_VPS
350  string cfg_bitRateInfoPresentFlag;
351  string cfg_picRateInfoPresentFlag;
352  string cfg_avgBitRate;
353  string cfg_maxBitRate;
354  string cfg_avgPicRate;
355  string cfg_constantPicRateIdc;
356#endif
357  po::Options opts;
358  opts.addOptions()
359  ("help", do_help, false, "this help text")
360  ("c", po::parseConfigFile, "configuration file name")
361 
362  // File, I/O and source parameters
363
364#if H_MV
365  ("InputFile_%d,i_%d",       m_pchInputFileList,       (char *) 0 , MAX_NUM_LAYER_IDS , "original Yuv input file name %d")
366#else
367  ("InputFile,i",           cfg_InputFile,     string(""), "Original YUV input file name")
368#endif
369
370  ("BitstreamFile,b",       cfg_BitstreamFile, string(""), "Bitstream output file name")
371
372#if H_MV
373  ("ReconFile_%d,o_%d",       m_pchReconFileList,       (char *) 0 , MAX_NUM_LAYER_IDS , "reconstructed Yuv output file name %d")
374#else
375  ("ReconFile,o",           cfg_ReconFile,     string(""), "Reconstructed YUV output file name")
376#endif
377
378#if H_MV
379  ("NumberOfLayers",        m_numberOfLayers     , 1,                     "Number of layers")
380#if !H_3D
381  ("ScalabilityMask",       m_scalabilityMask    , 1                    , "Scalability Mask")   
382#else
383  ("ScalabilityMask",       m_scalabilityMask    , 3                    , "Scalability Mask, 1: Texture 3: Texture + Depth ")   
384#endif 
385  ("DimensionIdLen",        m_dimensionIdLen     , cfg_dimensionLength  , "Number of bits used to store dimensions Id")
386  ("ViewId",                m_viewId             , std::vector<Int>(1,0), "View Id")
387#if H_3D
388  ("DepthFlag",             m_depthFlag          , std::vector<Int>(1,0), "Depth Flag")
389#endif
390  ("LayerIdInNuh",          m_layerIdInNuh       , std::vector<Int>(1,0), "LayerId in Nuh")
391  ("SplittingFlag",         m_splittingFlag      , false                , "Splitting Flag")   
392#endif
393
394  ("SourceWidth,-wdt",      m_iSourceWidth,        0, "Source picture width")
395  ("SourceHeight,-hgt",     m_iSourceHeight,       0, "Source picture height")
396  ("InputBitDepth",         m_inputBitDepthY,    8, "Bit-depth of input file")
397  ("OutputBitDepth",        m_outputBitDepthY,   0, "Bit-depth of output file (default:InternalBitDepth)")
398  ("InternalBitDepth",      m_internalBitDepthY, 0, "Bit-depth the codec operates at. (default:InputBitDepth)"
399                                                       "If different to InputBitDepth, source data will be converted")
400  ("InputBitDepthC",        m_inputBitDepthC,    0, "As per InputBitDepth but for chroma component. (default:InputBitDepth)")
401  ("OutputBitDepthC",       m_outputBitDepthC,   0, "As per OutputBitDepth but for chroma component. (default:InternalBitDepthC)")
402  ("InternalBitDepthC",     m_internalBitDepthC, 0, "As per InternalBitDepth but for chroma component. (default:IntrenalBitDepth)")
403  ("ConformanceMode",       m_conformanceMode,     0, "Window conformance mode (0: no window, 1:automatic padding, 2:padding, 3:conformance")
404  ("HorizontalPadding,-pdx",m_aiPad[0],            0, "Horizontal source padding for conformance window mode 2")
405  ("VerticalPadding,-pdy",  m_aiPad[1],            0, "Vertical source padding for conformance window mode 2")
406  ("ConfLeft",              m_confLeft,            0, "Left offset for window conformance mode 3")
407  ("ConfRight",             m_confRight,           0, "Right offset for window conformance mode 3")
408  ("ConfTop",               m_confTop,             0, "Top offset for window conformance mode 3")
409  ("ConfBottom",            m_confBottom,          0, "Bottom offset for window conformance mode 3")
410  ("FrameRate,-fr",         m_iFrameRate,          0, "Frame rate")
411  ("FrameSkip,-fs",         m_FrameSkip,          0u, "Number of frames to skip at start of input YUV")
412  ("FramesToBeEncoded,f",   m_framesToBeEncoded,   0, "Number of frames to be encoded (default=all)")
413
414  // Profile and level
415
416  ("Profile", m_profile,   Profile::NONE, "Profile to be used when encoding (Incomplete)")
417  ("Level",   m_level,     Level::NONE,   "Level limit to be used, eg 5.1 (Incomplete)")
418  ("Tier",    m_levelTier, Level::MAIN,   "Tier to use for interpretation of --Level")
419
420#if L0046_CONSTRAINT_FLAGS
421  ("ProgressiveSource", m_progressiveSourceFlag, false, "Indicate that source is progressive")
422  ("InterlacedSource",  m_interlacedSourceFlag,  false, "Indicate that source is interlaced")
423  ("NonPackedSource",   m_nonPackedConstraintFlag, false, "Indicate that source does not contain frame packing")
424  ("FrameOnly",         m_frameOnlyConstraintFlag, false, "Indicate that the bitstream contains only frames")
425#endif
426 
427  // Unit definition parameters
428  ("MaxCUWidth",              m_uiMaxCUWidth,             64u)
429  ("MaxCUHeight",             m_uiMaxCUHeight,            64u)
430  // todo: remove defaults from MaxCUSize
431  ("MaxCUSize,s",             m_uiMaxCUWidth,             64u, "Maximum CU size")
432  ("MaxCUSize,s",             m_uiMaxCUHeight,            64u, "Maximum CU size")
433  ("MaxPartitionDepth,h",     m_uiMaxCUDepth,              4u, "CU depth")
434 
435  ("QuadtreeTULog2MaxSize",   m_uiQuadtreeTULog2MaxSize,   6u, "Maximum TU size in logarithm base 2")
436  ("QuadtreeTULog2MinSize",   m_uiQuadtreeTULog2MinSize,   2u, "Minimum TU size in logarithm base 2")
437 
438  ("QuadtreeTUMaxDepthIntra", m_uiQuadtreeTUMaxDepthIntra, 1u, "Depth of TU tree for intra CUs")
439  ("QuadtreeTUMaxDepthInter", m_uiQuadtreeTUMaxDepthInter, 2u, "Depth of TU tree for inter CUs")
440 
441  // Coding structure paramters
442  ("IntraPeriod,-ip",         m_iIntraPeriod,              -1, "Intra period in frames, (-1: only first frame)")
443  ("DecodingRefreshType,-dr", m_iDecodingRefreshType,       0, "Intra refresh type (0:none 1:CRA 2:IDR)")
444  ("GOPSize,g",               m_iGOPSize,                   1, "GOP size of temporal structure")
445#if !L0034_COMBINED_LIST_CLEANUP
446  ("ListCombination,-lc",     m_bUseLComb,               true, "Combined reference list for uni-prediction estimation in B-slices")
447#endif
448  // motion options
449  ("FastSearch",              m_iFastSearch,                1, "0:Full search  1:Diamond  2:PMVFAST")
450  ("SearchRange,-sr",         m_iSearchRange,              96, "Motion search range")
451  ("BipredSearchRange",       m_bipredSearchRange,          4, "Motion search range for bipred refinement")
452  ("HadamardME",              m_bUseHADME,               true, "Hadamard ME for fractional-pel")
453  ("ASR",                     m_bUseASR,                false, "Adaptive motion search range")
454
455  // Mode decision parameters
456  ("LambdaModifier0,-LM0", m_adLambdaModifier[ 0 ], ( Double )1.0, "Lambda modifier for temporal layer 0")
457  ("LambdaModifier1,-LM1", m_adLambdaModifier[ 1 ], ( Double )1.0, "Lambda modifier for temporal layer 1")
458  ("LambdaModifier2,-LM2", m_adLambdaModifier[ 2 ], ( Double )1.0, "Lambda modifier for temporal layer 2")
459  ("LambdaModifier3,-LM3", m_adLambdaModifier[ 3 ], ( Double )1.0, "Lambda modifier for temporal layer 3")
460  ("LambdaModifier4,-LM4", m_adLambdaModifier[ 4 ], ( Double )1.0, "Lambda modifier for temporal layer 4")
461  ("LambdaModifier5,-LM5", m_adLambdaModifier[ 5 ], ( Double )1.0, "Lambda modifier for temporal layer 5")
462  ("LambdaModifier6,-LM6", m_adLambdaModifier[ 6 ], ( Double )1.0, "Lambda modifier for temporal layer 6")
463  ("LambdaModifier7,-LM7", m_adLambdaModifier[ 7 ], ( Double )1.0, "Lambda modifier for temporal layer 7")
464
465  /* Quantization parameters */
466#if H_MV
467  ("QP,q",          m_fQP, std::vector<double>(1,30.0), "Qp values for each layer, if value is float, QP is switched once during encoding")
468#else
469  ("QP,q",          m_fQP,             30.0, "Qp value, if value is float, QP is switched once during encoding")
470#endif
471  ("DeltaQpRD,-dqr",m_uiDeltaQpRD,       0u, "max dQp offset for slice")
472  ("MaxDeltaQP,d",  m_iMaxDeltaQP,        0, "max dQp offset for block")
473  ("MaxCuDQPDepth,-dqd",  m_iMaxCuDQPDepth,        0, "max depth for a minimum CuDQP")
474
475  ("CbQpOffset,-cbqpofs",  m_cbQpOffset,        0, "Chroma Cb QP Offset")
476  ("CrQpOffset,-crqpofs",  m_crQpOffset,        0, "Chroma Cr QP Offset")
477
478#if ADAPTIVE_QP_SELECTION
479  ("AdaptiveQpSelection,-aqps",   m_bUseAdaptQpSelect,           false, "AdaptiveQpSelection")
480#endif
481
482  ("AdaptiveQP,-aq",                m_bUseAdaptiveQP,           false, "QP adaptation based on a psycho-visual model")
483  ("MaxQPAdaptationRange,-aqr",     m_iQPAdaptationRange,           6, "QP adaptation range")
484  ("dQPFile,m",                     cfg_dQPFile,           string(""), "dQP file name")
485  ("RDOQ",                          m_useRDOQ,                  true )
486  ("RDOQTS",                        m_useRDOQTS,                true )
487#if L0232_RD_PENALTY
488  ("RDpenalty",                     m_rdPenalty,                0,  "RD-penalty for 32x32 TU for intra in non-intra slices. 0:disbaled  1:RD-penalty  2:maximum RD-penalty")
489#endif
490  // Entropy coding parameters
491  ("SBACRD",                         m_bUseSBACRD,                      true, "SBAC based RD estimation")
492 
493  // Deblocking filter parameters
494#if H_MV
495  ("LoopFilterDisable",              m_bLoopFilterDisable,             std::vector<Bool>(1,false), "Disable Loop Filter per Layer" )
496#else
497  ("LoopFilterDisable",              m_bLoopFilterDisable,             false )
498#endif
499  ("LoopFilterOffsetInPPS",          m_loopFilterOffsetInPPS,          false )
500  ("LoopFilterBetaOffset_div2",      m_loopFilterBetaOffsetDiv2,           0 )
501  ("LoopFilterTcOffset_div2",        m_loopFilterTcOffsetDiv2,             0 )
502  ("DeblockingFilterControlPresent", m_DeblockingFilterControlPresent, false )
503#if L0386_DB_METRIC
504  ("DeblockingFilterMetric",         m_DeblockingFilterMetric,         false )
505#endif
506
507  // Coding tools
508  ("AMP",                      m_enableAMP,                 true,  "Enable asymmetric motion partitions")
509  ("TransformSkip",            m_useTransformSkip,          false, "Intra transform skipping")
510  ("TransformSkipFast",        m_useTransformSkipFast,      false, "Fast intra transform skipping")
511#if H_MV
512  ("SAO",                      m_bUseSAO, std::vector<Bool>(1,true), "Enable Sample Adaptive Offset per Layer")
513#else
514  ("SAO",                      m_bUseSAO,                   true,  "Enable Sample Adaptive Offset")
515#endif
516  ("MaxNumOffsetsPerPic",      m_maxNumOffsetsPerPic,       2048,  "Max number of SAO offset per picture (Default: 2048)")   
517  ("SAOLcuBoundary",           m_saoLcuBoundary,            false, "0: right/bottom LCU boundary areas skipped from SAO parameter estimation, 1: non-deblocked pixels are used for those areas")
518  ("SAOLcuBasedOptimization",  m_saoLcuBasedOptimization,   true,  "0: SAO picture-based optimization, 1: SAO LCU-based optimization ")
519  ("SliceMode",                m_sliceMode,                0,     "0: Disable all Recon slice limits, 1: Enforce max # of LCUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
520  ("SliceArgument",            m_sliceArgument,            0,     "Depending on SliceMode being:"
521                                                                   "\t1: max number of CTUs per slice"
522                                                                   "\t2: max number of bytes per slice"
523                                                                   "\t3: max number of tiles per slice")
524  ("SliceSegmentMode",         m_sliceSegmentMode,       0,     "0: Disable all slice segment limits, 1: Enforce max # of LCUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
525  ("SliceSegmentArgument",     m_sliceSegmentArgument,   0,     "Depending on SliceSegmentMode being:"
526                                                                   "\t1: max number of CTUs per slice segment"
527                                                                   "\t2: max number of bytes per slice segment"
528                                                                   "\t3: max number of tiles per slice segment")
529  ("LFCrossSliceBoundaryFlag", m_bLFCrossSliceBoundaryFlag, true)
530
531  ("ConstrainedIntraPred",     m_bUseConstrainedIntraPred,  false, "Constrained Intra Prediction")
532
533  ("PCMEnabledFlag",           m_usePCM,                    false)
534  ("PCMLog2MaxSize",           m_pcmLog2MaxSize,            5u)
535  ("PCMLog2MinSize",           m_uiPCMLog2MinSize,          3u)
536  ("PCMInputBitDepthFlag",     m_bPCMInputBitDepthFlag,     true)
537  ("PCMFilterDisableFlag",     m_bPCMFilterDisableFlag,    false)
538
539  ("LosslessCuEnabled",        m_useLossless, false)
540
541  ("WeightedPredP,-wpP",          m_useWeightedPred,               false,      "Use weighted prediction in P slices")
542  ("WeightedPredB,-wpB",          m_useWeightedBiPred,             false,      "Use weighted (bidirectional) prediction in B slices")
543  ("Log2ParallelMergeLevel",      m_log2ParallelMergeLevel,     2u,          "Parallel merge estimation region")
544  ("UniformSpacingIdc",           m_iUniformSpacingIdr,            0,          "Indicates if the column and row boundaries are distributed uniformly")
545  ("NumTileColumnsMinus1",        m_iNumColumnsMinus1,             0,          "Number of columns in a picture minus 1")
546  ("ColumnWidthArray",            cfg_ColumnWidth,                 string(""), "Array containing ColumnWidth values in units of LCU")
547  ("NumTileRowsMinus1",           m_iNumRowsMinus1,                0,          "Number of rows in a picture minus 1")
548  ("RowHeightArray",              cfg_RowHeight,                   string(""), "Array containing RowHeight values in units of LCU")
549  ("LFCrossTileBoundaryFlag",      m_bLFCrossTileBoundaryFlag,             true,          "1: cross-tile-boundary loop filtering. 0:non-cross-tile-boundary loop filtering")
550  ("WaveFrontSynchro",            m_iWaveFrontSynchro,             0,          "0: no synchro; 1 synchro with TR; 2 TRR etc")
551  ("ScalingList",                 m_useScalingListId,              0,          "0: no scaling list, 1: default scaling lists, 2: scaling lists specified in ScalingListFile")
552  ("ScalingListFile",             cfg_ScalingListFile,             string(""), "Scaling list file name")
553  ("SignHideFlag,-SBH",                m_signHideFlag, 1)
554  ("MaxNumMergeCand",             m_maxNumMergeCand,             5u,         "Maximum number of merge candidates")
555
556  /* Misc. */
557  ("SEIDecodedPictureHash",       m_decodedPictureHashSEIEnabled, 0, "Control generation of decode picture hash SEI messages\n"
558                                                                    "\t3: checksum\n"
559                                                                    "\t2: CRC\n"
560                                                                    "\t1: use MD5\n"
561                                                                    "\t0: disable")
562  ("SEIpictureDigest",            m_decodedPictureHashSEIEnabled, 0, "deprecated alias for SEIDecodedPictureHash")
563  ("TMVPMode", m_TMVPModeId, 1, "TMVP mode 0: TMVP disable for all slices. 1: TMVP enable for all slices (default) 2: TMVP enable for certain slices only")
564  ("FEN", m_bUseFastEnc, false, "fast encoder setting")
565  ("ECU", m_bUseEarlyCU, false, "Early CU setting") 
566  ("FDM", m_useFastDecisionForMerge, true, "Fast decision for Merge RD Cost") 
567  ("CFM", m_bUseCbfFastMode, false, "Cbf fast mode setting")
568  ("ESD", m_useEarlySkipDetection, false, "Early SKIP detection setting")
569#if RATE_CONTROL_LAMBDA_DOMAIN
570  ( "RateControl",         m_RCEnableRateControl,   false, "Rate control: enable rate control" )
571  ( "TargetBitrate",       m_RCTargetBitrate,           0, "Rate control: target bitrate" )
572  ( "KeepHierarchicalBit", m_RCKeepHierarchicalBit, false, "Rate control: keep hierarchical bit allocation in rate control algorithm" )
573  ( "LCULevelRateControl", m_RCLCULevelRC,           true, "Rate control: true: LCU level RC; false: picture level RC" )
574  ( "RCLCUSeparateModel",  m_RCUseLCUSeparateModel,  true, "Rate control: use LCU level separate R-lambda model" )
575  ( "InitialQP",           m_RCInitialQP,               0, "Rate control: initial QP" )
576  ( "RCForceIntraQP",      m_RCForceIntraQP,        false, "Rate control: force intra QP to be equal to initial QP" )
577#else
578  ("RateCtrl,-rc", m_enableRateCtrl, false, "Rate control on/off")
579  ("TargetBitrate,-tbr", m_targetBitrate, 0, "Input target bitrate")
580  ("NumLCUInUnit,-nu", m_numLCUInUnit, 0, "Number of LCUs in an Unit")
581#endif
582
583  ("TransquantBypassEnableFlag", m_TransquantBypassEnableFlag, false, "transquant_bypass_enable_flag indicator in PPS")
584  ("CUTransquantBypassFlagValue", m_CUTransquantBypassFlagValue, false, "Fixed cu_transquant_bypass_flag value, when transquant_bypass_enable_flag is enabled")
585  ("RecalculateQPAccordingToLambda", m_recalculateQPAccordingToLambda, false, "Recalculate QP values according to lambda values. Do not suggest to be enabled in all intra case")
586  ("StrongIntraSmoothing,-sis",      m_useStrongIntraSmoothing,           true, "Enable strong intra smoothing for 32x32 blocks")
587  ("SEIActiveParameterSets",         m_activeParameterSetsSEIEnabled,          0, "Enable generation of active parameter sets SEI messages")
588  ("VuiParametersPresent,-vui",      m_vuiParametersPresentFlag,           false, "Enable generation of vui_parameters()")
589  ("AspectRatioInfoPresent",         m_aspectRatioInfoPresentFlag,         false, "Signals whether aspect_ratio_idc is present")
590  ("AspectRatioIdc",                 m_aspectRatioIdc,                         0, "aspect_ratio_idc")
591  ("SarWidth",                       m_sarWidth,                               0, "horizontal size of the sample aspect ratio")
592  ("SarHeight",                      m_sarHeight,                              0, "vertical size of the sample aspect ratio")
593  ("OverscanInfoPresent",            m_overscanInfoPresentFlag,            false, "Indicates whether conformant decoded pictures are suitable for display using overscan\n")
594  ("OverscanAppropriate",            m_overscanAppropriateFlag,            false, "Indicates whether conformant decoded pictures are suitable for display using overscan\n")
595  ("VideoSignalTypePresent",         m_videoSignalTypePresentFlag,         false, "Signals whether video_format, video_full_range_flag, and colour_description_present_flag are present")
596  ("VideoFormat",                    m_videoFormat,                            5, "Indicates representation of pictures")
597  ("VideoFullRange",                 m_videoFullRangeFlag,                 false, "Indicates the black level and range of luma and chroma signals")
598  ("ColourDescriptionPresent",       m_colourDescriptionPresentFlag,       false, "Signals whether colour_primaries, transfer_characteristics and matrix_coefficients are present")
599  ("ColourPrimaries",                m_colourPrimaries,                        2, "Indicates chromaticity coordinates of the source primaries")
600  ("TransferCharateristics",         m_transferCharacteristics,                2, "Indicates the opto-electronic transfer characteristics of the source")
601  ("MatrixCoefficients",             m_matrixCoefficients,                     2, "Describes the matrix coefficients used in deriving luma and chroma from RGB primaries")
602  ("ChromaLocInfoPresent",           m_chromaLocInfoPresentFlag,           false, "Signals whether chroma_sample_loc_type_top_field and chroma_sample_loc_type_bottom_field are present")
603  ("ChromaSampleLocTypeTopField",    m_chromaSampleLocTypeTopField,            0, "Specifies the location of chroma samples for top field")
604  ("ChromaSampleLocTypeBottomField", m_chromaSampleLocTypeBottomField,         0, "Specifies the location of chroma samples for bottom field")
605  ("NeutralChromaIndication",        m_neutralChromaIndicationFlag,        false, "Indicates that the value of all decoded chroma samples is equal to 1<<(BitDepthCr-1)")
606  ("DefaultDisplayWindowFlag",       m_defaultDisplayWindowFlag,           false, "Indicates the presence of the Default Window parameters")
607  ("DefDispWinLeftOffset",           m_defDispWinLeftOffset,                   0, "Specifies the left offset of the default display window from the conformance window")
608  ("DefDispWinRightOffset",          m_defDispWinRightOffset,                  0, "Specifies the right offset of the default display window from the conformance window")
609  ("DefDispWinTopOffset",            m_defDispWinTopOffset,                    0, "Specifies the top offset of the default display window from the conformance window")
610  ("DefDispWinBottomOffset",         m_defDispWinBottomOffset,                 0, "Specifies the bottom offset of the default display window from the conformance window")
611  ("FrameFieldInfoPresentFlag",      m_frameFieldInfoPresentFlag,               false, "Indicates that pic_struct and field coding related values are present in picture timing SEI messages")
612  ("PocProportionalToTimingFlag",   m_pocProportionalToTimingFlag,         false, "Indicates that the POC value is proportional to the output time w.r.t. first picture in CVS")
613  ("NumTicksPocDiffOneMinus1",      m_numTicksPocDiffOneMinus1,                0, "Number of ticks minus 1 that for a POC difference of one")
614  ("BitstreamRestriction",           m_bitstreamRestrictionFlag,           false, "Signals whether bitstream restriction parameters are present")
615  ("TilesFixedStructure",            m_tilesFixedStructureFlag,            false, "Indicates that each active picture parameter set has the same values of the syntax elements related to tiles")
616  ("MotionVectorsOverPicBoundaries", m_motionVectorsOverPicBoundariesFlag, false, "Indicates that no samples outside the picture boundaries are used for inter prediction")
617  ("MaxBytesPerPicDenom",            m_maxBytesPerPicDenom,                    2, "Indicates a number of bytes not exceeded by the sum of the sizes of the VCL NAL units associated with any coded picture")
618  ("MaxBitsPerMinCuDenom",           m_maxBitsPerMinCuDenom,                   1, "Indicates an upper bound for the number of bits of coding_unit() data")
619  ("Log2MaxMvLengthHorizontal",      m_log2MaxMvLengthHorizontal,             15, "Indicate the maximum absolute value of a decoded horizontal MV component in quarter-pel luma units")
620  ("Log2MaxMvLengthVertical",        m_log2MaxMvLengthVertical,               15, "Indicate the maximum absolute value of a decoded vertical MV component in quarter-pel luma units")
621  ("SEIRecoveryPoint",               m_recoveryPointSEIEnabled,                0, "Control generation of recovery point SEI messages")
622  ("SEIBufferingPeriod",             m_bufferingPeriodSEIEnabled,              0, "Control generation of buffering period SEI messages")
623  ("SEIPictureTiming",               m_pictureTimingSEIEnabled,                0, "Control generation of picture timing SEI messages")
624#if J0149_TONE_MAPPING_SEI
625  ("SEIToneMappingInfo",                       m_toneMappingInfoSEIEnabled,    false, "Control generation of Tone Mapping SEI messages")
626  ("SEIToneMapId",                             m_toneMapId,                        0, "Specifies Id of Tone Mapping SEI message for a given session")
627  ("SEIToneMapCancelFlag",                     m_toneMapCancelFlag,            false, "Indicates that Tone Mapping SEI message cancels the persistance or follows")
628  ("SEIToneMapPersistenceFlag",                m_toneMapPersistenceFlag,        true, "Specifies the persistence of the Tone Mapping SEI message")
629  ("SEIToneMapCodedDataBitDepth",              m_toneMapCodedDataBitDepth,         8, "Specifies Coded Data BitDepth of Tone Mapping SEI messages")
630  ("SEIToneMapTargetBitDepth",                 m_toneMapTargetBitDepth,            8, "Specifies Output BitDepth of Tome mapping function")
631  ("SEIToneMapModelId",                        m_toneMapModelId,                   0, "Specifies Model utilized for mapping coded data into target_bit_depth range\n"
632                                                                                      "\t0:  linear mapping with clipping\n"
633                                                                                      "\t1:  sigmoidal mapping\n"
634                                                                                      "\t2:  user-defined table mapping\n"
635                                                                                      "\t3:  piece-wise linear mapping\n"
636                                                                                      "\t4:  luminance dynamic range information ")
637  ("SEIToneMapMinValue",                              m_toneMapMinValue,                          0, "Specifies the minimum value in mode 0")
638  ("SEIToneMapMaxValue",                              m_toneMapMaxValue,                       1023, "Specifies the maxmum value in mode 0")
639  ("SEIToneMapSigmoidMidpoint",                       m_sigmoidMidpoint,                        512, "Specifies the centre point in mode 1")
640  ("SEIToneMapSigmoidWidth",                          m_sigmoidWidth,                           960, "Specifies the distance between 5% and 95% values of the target_bit_depth in mode 1")
641  ("SEIToneMapStartOfCodedInterval",                  cfg_startOfCodedInterval,          string(""), "Array of user-defined mapping table")
642  ("SEIToneMapNumPivots",                             m_numPivots,                                0, "Specifies the number of pivot points in mode 3")
643  ("SEIToneMapCodedPivotValue",                       cfg_codedPivotValue,               string(""), "Array of pivot point")
644  ("SEIToneMapTargetPivotValue",                      cfg_targetPivotValue,              string(""), "Array of pivot point")
645  ("SEIToneMapCameraIsoSpeedIdc",                     m_cameraIsoSpeedIdc,                        0, "Indicates the camera ISO speed for daylight illumination")
646  ("SEIToneMapCameraIsoSpeedValue",                   m_cameraIsoSpeedValue,                    400, "Specifies the camera ISO speed for daylight illumination of Extended_ISO")
647  ("SEIToneMapExposureCompensationValueSignFlag",     m_exposureCompensationValueSignFlag,        0, "Specifies the sign of ExposureCompensationValue")
648  ("SEIToneMapExposureCompensationValueNumerator",    m_exposureCompensationValueNumerator,       0, "Specifies the numerator of ExposureCompensationValue")
649  ("SEIToneMapExposureCompensationValueDenomIdc",     m_exposureCompensationValueDenomIdc,        2, "Specifies the denominator of ExposureCompensationValue")
650  ("SEIToneMapRefScreenLuminanceWhite",               m_refScreenLuminanceWhite,                350, "Specifies reference screen brightness setting in units of candela per square metre")
651  ("SEIToneMapExtendedRangeWhiteLevel",               m_extendedRangeWhiteLevel,                800, "Indicates the luminance dynamic range")
652  ("SEIToneMapNominalBlackLevelLumaCodeValue",        m_nominalBlackLevelLumaCodeValue,          16, "Specifies luma sample value of the nominal black level assigned decoded pictures")
653  ("SEIToneMapNominalWhiteLevelLumaCodeValue",        m_nominalWhiteLevelLumaCodeValue,         235, "Specifies luma sample value of the nominal white level assigned decoded pictures")
654  ("SEIToneMapExtendedWhiteLevelLumaCodeValue",       m_extendedWhiteLevelLumaCodeValue,        300, "Specifies luma sample value of the extended dynamic range assigned decoded pictures")
655#endif
656  ("SEIFramePacking",                m_framePackingSEIEnabled,                 0, "Control generation of frame packing SEI messages")
657  ("SEIFramePackingType",            m_framePackingSEIType,                    0, "Define frame packing arrangement\n"
658                                                                                  "\t0: checkerboard - pixels alternatively represent either frames\n"
659                                                                                  "\t1: column alternation - frames are interlaced by column\n"
660                                                                                  "\t2: row alternation - frames are interlaced by row\n"
661                                                                                  "\t3: side by side - frames are displayed horizontally\n"
662                                                                                  "\t4: top bottom - frames are displayed vertically\n"
663                                                                                  "\t5: frame alternation - one frame is alternated with the other")
664  ("SEIFramePackingId",              m_framePackingSEIId,                      0, "Id of frame packing SEI message for a given session")
665  ("SEIFramePackingQuincunx",        m_framePackingSEIQuincunx,                0, "Indicate the presence of a Quincunx type video frame")
666  ("SEIFramePackingInterpretation",  m_framePackingSEIInterpretation,          0, "Indicate the interpretation of the frame pair\n"
667                                                                                  "\t0: unspecified\n"
668                                                                                  "\t1: stereo pair, frame0 represents left view\n"
669                                                                                  "\t2: stereo pair, frame0 represents right view")
670  ("SEIDisplayOrientation",          m_displayOrientationSEIAngle,             0, "Control generation of display orientation SEI messages\n"
671                                                              "\tN: 0 < N < (2^16 - 1) enable display orientation SEI message with anticlockwise_rotation = N and display_orientation_repetition_period = 1\n"
672                                                              "\t0: disable")
673  ("SEITemporalLevel0Index",         m_temporalLevel0IndexSEIEnabled,          0, "Control generation of temporal level 0 index SEI messages")
674  ("SEIGradualDecodingRefreshInfo",  m_gradualDecodingRefreshInfoEnabled,      0, "Control generation of gradual decoding refresh information SEI message")
675  ("SEIDecodingUnitInfo",             m_decodingUnitInfoSEIEnabled,                       0, "Control generation of decoding unit information SEI message.")
676#if L0208_SOP_DESCRIPTION_SEI
677  ("SEISOPDescription",              m_SOPDescriptionSEIEnabled,              0, "Control generation of SOP description SEI messages")
678#endif
679#if K0180_SCALABLE_NESTING_SEI
680  ("SEIScalableNesting",             m_scalableNestingSEIEnabled,              0, "Control generation of scalable nesting SEI messages")
681#endif
682#if SIGNAL_BITRATE_PICRATE_IN_VPS
683  ("BitRatePicRateMaxTLayers",   m_bitRatePicRateMaxTLayers,           0, "Maximum number of sub-layers signalled; can be inferred otherwise; here for easy parsing of config. file")
684  ("BitRateInfoPresent",         cfg_bitRateInfoPresentFlag,          string(""), "Control signalling of bit rate information of avg. bit rate and max. bit rate in VPS\n"
685                                                                          "\t0: Do not sent bit rate info\n"
686                                                                          "\tN (N > 0): Send bit rate info for N sub-layers. N should equal maxTempLayers.")                                                                     
687  ("PicRateInfoPresent",         cfg_picRateInfoPresentFlag,          string(""), "Control signalling of picture rate information of avg. bit rate and max. bit rate in VPS\n"
688                                                                          "\t0: Do not sent picture rate info\n"
689                                                                          "\tN (N > 0): Send picture rate info for N sub-layers. N should equal maxTempLayers.")                                                                     
690  ("AvgBitRate",                   cfg_avgBitRate,                    string(""), "List of avg. bit rates for the different sub-layers; include non-negative number even if corresponding flag is 0")
691  ("MaxBitRate",                   cfg_maxBitRate,                    string(""), "List of max. bit rates for the different sub-layers; include non-negative number even if corresponding flag is 0")
692  ("AvgPicRate",                   cfg_avgPicRate,                    string(""), "List of avg. picture rates for the different sub-layers; include non-negative number even if corresponding flag is 0")
693  ("ConstantPicRateIdc",           cfg_constantPicRateIdc,            string(""), "List of constant picture rate IDCs; include non-negative number even if corresponding flag is 0")
694#endif
695  ;
696 
697#if H_MV
698  // parse coding structure
699  for( Int k = 0; k < MAX_NUM_LAYERS; k++ )
700  {
701    m_GOPListMvc.push_back( new GOPEntry[MAX_GOP + 1] );
702    if( k == 0 )
703    {
704      for( Int i = 1; i < MAX_GOP + 1; i++ ) 
705      {
706        std::ostringstream cOSS;
707        cOSS<<"Frame"<<i;
708        opts.addOptions()( cOSS.str(), m_GOPListMvc[k][i-1], GOPEntry() );
709      }
710    }
711    else
712    {
713      std::ostringstream cOSS1;
714      cOSS1<<"FrameI"<<"_l"<<k;
715      opts.addOptions()(cOSS1.str(), m_GOPListMvc[k][MAX_GOP], GOPEntry());
716
717      for( Int i = 1; i < MAX_GOP + 1; i++ ) 
718      {
719        std::ostringstream cOSS2;
720        cOSS2<<"Frame"<<i<<"_l"<<k;
721        opts.addOptions()(cOSS2.str(), m_GOPListMvc[k][i-1], GOPEntry());
722      }
723    }
724  }
725#else
726  for(Int i=1; i<MAX_GOP+1; i++) {
727    std::ostringstream cOSS;
728    cOSS<<"Frame"<<i;
729    opts.addOptions()(cOSS.str(), m_GOPList[i-1], GOPEntry());
730  }
731#endif
732
733  po::setDefaults(opts);
734  const list<const Char*>& argv_unhandled = po::scanArgv(opts, argc, (const Char**) argv);
735
736  for (list<const Char*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
737  {
738    fprintf(stderr, "Unhandled argument ignored: `%s'\n", *it);
739  }
740 
741  if (argc == 1 || do_help)
742  {
743    /* argc == 1: no options have been specified */
744    po::doHelp(cout, opts);
745    return false;
746  }
747 
748  /*
749   * Set any derived parameters
750   */
751  /* convert std::string to c string for compatability */
752
753#if !H_MV
754  m_pchInputFile = cfg_InputFile.empty() ? NULL : strdup(cfg_InputFile.c_str());
755#endif
756
757  m_pchBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
758
759#if !H_MV
760  m_pchReconFile = cfg_ReconFile.empty() ? NULL : strdup(cfg_ReconFile.c_str());
761#endif
762
763  m_pchdQPFile = cfg_dQPFile.empty() ? NULL : strdup(cfg_dQPFile.c_str());
764 
765  Char* pColumnWidth = cfg_ColumnWidth.empty() ? NULL: strdup(cfg_ColumnWidth.c_str());
766  Char* pRowHeight = cfg_RowHeight.empty() ? NULL : strdup(cfg_RowHeight.c_str());
767  if( m_iUniformSpacingIdr == 0 && m_iNumColumnsMinus1 > 0 )
768  {
769    char *columnWidth;
770    int  i=0;
771    m_pColumnWidth = new UInt[m_iNumColumnsMinus1];
772    columnWidth = strtok(pColumnWidth, " ,-");
773    while(columnWidth!=NULL)
774    {
775      if( i>=m_iNumColumnsMinus1 )
776      {
777        printf( "The number of columns whose width are defined is larger than the allowed number of columns.\n" );
778        exit( EXIT_FAILURE );
779      }
780      *( m_pColumnWidth + i ) = atoi( columnWidth );
781      columnWidth = strtok(NULL, " ,-");
782      i++;
783    }
784    if( i<m_iNumColumnsMinus1 )
785    {
786      printf( "The width of some columns is not defined.\n" );
787      exit( EXIT_FAILURE );
788    }
789  }
790  else
791  {
792    m_pColumnWidth = NULL;
793  }
794
795  if( m_iUniformSpacingIdr == 0 && m_iNumRowsMinus1 > 0 )
796  {
797    char *rowHeight;
798    int  i=0;
799    m_pRowHeight = new UInt[m_iNumRowsMinus1];
800    rowHeight = strtok(pRowHeight, " ,-");
801    while(rowHeight!=NULL)
802    {
803      if( i>=m_iNumRowsMinus1 )
804      {
805        printf( "The number of rows whose height are defined is larger than the allowed number of rows.\n" );
806        exit( EXIT_FAILURE );
807      }
808      *( m_pRowHeight + i ) = atoi( rowHeight );
809      rowHeight = strtok(NULL, " ,-");
810      i++;
811    }
812    if( i<m_iNumRowsMinus1 )
813    {
814      printf( "The height of some rows is not defined.\n" );
815      exit( EXIT_FAILURE );
816   }
817  }
818  else
819  {
820    m_pRowHeight = NULL;
821  }
822#if H_MV
823  free ( pColumnWidth );
824  free ( pRowHeight   ); 
825#endif
826
827#if SIGNAL_BITRATE_PICRATE_IN_VPS
828  readBoolString(cfg_bitRateInfoPresentFlag, m_bitRatePicRateMaxTLayers, m_bitRateInfoPresentFlag, "bit rate info. present flag" );
829  readIntString (cfg_avgBitRate,             m_bitRatePicRateMaxTLayers, m_avgBitRate,             "avg. bit rate"               );
830  readIntString (cfg_maxBitRate,             m_bitRatePicRateMaxTLayers, m_maxBitRate,             "max. bit rate"               );
831  readBoolString(cfg_picRateInfoPresentFlag, m_bitRatePicRateMaxTLayers, m_picRateInfoPresentFlag, "bit rate info. present flag" );
832  readIntString (cfg_avgPicRate,             m_bitRatePicRateMaxTLayers, m_avgPicRate,             "avg. pic rate"               );
833  readIntString (cfg_constantPicRateIdc,     m_bitRatePicRateMaxTLayers, m_constantPicRateIdc,     "constant pic rate Idc"       );
834#endif
835  m_scalingListFile = cfg_ScalingListFile.empty() ? NULL : strdup(cfg_ScalingListFile.c_str());
836 
837  /* rules for input, output and internal bitdepths as per help text */
838  if (!m_internalBitDepthY) { m_internalBitDepthY = m_inputBitDepthY; }
839  if (!m_internalBitDepthC) { m_internalBitDepthC = m_internalBitDepthY; }
840  if (!m_inputBitDepthC) { m_inputBitDepthC = m_inputBitDepthY; }
841  if (!m_outputBitDepthY) { m_outputBitDepthY = m_internalBitDepthY; }
842  if (!m_outputBitDepthC) { m_outputBitDepthC = m_internalBitDepthC; }
843
844  // TODO:ChromaFmt assumes 4:2:0 below
845  switch (m_conformanceMode)
846  {
847  case 0:
848    {
849      // no conformance or padding
850      m_confLeft = m_confRight = m_confTop = m_confBottom = 0;
851      m_aiPad[1] = m_aiPad[0] = 0;
852      break;
853    }
854  case 1:
855    {
856      // automatic padding to minimum CU size
857      Int minCuSize = m_uiMaxCUHeight >> (m_uiMaxCUDepth - 1);
858      if (m_iSourceWidth % minCuSize)
859      {
860        m_aiPad[0] = m_confRight  = ((m_iSourceWidth / minCuSize) + 1) * minCuSize - m_iSourceWidth;
861        m_iSourceWidth  += m_confRight;
862      }
863      if (m_iSourceHeight % minCuSize)
864      {
865        m_aiPad[1] = m_confBottom = ((m_iSourceHeight / minCuSize) + 1) * minCuSize - m_iSourceHeight;
866        m_iSourceHeight += m_confBottom;
867      }
868      if (m_aiPad[0] % TComSPS::getWinUnitX(CHROMA_420) != 0)
869      {
870        fprintf(stderr, "Error: picture width is not an integer multiple of the specified chroma subsampling\n");
871        exit(EXIT_FAILURE);
872      }
873      if (m_aiPad[1] % TComSPS::getWinUnitY(CHROMA_420) != 0)
874      {
875        fprintf(stderr, "Error: picture height is not an integer multiple of the specified chroma subsampling\n");
876        exit(EXIT_FAILURE);
877      }
878      break;
879    }
880  case 2:
881    {
882      //padding
883      m_iSourceWidth  += m_aiPad[0];
884      m_iSourceHeight += m_aiPad[1];
885      m_confRight  = m_aiPad[0];
886      m_confBottom = m_aiPad[1];
887      break;
888    }
889  case 3:
890    {
891      // conformance
892      if ((m_confLeft == 0) && (m_confRight == 0) && (m_confTop == 0) && (m_confBottom == 0))
893      {
894        fprintf(stderr, "Warning: Conformance window enabled, but all conformance window parameters set to zero\n");
895      }
896      if ((m_aiPad[1] != 0) || (m_aiPad[0]!=0))
897      {
898        fprintf(stderr, "Warning: Conformance window enabled, padding parameters will be ignored\n");
899      }
900      m_aiPad[1] = m_aiPad[0] = 0;
901      break;
902    }
903  }
904 
905  // allocate slice-based dQP values
906#if H_MV
907  xResizeVector( m_viewId    ); 
908#if H_3D
909  xResizeVector( m_depthFlag ); 
910#endif
911
912  xResizeVector( m_fQP ); 
913
914  for( Int layer = 0; layer < m_numberOfLayers; layer++ )
915  {
916    m_aidQP.push_back( new Int[ m_framesToBeEncoded + m_iGOPSize + 1 ] );
917    ::memset( m_aidQP[layer], 0, sizeof(Int)*( m_framesToBeEncoded + m_iGOPSize + 1 ) );
918
919    // handling of floating-point QP values
920    // if QP is not integer, sequence is split into two sections having QP and QP+1
921    m_iQP.push_back((Int)( m_fQP[layer] ));
922    if ( m_iQP[layer] < m_fQP[layer] )
923    {
924      Int iSwitchPOC = (Int)( m_framesToBeEncoded - (m_fQP[layer] - m_iQP[layer])*m_framesToBeEncoded + 0.5 );
925
926      iSwitchPOC = (Int)( (Double)iSwitchPOC / m_iGOPSize + 0.5 )*m_iGOPSize;
927      for ( Int i=iSwitchPOC; i<m_framesToBeEncoded + m_iGOPSize + 1; i++ )
928      {
929        m_aidQP[layer][i] = 1;
930      }
931    }
932  }
933
934  xResizeVector( m_bLoopFilterDisable ); 
935  xResizeVector( m_bUseSAO );   
936
937#else
938  m_aidQP = new Int[ m_framesToBeEncoded + m_iGOPSize + 1 ];
939  ::memset( m_aidQP, 0, sizeof(Int)*( m_framesToBeEncoded + m_iGOPSize + 1 ) );
940 
941  // handling of floating-point QP values
942  // if QP is not integer, sequence is split into two sections having QP and QP+1
943  m_iQP = (Int)( m_fQP );
944  if ( m_iQP < m_fQP )
945  {
946    Int iSwitchPOC = (Int)( m_framesToBeEncoded - (m_fQP - m_iQP)*m_framesToBeEncoded + 0.5 );
947   
948    iSwitchPOC = (Int)( (Double)iSwitchPOC / m_iGOPSize + 0.5 )*m_iGOPSize;
949    for ( Int i=iSwitchPOC; i<m_framesToBeEncoded + m_iGOPSize + 1; i++ )
950    {
951      m_aidQP[i] = 1;
952    }
953  }
954#endif
955 
956  // reading external dQP description from file
957  if ( m_pchdQPFile )
958  {
959    FILE* fpt=fopen( m_pchdQPFile, "r" );
960    if ( fpt )
961    {
962#if H_MV
963      for( Int layer = 0; layer < m_numberOfLayers; layer++ )
964      {
965#endif
966      Int iValue;
967      Int iPOC = 0;
968      while ( iPOC < m_framesToBeEncoded )
969      {
970        if ( fscanf(fpt, "%d", &iValue ) == EOF ) break;
971#if H_MV
972        m_aidQP[layer][ iPOC ] = iValue;
973        iPOC++;
974      }
975#else
976        m_aidQP[ iPOC ] = iValue;
977        iPOC++;
978#endif
979      }
980      fclose(fpt);
981    }
982  }
983  m_iWaveFrontSubstreams = m_iWaveFrontSynchro ? (m_iSourceHeight + m_uiMaxCUHeight - 1) / m_uiMaxCUHeight : 1;
984
985#if J0149_TONE_MAPPING_SEI
986  if( m_toneMappingInfoSEIEnabled && !m_toneMapCancelFlag )
987  {
988    Char* pcStartOfCodedInterval = cfg_startOfCodedInterval.empty() ? NULL: strdup(cfg_startOfCodedInterval.c_str());
989    Char* pcCodedPivotValue = cfg_codedPivotValue.empty() ? NULL: strdup(cfg_codedPivotValue.c_str());
990    Char* pcTargetPivotValue = cfg_targetPivotValue.empty() ? NULL: strdup(cfg_targetPivotValue.c_str());
991    if( m_toneMapModelId == 2 && pcStartOfCodedInterval )
992    {
993      char *startOfCodedInterval;
994      UInt num = 1u<< m_toneMapTargetBitDepth;
995      m_startOfCodedInterval = new Int[num];
996      ::memset( m_startOfCodedInterval, 0, sizeof(Int)*num );
997      startOfCodedInterval = strtok(pcStartOfCodedInterval, " .");
998      int i = 0;
999      while( startOfCodedInterval && ( i < num ) )
1000      {
1001        m_startOfCodedInterval[i] = atoi( startOfCodedInterval );
1002        startOfCodedInterval = strtok(NULL, " .");
1003        i++;
1004      }
1005    } 
1006    else
1007    {
1008      m_startOfCodedInterval = NULL;
1009    }
1010    if( ( m_toneMapModelId == 3 ) && ( m_numPivots > 0 ) )
1011    {
1012      if( pcCodedPivotValue && pcTargetPivotValue )
1013      {
1014        char *codedPivotValue;
1015        char *targetPivotValue;
1016        m_codedPivotValue = new Int[m_numPivots];
1017        m_targetPivotValue = new Int[m_numPivots];
1018        ::memset( m_codedPivotValue, 0, sizeof(Int)*( m_numPivots ) );
1019        ::memset( m_targetPivotValue, 0, sizeof(Int)*( m_numPivots ) );
1020        codedPivotValue = strtok(pcCodedPivotValue, " .");
1021        int i=0;
1022        while(codedPivotValue&&i<m_numPivots)
1023        {
1024          m_codedPivotValue[i] = atoi( codedPivotValue );
1025          codedPivotValue = strtok(NULL, " .");
1026          i++;
1027        }
1028        i=0;
1029        targetPivotValue = strtok(pcTargetPivotValue, " .");
1030        while(targetPivotValue&&i<m_numPivots)
1031        {
1032          m_targetPivotValue[i]= atoi( targetPivotValue );
1033          targetPivotValue = strtok(NULL, " .");
1034          i++;
1035        }
1036      }
1037    }
1038    else
1039    {
1040      m_codedPivotValue = NULL;
1041      m_targetPivotValue = NULL;
1042    }
1043  }
1044#endif
1045  // check validity of input parameters
1046  xCheckParameter();
1047 
1048  // set global varibles
1049  xSetGlobal();
1050 
1051  // print-out parameters
1052  xPrintParameter();
1053 
1054  return true;
1055}
1056#if SIGNAL_BITRATE_PICRATE_IN_VPS
1057Void readBoolString(const string inpString, const Int numEntries, Bool* &memberArray, const char *elementName)
1058{
1059  Char* inpArray = inpString.empty() ? NULL : strdup(inpString.c_str());
1060  Int i = 0;
1061  if(numEntries)
1062  {
1063    Char* tempArray = strtok(inpArray, " ,-");
1064    memberArray = new Bool[numEntries];
1065    while( tempArray != NULL )
1066    {
1067      if( i >= numEntries )
1068      {
1069        printf( "The number of %s defined is larger than the allowed number\n", elementName );
1070        exit( EXIT_FAILURE );
1071      }
1072      assert( (atoi(tempArray) == 0) || (atoi(tempArray) == 1) );
1073      *( memberArray + i ) = atoi(tempArray);
1074      tempArray = strtok(NULL, " ,-");
1075      i++;
1076    }
1077    if( i < numEntries )
1078    {
1079      printf( "Some %s are not defined\n", elementName );
1080      exit( EXIT_FAILURE );
1081    }
1082  }
1083  else
1084  {
1085    memberArray = NULL;
1086  }
1087}
1088
1089Void readIntString(const string inpString, const Int numEntries, Int* &memberArray, const char *elementName)
1090{
1091  Char* inpArray = inpString.empty() ? NULL : strdup(inpString.c_str());
1092  Int i = 0;
1093  if(numEntries)
1094  {
1095    Char* tempArray = strtok(inpArray, " ,-");
1096    memberArray = new Int[numEntries];
1097    while( tempArray != NULL )
1098    {
1099      if( i >= numEntries )
1100      {
1101        printf( "The number of %s defined is larger than the allowed number\n", elementName );
1102        exit( EXIT_FAILURE );
1103      }
1104      *( memberArray + i ) = atoi(tempArray);
1105      tempArray = strtok(NULL, " ,-");
1106      i++;
1107    }
1108    if( i < numEntries )
1109    {
1110      printf( "Some %s are not defined\n", elementName );
1111      exit( EXIT_FAILURE );
1112    }
1113  }
1114  else
1115  {
1116    memberArray = NULL;
1117  }
1118}
1119#endif
1120// ====================================================================================================================
1121// Private member functions
1122// ====================================================================================================================
1123
1124Bool confirmPara(Bool bflag, const Char* message);
1125
1126Void TAppEncCfg::xCheckParameter()
1127{
1128  if (!m_decodedPictureHashSEIEnabled)
1129  {
1130    fprintf(stderr, "******************************************************************\n");
1131    fprintf(stderr, "** WARNING: --SEIDecodedPictureHash is now disabled by default. **\n");
1132    fprintf(stderr, "**          Automatic verification of decoded pictures by a     **\n");
1133    fprintf(stderr, "**          decoder requires this option to be enabled.         **\n");
1134    fprintf(stderr, "******************************************************************\n");
1135  }
1136
1137  Bool check_failed = false; /* abort if there is a fatal configuration problem */
1138#define xConfirmPara(a,b) check_failed |= confirmPara(a,b)
1139  // check range of parameters
1140  xConfirmPara( m_inputBitDepthY < 8,                                                     "InputBitDepth must be at least 8" );
1141  xConfirmPara( m_inputBitDepthC < 8,                                                     "InputBitDepthC must be at least 8" );
1142  xConfirmPara( m_iFrameRate <= 0,                                                          "Frame rate must be more than 1" );
1143  xConfirmPara( m_framesToBeEncoded <= 0,                                                   "Total Number Of Frames encoded must be more than 0" );
1144
1145#if H_MV
1146  xConfirmPara( m_numberOfLayers > MAX_NUM_LAYER_IDS ,                                      "NumberOfLayers must be less than or equal to MAX_NUM_LAYER_IDS");
1147
1148
1149  xConfirmPara( m_layerIdInNuh[0] != 0      , "LayerIdInNuh must be 0 for the first layer. ");
1150  xConfirmPara( (m_layerIdInNuh.size()!=1) && (m_layerIdInNuh.size() < m_numberOfLayers) , "LayerIdInNuh must be given for all layers. ");
1151 
1152#if H_3D
1153  xConfirmPara( m_scalabilityMask != 1 && m_scalabilityMask != 3, "Scalability Mask must be equal to 1 or 3. ");
1154#else
1155  xConfirmPara( m_scalabilityMask != 1 , "Scalability Mask must be equal to 1. ");
1156#endif
1157 
1158  m_dimIds.push_back( m_viewId ); 
1159#if H_3D
1160  if ( m_scalabilityMask & ( 1 << DEPTH_ID ) )
1161    m_dimIds.push_back( m_depthFlag ); 
1162#endif
1163
1164  xConfirmPara(  m_dimensionIdLen.size() < m_dimIds.size(), "DimensionIdLen must be given for all dimensions. "   ); 
1165
1166 for( Int dim = 0; dim < m_dimIds.size(); dim++ )
1167 {
1168   xConfirmPara( m_dimIds[dim].size() < m_numberOfLayers,  "DimensionId must be given for all layers and all dimensions. ");
1169   xConfirmPara( m_dimIds[dim][0] != 0,                    "DimensionId of layer 0 must be 0 in all dimensions. " );
1170   xConfirmPara( m_dimensionIdLen[dim] < 1 || m_dimensionIdLen[dim] > 8, "DimensionIdLen must be greater than 0 and less than 9 in all dimensions. " ); 
1171   for( Int i = 1; i < m_numberOfLayers; i++ )
1172   {     
1173     xConfirmPara(  ( m_dimIds[dim][i] < 0 ) || ( m_dimIds[dim][i] > ( ( 1 << m_dimensionIdLen[dim] ) - 1 ) )   , "DimensionId shall be in the range of 0 to 2^DimensionIdLen - 1. " );
1174   }
1175 }
1176
1177 for( Int i = 0; i < m_numberOfLayers; i++ )
1178 {
1179   for( Int j = 0; j < i; j++ )
1180   {     
1181     Int numDiff  = 0; 
1182     Int lastDiff = -1; 
1183     for( Int dim = 0; dim < m_dimIds.size(); dim++ )
1184     {
1185       if ( m_dimIds[dim][i] != m_dimIds[dim][j] )
1186       {
1187         numDiff ++; 
1188         lastDiff = dim; 
1189       }
1190     }
1191
1192     Bool allEqual = ( numDiff == 0 ); 
1193
1194     if ( allEqual ) 
1195     {
1196       printf( "\nError: Positions of Layers %d and %d are identical in scalability space\n", i, j);
1197     }
1198
1199     xConfirmPara( allEqual , "Each layer shall have a different position in scalability space." );
1200
1201     if ( numDiff  == 1 ) 
1202     {
1203       Bool inc = m_dimIds[ lastDiff ][ i ] > m_dimIds[ lastDiff ][ j ]; 
1204       if ( !inc )
1205       {       
1206         printf( "\nError: Positions of Layers %d and %d is not increasing in dimension %d \n", i, j, lastDiff);       
1207       }
1208       xConfirmPara( !inc,  "DimensionIds shall be increasing within one dimension. " );
1209     }
1210   }
1211 }
1212
1213#endif
1214
1215
1216  xConfirmPara( m_iGOPSize < 1 ,                                                            "GOP Size must be greater or equal to 1" );
1217  xConfirmPara( m_iGOPSize > 1 &&  m_iGOPSize % 2,                                          "GOP Size must be a multiple of 2, if GOP Size is greater than 1" );
1218  xConfirmPara( (m_iIntraPeriod > 0 && m_iIntraPeriod < m_iGOPSize) || m_iIntraPeriod == 0, "Intra period must be more than GOP size, or -1 , not 0" );
1219  xConfirmPara( m_iDecodingRefreshType < 0 || m_iDecodingRefreshType > 2,                   "Decoding Refresh Type must be equal to 0, 1 or 2" );
1220#if H_MV
1221  for( Int layer = 0; layer < m_numberOfLayers; layer++ )
1222  {
1223    xConfirmPara( m_iQP[layer] <  -6 * (m_internalBitDepthY - 8) || m_iQP[layer] > 51,      "QP exceeds supported range (-QpBDOffsety to 51)" );
1224  }
1225#else
1226  xConfirmPara( m_iQP <  -6 * (m_internalBitDepthY - 8) || m_iQP > 51,                    "QP exceeds supported range (-QpBDOffsety to 51)" );
1227#endif
1228  xConfirmPara( m_loopFilterBetaOffsetDiv2 < -13 || m_loopFilterBetaOffsetDiv2 > 13,          "Loop Filter Beta Offset div. 2 exceeds supported range (-13 to 13)");
1229  xConfirmPara( m_loopFilterTcOffsetDiv2 < -13 || m_loopFilterTcOffsetDiv2 > 13,              "Loop Filter Tc Offset div. 2 exceeds supported range (-13 to 13)");
1230  xConfirmPara( m_iFastSearch < 0 || m_iFastSearch > 2,                                     "Fast Search Mode is not supported value (0:Full search  1:Diamond  2:PMVFAST)" );
1231  xConfirmPara( m_iSearchRange < 0 ,                                                        "Search Range must be more than 0" );
1232  xConfirmPara( m_bipredSearchRange < 0 ,                                                   "Search Range must be more than 0" );
1233  xConfirmPara( m_iMaxDeltaQP > 7,                                                          "Absolute Delta QP exceeds supported range (0 to 7)" );
1234  xConfirmPara( m_iMaxCuDQPDepth > m_uiMaxCUDepth - 1,                                          "Absolute depth for a minimum CuDQP exceeds maximum coding unit depth" );
1235
1236  xConfirmPara( m_cbQpOffset < -12,   "Min. Chroma Cb QP Offset is -12" );
1237  xConfirmPara( m_cbQpOffset >  12,   "Max. Chroma Cb QP Offset is  12" );
1238  xConfirmPara( m_crQpOffset < -12,   "Min. Chroma Cr QP Offset is -12" );
1239  xConfirmPara( m_crQpOffset >  12,   "Max. Chroma Cr QP Offset is  12" );
1240
1241  xConfirmPara( m_iQPAdaptationRange <= 0,                                                  "QP Adaptation Range must be more than 0" );
1242  if (m_iDecodingRefreshType == 2)
1243  {
1244    xConfirmPara( m_iIntraPeriod > 0 && m_iIntraPeriod <= m_iGOPSize ,                      "Intra period must be larger than GOP size for periodic IDR pictures");
1245  }
1246  xConfirmPara( (m_uiMaxCUWidth  >> m_uiMaxCUDepth) < 4,                                    "Minimum partition width size should be larger than or equal to 8");
1247  xConfirmPara( (m_uiMaxCUHeight >> m_uiMaxCUDepth) < 4,                                    "Minimum partition height size should be larger than or equal to 8");
1248  xConfirmPara( m_uiMaxCUWidth < 16,                                                        "Maximum partition width size should be larger than or equal to 16");
1249  xConfirmPara( m_uiMaxCUHeight < 16,                                                       "Maximum partition height size should be larger than or equal to 16");
1250  xConfirmPara( (m_iSourceWidth  % (m_uiMaxCUWidth  >> (m_uiMaxCUDepth-1)))!=0,             "Resulting coded frame width must be a multiple of the minimum CU size");
1251  xConfirmPara( (m_iSourceHeight % (m_uiMaxCUHeight >> (m_uiMaxCUDepth-1)))!=0,             "Resulting coded frame height must be a multiple of the minimum CU size");
1252 
1253  xConfirmPara( m_uiQuadtreeTULog2MinSize < 2,                                        "QuadtreeTULog2MinSize must be 2 or greater.");
1254  xConfirmPara( m_uiQuadtreeTULog2MaxSize > 5,                                        "QuadtreeTULog2MaxSize must be 5 or smaller.");
1255  xConfirmPara( (1<<m_uiQuadtreeTULog2MaxSize) > m_uiMaxCUWidth,                                        "QuadtreeTULog2MaxSize must be log2(maxCUSize) or smaller.");
1256 
1257  xConfirmPara( m_uiQuadtreeTULog2MaxSize < m_uiQuadtreeTULog2MinSize,                "QuadtreeTULog2MaxSize must be greater than or equal to m_uiQuadtreeTULog2MinSize.");
1258  xConfirmPara( (1<<m_uiQuadtreeTULog2MinSize)>(m_uiMaxCUWidth >>(m_uiMaxCUDepth-1)), "QuadtreeTULog2MinSize must not be greater than minimum CU size" ); // HS
1259  xConfirmPara( (1<<m_uiQuadtreeTULog2MinSize)>(m_uiMaxCUHeight>>(m_uiMaxCUDepth-1)), "QuadtreeTULog2MinSize must not be greater than minimum CU size" ); // HS
1260  xConfirmPara( ( 1 << m_uiQuadtreeTULog2MinSize ) > ( m_uiMaxCUWidth  >> m_uiMaxCUDepth ), "Minimum CU width must be greater than minimum transform size." );
1261  xConfirmPara( ( 1 << m_uiQuadtreeTULog2MinSize ) > ( m_uiMaxCUHeight >> m_uiMaxCUDepth ), "Minimum CU height must be greater than minimum transform size." );
1262  xConfirmPara( m_uiQuadtreeTUMaxDepthInter < 1,                                                         "QuadtreeTUMaxDepthInter must be greater than or equal to 1" );
1263  xConfirmPara( m_uiMaxCUWidth < ( 1 << (m_uiQuadtreeTULog2MinSize + m_uiQuadtreeTUMaxDepthInter - 1) ), "QuadtreeTUMaxDepthInter must be less than or equal to the difference between log2(maxCUSize) and QuadtreeTULog2MinSize plus 1" );
1264  xConfirmPara( m_uiQuadtreeTUMaxDepthIntra < 1,                                                         "QuadtreeTUMaxDepthIntra must be greater than or equal to 1" );
1265  xConfirmPara( m_uiMaxCUWidth < ( 1 << (m_uiQuadtreeTULog2MinSize + m_uiQuadtreeTUMaxDepthIntra - 1) ), "QuadtreeTUMaxDepthInter must be less than or equal to the difference between log2(maxCUSize) and QuadtreeTULog2MinSize plus 1" );
1266 
1267  xConfirmPara(  m_maxNumMergeCand < 1,  "MaxNumMergeCand must be 1 or greater.");
1268  xConfirmPara(  m_maxNumMergeCand > 5,  "MaxNumMergeCand must be 5 or smaller.");
1269
1270#if ADAPTIVE_QP_SELECTION
1271#if H_MV
1272  for( Int layer = 0; layer < m_numberOfLayers; layer++ )
1273  {
1274    xConfirmPara( m_bUseAdaptQpSelect == true && m_iQP[layer] < 0,                                     "AdaptiveQpSelection must be disabled when QP < 0.");
1275  }
1276#else
1277  xConfirmPara( m_bUseAdaptQpSelect == true && m_iQP < 0,                                              "AdaptiveQpSelection must be disabled when QP < 0.");
1278#endif
1279  xConfirmPara( m_bUseAdaptQpSelect == true && (m_cbQpOffset !=0 || m_crQpOffset != 0 ),               "AdaptiveQpSelection must be disabled when ChromaQpOffset is not equal to 0.");
1280#endif
1281
1282  if( m_usePCM)
1283  {
1284    xConfirmPara(  m_uiPCMLog2MinSize < 3,                                      "PCMLog2MinSize must be 3 or greater.");
1285    xConfirmPara(  m_uiPCMLog2MinSize > 5,                                      "PCMLog2MinSize must be 5 or smaller.");
1286    xConfirmPara(  m_pcmLog2MaxSize > 5,                                        "PCMLog2MaxSize must be 5 or smaller.");
1287    xConfirmPara(  m_pcmLog2MaxSize < m_uiPCMLog2MinSize,                       "PCMLog2MaxSize must be equal to or greater than m_uiPCMLog2MinSize.");
1288  }
1289
1290  xConfirmPara( m_sliceMode < 0 || m_sliceMode > 3, "SliceMode exceeds supported range (0 to 3)" );
1291  if (m_sliceMode!=0)
1292  {
1293    xConfirmPara( m_sliceArgument < 1 ,         "SliceArgument should be larger than or equal to 1" );
1294  }
1295  xConfirmPara( m_sliceSegmentMode < 0 || m_sliceSegmentMode > 3, "SliceSegmentMode exceeds supported range (0 to 3)" );
1296  if (m_sliceSegmentMode!=0)
1297  {
1298    xConfirmPara( m_sliceSegmentArgument < 1 ,         "SliceSegmentArgument should be larger than or equal to 1" );
1299  }
1300 
1301  Bool tileFlag = (m_iNumColumnsMinus1 > 0 || m_iNumRowsMinus1 > 0 );
1302  xConfirmPara( tileFlag && m_iWaveFrontSynchro,            "Tile and Wavefront can not be applied together");
1303
1304  //TODO:ChromaFmt assumes 4:2:0 below
1305  xConfirmPara( m_iSourceWidth  % TComSPS::getWinUnitX(CHROMA_420) != 0, "Picture width must be an integer multiple of the specified chroma subsampling");
1306  xConfirmPara( m_iSourceHeight % TComSPS::getWinUnitY(CHROMA_420) != 0, "Picture height must be an integer multiple of the specified chroma subsampling");
1307
1308  xConfirmPara( m_aiPad[0] % TComSPS::getWinUnitX(CHROMA_420) != 0, "Horizontal padding must be an integer multiple of the specified chroma subsampling");
1309  xConfirmPara( m_aiPad[1] % TComSPS::getWinUnitY(CHROMA_420) != 0, "Vertical padding must be an integer multiple of the specified chroma subsampling");
1310
1311  xConfirmPara( m_confLeft   % TComSPS::getWinUnitX(CHROMA_420) != 0, "Left conformance window offset must be an integer multiple of the specified chroma subsampling");
1312  xConfirmPara( m_confRight  % TComSPS::getWinUnitX(CHROMA_420) != 0, "Right conformance window offset must be an integer multiple of the specified chroma subsampling");
1313  xConfirmPara( m_confTop    % TComSPS::getWinUnitY(CHROMA_420) != 0, "Top conformance window offset must be an integer multiple of the specified chroma subsampling");
1314  xConfirmPara( m_confBottom % TComSPS::getWinUnitY(CHROMA_420) != 0, "Bottom conformance window offset must be an integer multiple of the specified chroma subsampling");
1315
1316  // max CU width and height should be power of 2
1317  UInt ui = m_uiMaxCUWidth;
1318  while(ui)
1319  {
1320    ui >>= 1;
1321    if( (ui & 1) == 1)
1322      xConfirmPara( ui != 1 , "Width should be 2^n");
1323  }
1324  ui = m_uiMaxCUHeight;
1325  while(ui)
1326  {
1327    ui >>= 1;
1328    if( (ui & 1) == 1)
1329      xConfirmPara( ui != 1 , "Height should be 2^n");
1330  }
1331
1332#if H_MV
1333  // validate that POC of same frame is identical across multiple layers
1334  Bool bErrorMvePoc = false;
1335  if( m_numberOfLayers > 1 )
1336  {
1337    for( Int k = 1; k < m_numberOfLayers; k++ )
1338    {
1339      for( Int i = 0; i < MAX_GOP; i++ )
1340      {
1341        if( m_GOPListMvc[k][i].m_POC != m_GOPListMvc[0][i].m_POC )
1342        {
1343          printf( "\nError: Frame%d_l%d POC %d is not identical to Frame%d POC\n", i, k, m_GOPListMvc[k][i].m_POC, i );
1344          bErrorMvePoc = true;
1345        }
1346      }
1347    }
1348  }
1349  xConfirmPara( bErrorMvePoc,  "Invalid inter-layer POC structure given" );
1350
1351  // validate that baseview has no inter-view refs
1352  Bool bErrorIvpBase = false;
1353  for( Int i = 0; i < MAX_GOP; i++ )
1354  {
1355    if( m_GOPListMvc[0][i].m_numInterViewRefPics != 0 )
1356    {
1357      printf( "\nError: Frame%d inter_layer refs not available in layer 0\n", i );
1358      bErrorIvpBase = true;
1359    }
1360  }
1361  xConfirmPara( bErrorIvpBase, "Inter-layer refs not possible in base layer" );
1362
1363  // validate inter-view refs
1364  Bool bErrorIvpEnhV = false;
1365  if( m_numberOfLayers > 1 )
1366  {
1367    for( Int k = 1; k < m_numberOfLayers; k++ )
1368    {
1369      for( Int i = 0; i < MAX_GOP+1; i++ )
1370      {
1371        for( Int j = 0; j < m_GOPListMvc[k][i].m_numInterViewRefPics; j++ )
1372        {
1373          Int iAbsViewId = m_GOPListMvc[k][i].m_interViewRefs[j] + k;
1374          if( iAbsViewId < 0 || iAbsViewId >= k )
1375          {
1376            printf( "\nError: inter-layer ref pic %d is not available for Frame%d_l%d\n", m_GOPListMvc[k][i].m_interViewRefs[j], i, k );
1377            bErrorIvpEnhV = true;
1378          }
1379          if( m_GOPListMvc[k][i].m_interViewRefPosL[0][j] < -1 || m_GOPListMvc[k][i].m_interViewRefPosL[0][j] > m_GOPListMvc[k][i].m_numRefPicsActive )
1380          {
1381            printf( "\nError: inter-layer ref pos %d on L0 is not available for Frame%d_l%d\n", m_GOPListMvc[k][i].m_interViewRefPosL[0][j], i, k );
1382            bErrorIvpEnhV = true;
1383          }
1384          if( m_GOPListMvc[k][i].m_interViewRefPosL[1][j] < -1  || m_GOPListMvc[k][i].m_interViewRefPosL[1][j] > m_GOPListMvc[k][i].m_numRefPicsActive )
1385          {
1386            printf( "\nError: inter-layer ref pos %d on L1 is not available for Frame%d_l%d\n", m_GOPListMvc[k][i].m_interViewRefPosL[1][j], i, k );
1387            bErrorIvpEnhV = true;
1388          }
1389        }
1390        if( i == MAX_GOP ) // inter-view refs at I pic position in base view
1391        {
1392          if( m_GOPListMvc[k][MAX_GOP].m_sliceType != 'B' && m_GOPListMvc[k][MAX_GOP].m_sliceType != 'P' && m_GOPListMvc[k][MAX_GOP].m_sliceType != 'I' )
1393          {
1394            printf( "\nError: slice type of FrameI_l%d must be equal to B or P or I\n", k );
1395            bErrorIvpEnhV = true;
1396          }
1397
1398          if( m_GOPListMvc[k][MAX_GOP].m_POC != 0 )
1399          {
1400            printf( "\nError: POC %d not possible for FrameI_l%d, must be 0\n", m_GOPListMvc[k][MAX_GOP].m_POC, k );
1401            bErrorIvpEnhV = true;
1402          }
1403
1404          if( m_GOPListMvc[k][MAX_GOP].m_temporalId != 0 )
1405          {
1406            printf( "\nWarning: Temporal id of FrameI_l%d must be 0 (cp. I-frame in base layer)\n", k );
1407            m_GOPListMvc[k][MAX_GOP].m_temporalId = 0;
1408          }
1409
1410          if( m_GOPListMvc[k][MAX_GOP].m_numRefPics != 0 )
1411          {
1412            printf( "\nWarning: temporal references not possible for FrameI_l%d\n", k );
1413            for( Int j = 0; j < m_GOPListMvc[k][MAX_GOP].m_numRefPics; j++ )
1414            {
1415              m_GOPListMvc[k][MAX_GOP].m_referencePics[j] = 0;
1416            }
1417            m_GOPListMvc[k][MAX_GOP].m_numRefPics = 0;
1418          }
1419
1420          if( m_GOPListMvc[k][MAX_GOP].m_interRPSPrediction )
1421          {
1422            printf( "\nError: inter RPS prediction not possible for FrameI_l%d, must be 0\n", k );
1423            bErrorIvpEnhV = true;
1424          }
1425
1426          if( m_GOPListMvc[k][MAX_GOP].m_sliceType == 'I' && m_GOPListMvc[k][MAX_GOP].m_numInterViewRefPics != 0 )
1427          {
1428            printf( "\nError: inter-layer prediction not possible for FrameI_l%d with slice type I, #IL_ref_pics must be 0\n", k );
1429            bErrorIvpEnhV = true;
1430          }
1431
1432          if( m_GOPListMvc[k][MAX_GOP].m_numRefPicsActive > m_GOPListMvc[k][MAX_GOP].m_numInterViewRefPics )
1433          {
1434            m_GOPListMvc[k][MAX_GOP].m_numRefPicsActive = m_GOPListMvc[k][MAX_GOP].m_numInterViewRefPics;
1435          }
1436
1437          if( m_GOPListMvc[k][MAX_GOP].m_sliceType == 'P' )
1438          {
1439            if( m_GOPListMvc[k][MAX_GOP].m_numInterViewRefPics < 1 )
1440            {
1441              printf( "\nError: #IL_ref_pics must be at least one for FrameI_l%d with slice type P\n", k );
1442              bErrorIvpEnhV = true;
1443            }
1444            else
1445            {
1446              for( Int j = 0; j < m_GOPListMvc[k][MAX_GOP].m_numInterViewRefPics; j++ )
1447              {
1448                if( m_GOPListMvc[k][MAX_GOP].m_interViewRefPosL[1][j] != -1 )
1449                {
1450                  printf( "\nError: inter-layer ref pos %d on L1 not possible for FrameI_l%d with slice type P\n", m_GOPListMvc[k][MAX_GOP].m_interViewRefPosL[1][j], k );
1451                  bErrorIvpEnhV = true;
1452                }
1453              }
1454            }
1455          }
1456
1457          if( m_GOPListMvc[k][MAX_GOP].m_sliceType == 'B' && m_GOPListMvc[k][MAX_GOP].m_numInterViewRefPics < 1 )
1458          {
1459            printf( "\nError: #IL_ref_pics must be at least one for FrameI_l%d with slice type B\n", k );
1460            bErrorIvpEnhV = true;
1461          }
1462        }
1463      }
1464    }
1465  }
1466  xConfirmPara( bErrorIvpEnhV, "Invalid inter-layer coding structure for enhancement layers given" );
1467
1468  // validate temporal coding structure
1469  if( !bErrorMvePoc && !bErrorIvpBase && !bErrorIvpEnhV )
1470  {
1471    for( Int layer = 0; layer < m_numberOfLayers; layer++ )
1472    {
1473      GOPEntry* m_GOPList            = m_GOPListMvc           [layer]; // It is not a member, but this name helps avoiding code duplication !!!
1474      Int&      m_extraRPSs          = m_extraRPSsMvc         [layer]; // It is not a member, but this name helps avoiding code duplication !!!
1475      Int&      m_maxTempLayer       = m_maxTempLayerMvc      [layer]; // It is not a member, but this name helps avoiding code duplication !!!
1476      Int*      m_maxDecPicBuffering = m_maxDecPicBufferingMvc[layer]; // It is not a member, but this name helps avoiding code duplication !!!
1477      Int*      m_numReorderPics     = m_numReorderPicsMvc    [layer]; // It is not a member, but this name helps avoiding code duplication !!!
1478#endif
1479
1480  /* if this is an intra-only sequence, ie IntraPeriod=1, don't verify the GOP structure
1481   * This permits the ability to omit a GOP structure specification */
1482  if (m_iIntraPeriod == 1 && m_GOPList[0].m_POC == -1) {
1483    m_GOPList[0] = GOPEntry();
1484    m_GOPList[0].m_QPFactor = 1;
1485    m_GOPList[0].m_betaOffsetDiv2 = 0;
1486    m_GOPList[0].m_tcOffsetDiv2 = 0;
1487    m_GOPList[0].m_POC = 1;
1488    m_GOPList[0].m_numRefPicsActive = 4;
1489  }
1490 
1491  Bool verifiedGOP=false;
1492  Bool errorGOP=false;
1493  Int checkGOP=1;
1494  Int numRefs = 1;
1495  Int refList[MAX_NUM_REF_PICS+1];
1496  refList[0]=0;
1497  Bool isOK[MAX_GOP];
1498  for(Int i=0; i<MAX_GOP; i++) 
1499  {
1500    isOK[i]=false;
1501  }
1502  Int numOK=0;
1503  xConfirmPara( m_iIntraPeriod >=0&&(m_iIntraPeriod%m_iGOPSize!=0), "Intra period must be a multiple of GOPSize, or -1" );
1504
1505  for(Int i=0; i<m_iGOPSize; i++)
1506  {
1507    if(m_GOPList[i].m_POC==m_iGOPSize)
1508    {
1509      xConfirmPara( m_GOPList[i].m_temporalId!=0 , "The last frame in each GOP must have temporal ID = 0 " );
1510    }
1511  }
1512 
1513#if H_MV
1514  if ( (m_iIntraPeriod != 1) && !m_loopFilterOffsetInPPS && m_DeblockingFilterControlPresent && (!m_bLoopFilterDisable[layer]) )
1515#else
1516  if ( (m_iIntraPeriod != 1) && !m_loopFilterOffsetInPPS && m_DeblockingFilterControlPresent && (!m_bLoopFilterDisable) )
1517#endif
1518  {
1519    for(Int i=0; i<m_iGOPSize; i++)
1520    {
1521      xConfirmPara( (m_GOPList[i].m_betaOffsetDiv2 + m_loopFilterBetaOffsetDiv2) < -6 || (m_GOPList[i].m_betaOffsetDiv2 + m_loopFilterBetaOffsetDiv2) > 6, "Loop Filter Beta Offset div. 2 for one of the GOP entries exceeds supported range (-6 to 6)" );
1522      xConfirmPara( (m_GOPList[i].m_tcOffsetDiv2 + m_loopFilterTcOffsetDiv2) < -6 || (m_GOPList[i].m_tcOffsetDiv2 + m_loopFilterTcOffsetDiv2) > 6, "Loop Filter Tc Offset div. 2 for one of the GOP entries exceeds supported range (-6 to 6)" );
1523    }
1524  }
1525  m_extraRPSs=0;
1526  //start looping through frames in coding order until we can verify that the GOP structure is correct.
1527  while(!verifiedGOP&&!errorGOP) 
1528  {
1529    Int curGOP = (checkGOP-1)%m_iGOPSize;
1530    Int curPOC = ((checkGOP-1)/m_iGOPSize)*m_iGOPSize + m_GOPList[curGOP].m_POC;   
1531    if(m_GOPList[curGOP].m_POC<0) 
1532    {
1533#if H_MV
1534      printf("\nError: found fewer Reference Picture Sets than GOPSize for layer %d\n", layer );
1535#else
1536      printf("\nError: found fewer Reference Picture Sets than GOPSize\n");
1537#endif
1538      errorGOP=true;
1539    }
1540    else 
1541    {
1542      //check that all reference pictures are available, or have a POC < 0 meaning they might be available in the next GOP.
1543      Bool beforeI = false;
1544      for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++) 
1545      {
1546        Int absPOC = curPOC+m_GOPList[curGOP].m_referencePics[i];
1547        if(absPOC < 0)
1548        {
1549          beforeI=true;
1550        }
1551        else 
1552        {
1553          Bool found=false;
1554          for(Int j=0; j<numRefs; j++) 
1555          {
1556            if(refList[j]==absPOC) 
1557            {
1558              found=true;
1559              for(Int k=0; k<m_iGOPSize; k++)
1560              {
1561                if(absPOC%m_iGOPSize == m_GOPList[k].m_POC%m_iGOPSize)
1562                {
1563                  if(m_GOPList[k].m_temporalId==m_GOPList[curGOP].m_temporalId)
1564                  {
1565                    m_GOPList[k].m_refPic = true;
1566                  }
1567                  m_GOPList[curGOP].m_usedByCurrPic[i]=m_GOPList[k].m_temporalId<=m_GOPList[curGOP].m_temporalId;
1568                }
1569              }
1570            }
1571          }
1572          if(!found)
1573          {
1574#if H_MV
1575            printf("\nError: ref pic %d is not available for GOP frame %d of layer %d\n", m_GOPList[curGOP].m_referencePics[i], curGOP+1, layer);
1576#else
1577            printf("\nError: ref pic %d is not available for GOP frame %d\n",m_GOPList[curGOP].m_referencePics[i],curGOP+1);
1578#endif
1579            errorGOP=true;
1580          }
1581        }
1582      }
1583      if(!beforeI&&!errorGOP)
1584      {
1585        //all ref frames were present
1586        if(!isOK[curGOP]) 
1587        {
1588          numOK++;
1589          isOK[curGOP]=true;
1590          if(numOK==m_iGOPSize)
1591          {
1592            verifiedGOP=true;
1593          }
1594        }
1595      }
1596      else 
1597      {
1598        //create a new GOPEntry for this frame containing all the reference pictures that were available (POC > 0)
1599        m_GOPList[m_iGOPSize+m_extraRPSs]=m_GOPList[curGOP];
1600        Int newRefs=0;
1601        for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++) 
1602        {
1603          Int absPOC = curPOC+m_GOPList[curGOP].m_referencePics[i];
1604          if(absPOC>=0)
1605          {
1606            m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[newRefs]=m_GOPList[curGOP].m_referencePics[i];
1607            m_GOPList[m_iGOPSize+m_extraRPSs].m_usedByCurrPic[newRefs]=m_GOPList[curGOP].m_usedByCurrPic[i];
1608            newRefs++;
1609          }
1610        }
1611        Int numPrefRefs = m_GOPList[curGOP].m_numRefPicsActive;
1612       
1613        for(Int offset = -1; offset>-checkGOP; offset--)
1614        {
1615          //step backwards in coding order and include any extra available pictures we might find useful to replace the ones with POC < 0.
1616          Int offGOP = (checkGOP-1+offset)%m_iGOPSize;
1617          Int offPOC = ((checkGOP-1+offset)/m_iGOPSize)*m_iGOPSize + m_GOPList[offGOP].m_POC;
1618          if(offPOC>=0&&m_GOPList[offGOP].m_temporalId<=m_GOPList[curGOP].m_temporalId)
1619          {
1620            Bool newRef=false;
1621            for(Int i=0; i<numRefs; i++)
1622            {
1623              if(refList[i]==offPOC)
1624              {
1625                newRef=true;
1626              }
1627            }
1628            for(Int i=0; i<newRefs; i++) 
1629            {
1630              if(m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[i]==offPOC-curPOC)
1631              {
1632                newRef=false;
1633              }
1634            }
1635            if(newRef) 
1636            {
1637              Int insertPoint=newRefs;
1638              //this picture can be added, find appropriate place in list and insert it.
1639              if(m_GOPList[offGOP].m_temporalId==m_GOPList[curGOP].m_temporalId)
1640              {
1641                m_GOPList[offGOP].m_refPic = true;
1642              }
1643              for(Int j=0; j<newRefs; j++)
1644              {
1645                if(m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j]<offPOC-curPOC||m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j]>0)
1646                {
1647                  insertPoint = j;
1648                  break;
1649                }
1650              }
1651              Int prev = offPOC-curPOC;
1652              Int prevUsed = m_GOPList[offGOP].m_temporalId<=m_GOPList[curGOP].m_temporalId;
1653              for(Int j=insertPoint; j<newRefs+1; j++)
1654              {
1655                Int newPrev = m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j];
1656                Int newUsed = m_GOPList[m_iGOPSize+m_extraRPSs].m_usedByCurrPic[j];
1657                m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j]=prev;
1658                m_GOPList[m_iGOPSize+m_extraRPSs].m_usedByCurrPic[j]=prevUsed;
1659                prevUsed=newUsed;
1660                prev=newPrev;
1661              }
1662              newRefs++;
1663            }
1664          }
1665          if(newRefs>=numPrefRefs)
1666          {
1667            break;
1668          }
1669        }
1670        m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefPics=newRefs;
1671        m_GOPList[m_iGOPSize+m_extraRPSs].m_POC = curPOC;
1672        if (m_extraRPSs == 0)
1673        {
1674          m_GOPList[m_iGOPSize+m_extraRPSs].m_interRPSPrediction = 0;
1675          m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefIdc = 0;
1676        }
1677        else
1678        {
1679          Int rIdx =  m_iGOPSize + m_extraRPSs - 1;
1680          Int refPOC = m_GOPList[rIdx].m_POC;
1681          Int refPics = m_GOPList[rIdx].m_numRefPics;
1682          Int newIdc=0;
1683          for(Int i = 0; i<= refPics; i++) 
1684          {
1685            Int deltaPOC = ((i != refPics)? m_GOPList[rIdx].m_referencePics[i] : 0);  // check if the reference abs POC is >= 0
1686            Int absPOCref = refPOC+deltaPOC;
1687            Int refIdc = 0;
1688            for (Int j = 0; j < m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefPics; j++)
1689            {
1690              if ( (absPOCref - curPOC) == m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j])
1691              {
1692                if (m_GOPList[m_iGOPSize+m_extraRPSs].m_usedByCurrPic[j])
1693                {
1694                  refIdc = 1;
1695                }
1696                else
1697                {
1698                  refIdc = 2;
1699                }
1700              }
1701            }
1702            m_GOPList[m_iGOPSize+m_extraRPSs].m_refIdc[newIdc]=refIdc;
1703            newIdc++;
1704          }
1705          m_GOPList[m_iGOPSize+m_extraRPSs].m_interRPSPrediction = 1; 
1706          m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefIdc = newIdc;
1707          m_GOPList[m_iGOPSize+m_extraRPSs].m_deltaRPS = refPOC - m_GOPList[m_iGOPSize+m_extraRPSs].m_POC; 
1708        }
1709        curGOP=m_iGOPSize+m_extraRPSs;
1710        m_extraRPSs++;
1711      }
1712      numRefs=0;
1713      for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++) 
1714      {
1715        Int absPOC = curPOC+m_GOPList[curGOP].m_referencePics[i];
1716        if(absPOC >= 0) 
1717        {
1718          refList[numRefs]=absPOC;
1719          numRefs++;
1720        }
1721      }
1722      refList[numRefs]=curPOC;
1723      numRefs++;
1724    }
1725    checkGOP++;
1726  }
1727  xConfirmPara(errorGOP,"Invalid GOP structure given");
1728  m_maxTempLayer = 1;
1729  for(Int i=0; i<m_iGOPSize; i++) 
1730  {
1731    if(m_GOPList[i].m_temporalId >= m_maxTempLayer)
1732    {
1733      m_maxTempLayer = m_GOPList[i].m_temporalId+1;
1734    }
1735    xConfirmPara(m_GOPList[i].m_sliceType!='B'&&m_GOPList[i].m_sliceType!='P', "Slice type must be equal to B or P");
1736  }
1737  for(Int i=0; i<MAX_TLAYER; i++)
1738  {
1739    m_numReorderPics[i] = 0;
1740#if L0323_DPB
1741    m_maxDecPicBuffering[i] = 1;
1742#else
1743    m_maxDecPicBuffering[i] = 0;
1744#endif
1745  }
1746  for(Int i=0; i<m_iGOPSize; i++) 
1747  {
1748#if L0323_DPB
1749    if(m_GOPList[i].m_numRefPics+1 > m_maxDecPicBuffering[m_GOPList[i].m_temporalId])
1750#else
1751    if(m_GOPList[i].m_numRefPics > m_maxDecPicBuffering[m_GOPList[i].m_temporalId])
1752#endif
1753    {
1754#if L0323_DPB
1755      m_maxDecPicBuffering[m_GOPList[i].m_temporalId] = m_GOPList[i].m_numRefPics + 1;
1756#else
1757      m_maxDecPicBuffering[m_GOPList[i].m_temporalId] = m_GOPList[i].m_numRefPics;
1758#endif
1759    }
1760    Int highestDecodingNumberWithLowerPOC = 0; 
1761    for(Int j=0; j<m_iGOPSize; j++)
1762    {
1763      if(m_GOPList[j].m_POC <= m_GOPList[i].m_POC)
1764      {
1765        highestDecodingNumberWithLowerPOC = j;
1766      }
1767    }
1768    Int numReorder = 0;
1769    for(Int j=0; j<highestDecodingNumberWithLowerPOC; j++)
1770    {
1771      if(m_GOPList[j].m_temporalId <= m_GOPList[i].m_temporalId && 
1772        m_GOPList[j].m_POC > m_GOPList[i].m_POC)
1773      {
1774        numReorder++;
1775      }
1776    }   
1777    if(numReorder > m_numReorderPics[m_GOPList[i].m_temporalId])
1778    {
1779      m_numReorderPics[m_GOPList[i].m_temporalId] = numReorder;
1780    }
1781  }
1782  for(Int i=0; i<MAX_TLAYER-1; i++) 
1783  {
1784    // a lower layer can not have higher value of m_numReorderPics than a higher layer
1785    if(m_numReorderPics[i+1] < m_numReorderPics[i])
1786    {
1787      m_numReorderPics[i+1] = m_numReorderPics[i];
1788    }
1789#if L0323_DPB
1790    // the value of num_reorder_pics[ i ] shall be in the range of 0 to max_dec_pic_buffering[ i ] - 1, inclusive
1791    if(m_numReorderPics[i] > m_maxDecPicBuffering[i] - 1)
1792    {
1793      m_maxDecPicBuffering[i] = m_numReorderPics[i] + 1;
1794    }
1795#else
1796    // the value of num_reorder_pics[ i ] shall be in the range of 0 to max_dec_pic_buffering[ i ], inclusive
1797    if(m_numReorderPics[i] > m_maxDecPicBuffering[i])
1798    {
1799      m_maxDecPicBuffering[i] = m_numReorderPics[i];
1800    }
1801#endif
1802    // a lower layer can not have higher value of m_uiMaxDecPicBuffering than a higher layer
1803    if(m_maxDecPicBuffering[i+1] < m_maxDecPicBuffering[i])
1804    {
1805      m_maxDecPicBuffering[i+1] = m_maxDecPicBuffering[i];
1806    }
1807  }
1808
1809
1810#if L0323_DPB
1811  // the value of num_reorder_pics[ i ] shall be in the range of 0 to max_dec_pic_buffering[ i ] -  1, inclusive
1812  if(m_numReorderPics[MAX_TLAYER-1] > m_maxDecPicBuffering[MAX_TLAYER-1] - 1)
1813  {
1814    m_maxDecPicBuffering[MAX_TLAYER-1] = m_numReorderPics[MAX_TLAYER-1] + 1;
1815  }
1816#else
1817  // the value of num_reorder_pics[ i ] shall be in the range of 0 to max_dec_pic_buffering[ i ], inclusive
1818  if(m_numReorderPics[MAX_TLAYER-1] > m_maxDecPicBuffering[MAX_TLAYER-1])
1819  {
1820    m_maxDecPicBuffering[MAX_TLAYER-1] = m_numReorderPics[MAX_TLAYER-1];
1821  }
1822#endif
1823
1824  if(m_vuiParametersPresentFlag && m_bitstreamRestrictionFlag)
1825  { 
1826    Int PicSizeInSamplesY =  m_iSourceWidth * m_iSourceHeight;
1827    if(tileFlag)
1828    {
1829      Int maxTileWidth = 0;
1830      Int maxTileHeight = 0;
1831      Int widthInCU = (m_iSourceWidth % m_uiMaxCUWidth) ? m_iSourceWidth/m_uiMaxCUWidth + 1: m_iSourceWidth/m_uiMaxCUWidth;
1832      Int heightInCU = (m_iSourceHeight % m_uiMaxCUHeight) ? m_iSourceHeight/m_uiMaxCUHeight + 1: m_iSourceHeight/m_uiMaxCUHeight;
1833      if(m_iUniformSpacingIdr)
1834      {
1835        maxTileWidth = m_uiMaxCUWidth*((widthInCU+m_iNumColumnsMinus1)/(m_iNumColumnsMinus1+1));
1836        maxTileHeight = m_uiMaxCUHeight*((heightInCU+m_iNumRowsMinus1)/(m_iNumRowsMinus1+1));
1837        // if only the last tile-row is one treeblock higher than the others
1838        // the maxTileHeight becomes smaller if the last row of treeblocks has lower height than the others
1839        if(!((heightInCU-1)%(m_iNumRowsMinus1+1)))
1840        {
1841          maxTileHeight = maxTileHeight - m_uiMaxCUHeight + (m_iSourceHeight % m_uiMaxCUHeight);
1842        }     
1843        // if only the last tile-column is one treeblock wider than the others
1844        // the maxTileWidth becomes smaller if the last column of treeblocks has lower width than the others   
1845        if(!((widthInCU-1)%(m_iNumColumnsMinus1+1)))
1846        {
1847          maxTileWidth = maxTileWidth - m_uiMaxCUWidth + (m_iSourceWidth % m_uiMaxCUWidth);
1848        }
1849      }
1850      else // not uniform spacing
1851      {
1852        if(m_iNumColumnsMinus1<1)
1853        {
1854          maxTileWidth = m_iSourceWidth;
1855        }
1856        else
1857        {
1858          Int accColumnWidth = 0;
1859          for(Int col=0; col<(m_iNumColumnsMinus1); col++)
1860          {
1861            maxTileWidth = m_pColumnWidth[col]>maxTileWidth ? m_pColumnWidth[col]:maxTileWidth;
1862            accColumnWidth += m_pColumnWidth[col];
1863          }
1864          maxTileWidth = (widthInCU-accColumnWidth)>maxTileWidth ? m_uiMaxCUWidth*(widthInCU-accColumnWidth):m_uiMaxCUWidth*maxTileWidth;
1865        }
1866        if(m_iNumRowsMinus1<1)
1867        {
1868          maxTileHeight = m_iSourceHeight;
1869        }
1870        else
1871        {
1872          Int accRowHeight = 0;
1873          for(Int row=0; row<(m_iNumRowsMinus1); row++)
1874          {
1875            maxTileHeight = m_pRowHeight[row]>maxTileHeight ? m_pRowHeight[row]:maxTileHeight;
1876            accRowHeight += m_pRowHeight[row];
1877          }
1878          maxTileHeight = (heightInCU-accRowHeight)>maxTileHeight ? m_uiMaxCUHeight*(heightInCU-accRowHeight):m_uiMaxCUHeight*maxTileHeight;
1879        }
1880      }
1881      Int maxSizeInSamplesY = maxTileWidth*maxTileHeight;
1882      m_minSpatialSegmentationIdc = 4*PicSizeInSamplesY/maxSizeInSamplesY-4;
1883    }
1884    else if(m_iWaveFrontSynchro)
1885    {
1886      m_minSpatialSegmentationIdc = 4*PicSizeInSamplesY/((2*m_iSourceHeight+m_iSourceWidth)*m_uiMaxCUHeight)-4;
1887    }
1888    else if(m_sliceMode == 1)
1889    {
1890      m_minSpatialSegmentationIdc = 4*PicSizeInSamplesY/(m_sliceArgument*m_uiMaxCUWidth*m_uiMaxCUHeight)-4;
1891    }
1892    else
1893    {
1894      m_minSpatialSegmentationIdc = 0;
1895    }
1896  }
1897#if !L0034_COMBINED_LIST_CLEANUP
1898  xConfirmPara( m_bUseLComb==false && m_numReorderPics[MAX_TLAYER-1]!=0, "ListCombination can only be 0 in low delay coding (more precisely when L0 and L1 are identical)" );  // Note however this is not the full necessary condition as ref_pic_list_combination_flag can only be 0 if L0 == L1.
1899#endif
1900  xConfirmPara( m_iWaveFrontSynchro < 0, "WaveFrontSynchro cannot be negative" );
1901  xConfirmPara( m_iWaveFrontSubstreams <= 0, "WaveFrontSubstreams must be positive" );
1902  xConfirmPara( m_iWaveFrontSubstreams > 1 && !m_iWaveFrontSynchro, "Must have WaveFrontSynchro > 0 in order to have WaveFrontSubstreams > 1" );
1903
1904  xConfirmPara( m_decodedPictureHashSEIEnabled<0 || m_decodedPictureHashSEIEnabled>3, "this hash type is not correct!\n");
1905
1906#if J0149_TONE_MAPPING_SEI
1907  if (m_toneMappingInfoSEIEnabled)
1908  {
1909    xConfirmPara( m_toneMapCodedDataBitDepth < 8 || m_toneMapCodedDataBitDepth > 14 , "SEIToneMapCodedDataBitDepth must be in rage 8 to 14");
1910    xConfirmPara( m_toneMapTargetBitDepth < 1 || (m_toneMapTargetBitDepth > 16 && m_toneMapTargetBitDepth < 255) , "SEIToneMapTargetBitDepth must be in rage 1 to 16 or equal to 255");
1911    xConfirmPara( m_toneMapModelId < 0 || m_toneMapModelId > 4 , "SEIToneMapModelId must be in rage 0 to 4");
1912    xConfirmPara( m_cameraIsoSpeedValue == 0, "SEIToneMapCameraIsoSpeedValue shall not be equal to 0");
1913    xConfirmPara( m_extendedRangeWhiteLevel < 100, "SEIToneMapExtendedRangeWhiteLevel should be greater than or equal to 100");
1914    xConfirmPara( m_nominalBlackLevelLumaCodeValue >= m_nominalWhiteLevelLumaCodeValue, "SEIToneMapNominalWhiteLevelLumaCodeValue shall be greater than SEIToneMapNominalBlackLevelLumaCodeValue");
1915    xConfirmPara( m_extendedWhiteLevelLumaCodeValue < m_nominalWhiteLevelLumaCodeValue, "SEIToneMapExtendedWhiteLevelLumaCodeValue shall be greater than or equal to SEIToneMapNominalWhiteLevelLumaCodeValue");
1916  }
1917#endif
1918
1919#if RATE_CONTROL_LAMBDA_DOMAIN
1920  if ( m_RCEnableRateControl )
1921  {
1922    if ( m_RCForceIntraQP )
1923    {
1924      if ( m_RCInitialQP == 0 )
1925      {
1926        printf( "\nInitial QP for rate control is not specified. Reset not to use force intra QP!" );
1927        m_RCForceIntraQP = false;
1928      }
1929    }
1930    xConfirmPara( m_uiDeltaQpRD > 0, "Rate control cannot be used together with slice level multiple-QP optimization!\n" );
1931  }
1932#else
1933  if(m_enableRateCtrl)
1934  {
1935    Int numLCUInWidth  = (m_iSourceWidth  / m_uiMaxCUWidth) + (( m_iSourceWidth  %  m_uiMaxCUWidth ) ? 1 : 0);
1936    Int numLCUInHeight = (m_iSourceHeight / m_uiMaxCUHeight)+ (( m_iSourceHeight %  m_uiMaxCUHeight) ? 1 : 0);
1937    Int numLCUInPic    =  numLCUInWidth * numLCUInHeight;
1938
1939    xConfirmPara( (numLCUInPic % m_numLCUInUnit) != 0, "total number of LCUs in a frame should be completely divided by NumLCUInUnit" );
1940
1941    m_iMaxDeltaQP       = MAX_DELTA_QP;
1942    m_iMaxCuDQPDepth    = MAX_CUDQP_DEPTH;
1943  }
1944#endif
1945
1946  xConfirmPara(!m_TransquantBypassEnableFlag && m_CUTransquantBypassFlagValue, "CUTransquantBypassFlagValue cannot be 1 when TransquantBypassEnableFlag is 0");
1947
1948  xConfirmPara(m_log2ParallelMergeLevel < 2, "Log2ParallelMergeLevel should be larger than or equal to 2");
1949#if L0444_FPA_TYPE
1950  if (m_framePackingSEIEnabled)
1951  {
1952    xConfirmPara(m_framePackingSEIType < 3 || m_framePackingSEIType > 5 , "SEIFramePackingType must be in rage 3 to 5");
1953  }
1954#endif
1955
1956#if H_MV
1957  }
1958  }
1959#endif
1960
1961#undef xConfirmPara
1962  if (check_failed)
1963  {
1964    exit(EXIT_FAILURE);
1965  }
1966}
1967
1968/** \todo use of global variables should be removed later
1969 */
1970Void TAppEncCfg::xSetGlobal()
1971{
1972  // set max CU width & height
1973  g_uiMaxCUWidth  = m_uiMaxCUWidth;
1974  g_uiMaxCUHeight = m_uiMaxCUHeight;
1975 
1976  // compute actual CU depth with respect to config depth and max transform size
1977  g_uiAddCUDepth  = 0;
1978  while( (m_uiMaxCUWidth>>m_uiMaxCUDepth) > ( 1 << ( m_uiQuadtreeTULog2MinSize + g_uiAddCUDepth )  ) ) g_uiAddCUDepth++;
1979 
1980  m_uiMaxCUDepth += g_uiAddCUDepth;
1981  g_uiAddCUDepth++;
1982  g_uiMaxCUDepth = m_uiMaxCUDepth;
1983 
1984  // set internal bit-depth and constants
1985  g_bitDepthY = m_internalBitDepthY;
1986  g_bitDepthC = m_internalBitDepthC;
1987 
1988  g_uiPCMBitDepthLuma = m_bPCMInputBitDepthFlag ? m_inputBitDepthY : m_internalBitDepthY;
1989  g_uiPCMBitDepthChroma = m_bPCMInputBitDepthFlag ? m_inputBitDepthC : m_internalBitDepthC;
1990}
1991
1992Void TAppEncCfg::xPrintParameter()
1993{
1994  printf("\n");
1995#if H_MV
1996  for( Int layer = 0; layer < m_numberOfLayers; layer++)
1997  {
1998    printf("Input File %i                 : %s\n", layer, m_pchInputFileList[layer]);
1999  }
2000#else
2001  printf("Input          File          : %s\n", m_pchInputFile          );
2002#endif
2003
2004  printf("Bitstream      File          : %s\n", m_pchBitstreamFile      );
2005
2006#if H_MV
2007  for( Int layer = 0; layer < m_numberOfLayers; layer++)
2008  {
2009    printf("Reconstruction File %i        : %s\n", layer, m_pchReconFileList[layer]);
2010  }
2011#else
2012  printf("Reconstruction File          : %s\n", m_pchReconFile          );
2013#endif
2014
2015#if H_MV
2016 xPrintParaVector( "ViewId", m_viewId ); 
2017#endif
2018
2019#if H_3D
2020 xPrintParaVector( "DepthFlag", m_depthFlag ); 
2021#endif
2022
2023#if H_MV 
2024  xPrintParaVector( "QP"               , m_fQP                ); 
2025  xPrintParaVector( "LoopFilterDisable", m_bLoopFilterDisable ); 
2026  xPrintParaVector( "SAO"              , m_bUseSAO            ); 
2027#endif
2028  printf("Real     Format              : %dx%d %dHz\n", m_iSourceWidth - m_confLeft - m_confRight, m_iSourceHeight - m_confTop - m_confBottom, m_iFrameRate );
2029  printf("Internal Format              : %dx%d %dHz\n", m_iSourceWidth, m_iSourceHeight, m_iFrameRate );
2030  printf("Frame index                  : %u - %d (%d frames)\n", m_FrameSkip, m_FrameSkip+m_framesToBeEncoded-1, m_framesToBeEncoded );
2031  printf("CU size / depth              : %d / %d\n", m_uiMaxCUWidth, m_uiMaxCUDepth );
2032  printf("RQT trans. size (min / max)  : %d / %d\n", 1 << m_uiQuadtreeTULog2MinSize, 1 << m_uiQuadtreeTULog2MaxSize );
2033  printf("Max RQT depth inter          : %d\n", m_uiQuadtreeTUMaxDepthInter);
2034  printf("Max RQT depth intra          : %d\n", m_uiQuadtreeTUMaxDepthIntra);
2035  printf("Min PCM size                 : %d\n", 1 << m_uiPCMLog2MinSize);
2036  printf("Motion search range          : %d\n", m_iSearchRange );
2037  printf("Intra period                 : %d\n", m_iIntraPeriod );
2038  printf("Decoding refresh type        : %d\n", m_iDecodingRefreshType );
2039#if !H_MV
2040  printf("QP                           : %5.2f\n", m_fQP );
2041#endif
2042  printf("Max dQP signaling depth      : %d\n", m_iMaxCuDQPDepth);
2043
2044  printf("Cb QP Offset                 : %d\n", m_cbQpOffset   );
2045  printf("Cr QP Offset                 : %d\n", m_crQpOffset);
2046
2047  printf("QP adaptation                : %d (range=%d)\n", m_bUseAdaptiveQP, (m_bUseAdaptiveQP ? m_iQPAdaptationRange : 0) );
2048  printf("GOP size                     : %d\n", m_iGOPSize );
2049  printf("Internal bit depth           : (Y:%d, C:%d)\n", m_internalBitDepthY, m_internalBitDepthC );
2050  printf("PCM sample bit depth         : (Y:%d, C:%d)\n", g_uiPCMBitDepthLuma, g_uiPCMBitDepthChroma );
2051#if RATE_CONTROL_LAMBDA_DOMAIN
2052  printf("RateControl                  : %d\n", m_RCEnableRateControl );
2053  if(m_RCEnableRateControl)
2054  {
2055    printf("TargetBitrate                : %d\n", m_RCTargetBitrate );
2056    printf("KeepHierarchicalBit          : %d\n", m_RCKeepHierarchicalBit );
2057    printf("LCULevelRC                   : %d\n", m_RCLCULevelRC );
2058    printf("UseLCUSeparateModel          : %d\n", m_RCUseLCUSeparateModel );
2059    printf("InitialQP                    : %d\n", m_RCInitialQP );
2060    printf("ForceIntraQP                 : %d\n", m_RCForceIntraQP );
2061  }
2062#else
2063  printf("RateControl                  : %d\n", m_enableRateCtrl);
2064  if(m_enableRateCtrl)
2065  {
2066    printf("TargetBitrate                : %d\n", m_targetBitrate);
2067    printf("NumLCUInUnit                 : %d\n", m_numLCUInUnit);
2068  }
2069#endif
2070  printf("Max Num Merge Candidates     : %d\n", m_maxNumMergeCand);
2071  printf("\n");
2072 
2073  printf("TOOL CFG: ");
2074  printf("IBD:%d ", g_bitDepthY > m_inputBitDepthY || g_bitDepthC > m_inputBitDepthC);
2075  printf("HAD:%d ", m_bUseHADME           );
2076  printf("SRD:%d ", m_bUseSBACRD          );
2077  printf("RDQ:%d ", m_useRDOQ            );
2078  printf("RDQTS:%d ", m_useRDOQTS        );
2079#if L0232_RD_PENALTY
2080  printf("RDpenalty:%d ", m_rdPenalty  );
2081#endif
2082  printf("SQP:%d ", m_uiDeltaQpRD         );
2083  printf("ASR:%d ", m_bUseASR             );
2084#if !L0034_COMBINED_LIST_CLEANUP
2085  printf("LComb:%d ", m_bUseLComb         );
2086#endif
2087  printf("FEN:%d ", m_bUseFastEnc         );
2088  printf("ECU:%d ", m_bUseEarlyCU         );
2089  printf("FDM:%d ", m_useFastDecisionForMerge );
2090  printf("CFM:%d ", m_bUseCbfFastMode         );
2091  printf("ESD:%d ", m_useEarlySkipDetection  );
2092  printf("RQT:%d ", 1     );
2093  printf("TransformSkip:%d ",     m_useTransformSkip              );
2094  printf("TransformSkipFast:%d ", m_useTransformSkipFast       );
2095  printf("Slice: M=%d ", m_sliceMode);
2096  if (m_sliceMode!=0)
2097  {
2098    printf("A=%d ", m_sliceArgument);
2099  }
2100  printf("SliceSegment: M=%d ",m_sliceSegmentMode);
2101  if (m_sliceSegmentMode!=0)
2102  {
2103    printf("A=%d ", m_sliceSegmentArgument);
2104  }
2105  printf("CIP:%d ", m_bUseConstrainedIntraPred);
2106#if !H_MV
2107  printf("SAO:%d ", (m_bUseSAO)?(1):(0));
2108#endif
2109  printf("PCM:%d ", (m_usePCM && (1<<m_uiPCMLog2MinSize) <= m_uiMaxCUWidth)? 1 : 0);
2110  printf("SAOLcuBasedOptimization:%d ", (m_saoLcuBasedOptimization)?(1):(0));
2111
2112  printf("LosslessCuEnabled:%d ", (m_useLossless)? 1:0 );
2113  printf("WPP:%d ", (Int)m_useWeightedPred);
2114  printf("WPB:%d ", (Int)m_useWeightedBiPred);
2115  printf("PME:%d ", m_log2ParallelMergeLevel);
2116  printf(" WaveFrontSynchro:%d WaveFrontSubstreams:%d",
2117          m_iWaveFrontSynchro, m_iWaveFrontSubstreams);
2118  printf(" ScalingList:%d ", m_useScalingListId );
2119  printf("TMVPMode:%d ", m_TMVPModeId     );
2120#if ADAPTIVE_QP_SELECTION
2121  printf("AQpS:%d", m_bUseAdaptQpSelect   );
2122#endif
2123
2124  printf(" SignBitHidingFlag:%d ", m_signHideFlag);
2125  printf("RecalQP:%d", m_recalculateQPAccordingToLambda ? 1 : 0 );
2126  printf("\n\n");
2127 
2128  fflush(stdout);
2129}
2130
2131Bool confirmPara(Bool bflag, const Char* message)
2132{
2133  if (!bflag)
2134    return false;
2135 
2136  printf("Error: %s\n",message);
2137  return true;
2138}
2139
2140//! \}
Note: See TracBrowser for help on using the repository browser.