source: 3DVCSoftware/branches/HTM-15.1-MV-draft-4/source/App/TAppEncoder/TAppEncCfg.cpp @ 1325

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

Removed 3D-HEVC.

  • Property svn:eol-style set to native
File size: 186.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-2015, ITU/ISO/IEC
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
11 *
12 *  * Redistributions of source code must retain the above copyright notice,
13 *    this list of conditions and the following disclaimer.
14 *  * Redistributions in binary form must reproduce the above copyright notice,
15 *    this list of conditions and the following disclaimer in the documentation
16 *    and/or other materials provided with the distribution.
17 *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
18 *    be used to endorse or promote products derived from this software without
19 *    specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
31 * THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34/** \file     TAppEncCfg.cpp
35    \brief    Handle encoder configuration parameters
36*/
37
38#include <stdio.h>
39#include <stdlib.h>
40#include <cassert>
41#include <cstring>
42#include <string>
43#include <limits>
44#include "TLibCommon/TComRom.h"
45#include "TAppEncCfg.h"
46#include "TAppCommon/program_options_lite.h"
47#include "TLibEncoder/TEncRateCtrl.h"
48#ifdef WIN32
49#define strdup _strdup
50#endif
51
52#define MACRO_TO_STRING_HELPER(val) #val
53#define MACRO_TO_STRING(val) MACRO_TO_STRING_HELPER(val)
54
55using namespace std;
56namespace po = df::program_options_lite;
57
58
59
60enum ExtendedProfileName // this is used for determining profile strings, where multiple profiles map to a single profile idc with various constraint flag combinations
61{
62  NONE = 0,
63  MAIN = 1,
64  MAIN10 = 2,
65  MAINSTILLPICTURE = 3,
66  MAINREXT = 4,
67  HIGHTHROUGHPUTREXT = 5, // Placeholder profile for development
68  // The following are RExt profiles, which would map to the MAINREXT profile idc.
69  // The enumeration indicates the bit-depth constraint in the bottom 2 digits
70  //                           the chroma format in the next digit
71    //                           the intra constraint in the next digit
72//                           If it is a RExt still picture, there is a '1' for the top digit.
73#if NH_MV
74  MULTIVIEWMAIN = 6,
75#endif
76  MONOCHROME_8      = 1008,
77  MONOCHROME_12     = 1012,
78  MONOCHROME_16     = 1016,
79  MAIN_12           = 1112,
80  MAIN_422_10       = 1210,
81  MAIN_422_12       = 1212,
82  MAIN_444          = 1308,
83  MAIN_444_10       = 1310,
84  MAIN_444_12       = 1312,
85  MAIN_444_16       = 1316, // non-standard profile definition, used for development purposes
86  MAIN_INTRA        = 2108,
87  MAIN_10_INTRA     = 2110,
88  MAIN_12_INTRA     = 2112,
89  MAIN_422_10_INTRA = 2210,
90  MAIN_422_12_INTRA = 2212,
91  MAIN_444_INTRA    = 2308,
92  MAIN_444_10_INTRA = 2310,
93  MAIN_444_12_INTRA = 2312,
94  MAIN_444_16_INTRA = 2316,
95  MAIN_444_STILL_PICTURE = 11308,
96  MAIN_444_16_STILL_PICTURE = 12316
97};
98
99
100//! \ingroup TAppEncoder
101//! \{
102
103// ====================================================================================================================
104// Constructor / destructor / initialization / destroy
105// ====================================================================================================================
106
107TAppEncCfg::TAppEncCfg()
108#if NH_MV
109: m_pchBitstreamFile()
110#else
111: m_pchInputFile()
112, m_pchBitstreamFile()
113, m_pchReconFile()
114#endif
115, m_inputColourSpaceConvert(IPCOLOURSPACE_UNCHANGED)
116, m_snrInternalColourSpace(false)
117, m_outputInternalColourSpace(false)
118, m_pchdQPFile()
119, m_scalingListFile()
120{
121#if !NH_MV
122  m_aidQP = NULL;
123#endif
124  m_startOfCodedInterval = NULL;
125  m_codedPivotValue = NULL;
126  m_targetPivotValue = NULL;
127
128}
129
130TAppEncCfg::~TAppEncCfg()
131{
132#if NH_MV
133  for( Int layer = 0; layer < m_aidQP.size(); layer++ )
134  {
135    if ( m_aidQP[layer] != NULL )
136    {
137      delete[] m_aidQP[layer];
138      m_aidQP[layer] = NULL;
139    }
140  }
141  for(Int i = 0; i< m_pchInputFileList.size(); i++ )
142  {
143    if ( m_pchInputFileList[i] != NULL )
144      free (m_pchInputFileList[i]);
145  }
146#else
147  if ( m_aidQP )
148  {
149    delete[] m_aidQP;
150  }
151#endif
152  if ( m_startOfCodedInterval )
153  {
154    delete[] m_startOfCodedInterval;
155    m_startOfCodedInterval = NULL;
156  }
157   if ( m_codedPivotValue )
158  {
159    delete[] m_codedPivotValue;
160    m_codedPivotValue = NULL;
161  }
162  if ( m_targetPivotValue )
163  {
164    delete[] m_targetPivotValue;
165    m_targetPivotValue = NULL;
166  }
167#if !NH_MV
168  free(m_pchInputFile);
169#endif
170  free(m_pchBitstreamFile);
171#if NH_MV
172  for(Int i = 0; i< m_pchReconFileList.size(); i++ )
173  {
174    if ( m_pchReconFileList[i] != NULL )
175      free (m_pchReconFileList[i]);
176  }
177#else
178  free(m_pchReconFile);
179#endif
180  free(m_pchdQPFile);
181  free(m_scalingListFile);
182#if NH_MV
183  for( Int i = 0; i < m_GOPListMvc.size(); i++ )
184  {
185    if( m_GOPListMvc[i] )
186    {
187      delete[] m_GOPListMvc[i];
188      m_GOPListMvc[i] = NULL;
189    }
190  }
191#endif
192}
193
194Void TAppEncCfg::create()
195{
196}
197
198Void TAppEncCfg::destroy()
199{
200}
201
202std::istringstream &operator>>(std::istringstream &in, GOPEntry &entry)     //input
203{
204  in>>entry.m_sliceType;
205  in>>entry.m_POC;
206  in>>entry.m_QPOffset;
207  in>>entry.m_QPFactor;
208  in>>entry.m_tcOffsetDiv2;
209  in>>entry.m_betaOffsetDiv2;
210  in>>entry.m_temporalId;
211  in>>entry.m_numRefPicsActive;
212  in>>entry.m_numRefPics;
213  for ( Int i = 0; i < entry.m_numRefPics; i++ )
214  {
215    in>>entry.m_referencePics[i];
216  }
217  in>>entry.m_interRPSPrediction;
218  if (entry.m_interRPSPrediction==1)
219  {
220    in>>entry.m_deltaRPS;
221    in>>entry.m_numRefIdc;
222    for ( Int i = 0; i < entry.m_numRefIdc; i++ )
223    {
224      in>>entry.m_refIdc[i];
225    }
226  }
227  else if (entry.m_interRPSPrediction==2)
228  {
229    in>>entry.m_deltaRPS;
230  }
231#if NH_MV
232  in>>entry.m_numActiveRefLayerPics;
233  for( Int i = 0; i < entry.m_numActiveRefLayerPics; i++ )
234  {
235    in>>entry.m_interLayerPredLayerIdc[i];
236  }
237  for( Int i = 0; i < entry.m_numActiveRefLayerPics; i++ )
238  {
239    in>>entry.m_interViewRefPosL[0][i];
240  }
241  for( Int i = 0; i < entry.m_numActiveRefLayerPics; i++ )
242  {
243    in>>entry.m_interViewRefPosL[1][i];
244  }
245#endif
246
247  return in;
248}
249
250Bool confirmPara(Bool bflag, const Char* message);
251
252static inline ChromaFormat numberToChromaFormat(const Int val)
253{
254  switch (val)
255  {
256    case 400: return CHROMA_400; break;
257    case 420: return CHROMA_420; break;
258    case 422: return CHROMA_422; break;
259    case 444: return CHROMA_444; break;
260    default:  return NUM_CHROMA_FORMAT;
261  }
262}
263
264static const struct MapStrToProfile
265{
266  const Char* str;
267  Profile::Name value;
268}
269strToProfile[] =
270{
271  {"none",                 Profile::NONE               },
272  {"main",                 Profile::MAIN               },
273  {"main10",               Profile::MAIN10             },
274  {"main-still-picture",   Profile::MAINSTILLPICTURE   },
275  {"main-RExt",            Profile::MAINREXT           },
276  {"high-throughput-RExt", Profile::HIGHTHROUGHPUTREXT }
277#if NH_MV
278  ,{"multiview-main"     , Profile::MULTIVIEWMAIN      },
279#endif
280
281};
282
283static const struct MapStrToExtendedProfile
284{
285  const Char* str;
286  ExtendedProfileName value;
287}
288strToExtendedProfile[] =
289{
290    {"none",               NONE             },
291    {"main",               MAIN             },
292    {"main10",             MAIN10           },
293    {"main_still_picture",        MAINSTILLPICTURE },
294    {"main-still-picture",        MAINSTILLPICTURE },
295    {"main_RExt",                 MAINREXT         },
296    {"main-RExt",                 MAINREXT         },
297    {"main_rext",                 MAINREXT         },
298    {"main-rext",                 MAINREXT         },
299    {"high_throughput_RExt",      HIGHTHROUGHPUTREXT },
300    {"high-throughput-RExt",      HIGHTHROUGHPUTREXT },
301    {"high_throughput_rext",      HIGHTHROUGHPUTREXT },
302    {"high-throughput-rext",      HIGHTHROUGHPUTREXT },
303#if NH_MV
304    {"multiview-main"     , MULTIVIEWMAIN   },
305#endif
306    {"monochrome",         MONOCHROME_8     },
307    {"monochrome12",       MONOCHROME_12    },
308    {"monochrome16",       MONOCHROME_16    },
309    {"main12",             MAIN_12          },
310    {"main_422_10",        MAIN_422_10      },
311    {"main_422_12",        MAIN_422_12      },
312    {"main_444",           MAIN_444         },
313    {"main_444_10",        MAIN_444_10      },
314    {"main_444_12",        MAIN_444_12      },
315    {"main_444_16",        MAIN_444_16      },
316    {"main_intra",         MAIN_INTRA       },
317    {"main_10_intra",      MAIN_10_INTRA    },
318    {"main_12_intra",      MAIN_12_INTRA    },
319    {"main_422_10_intra",  MAIN_422_10_INTRA},
320    {"main_422_12_intra",  MAIN_422_12_INTRA},
321    {"main_444_intra",     MAIN_444_INTRA   },
322    {"main_444_still_picture",    MAIN_444_STILL_PICTURE },
323    {"main_444_10_intra",  MAIN_444_10_INTRA},
324    {"main_444_12_intra",  MAIN_444_12_INTRA},
325    {"main_444_16_intra",         MAIN_444_16_INTRA},
326    {"main_444_16_still_picture", MAIN_444_16_STILL_PICTURE }
327};
328
329static const ExtendedProfileName validRExtProfileNames[2/* intraConstraintFlag*/][4/* bit depth constraint 8=0, 10=1, 12=2, 16=3*/][4/*chroma format*/]=
330{
331    {
332        { MONOCHROME_8,  NONE,          NONE,              MAIN_444          }, // 8-bit  inter for 400, 420, 422 and 444
333        { NONE,          NONE,          MAIN_422_10,       MAIN_444_10       }, // 10-bit inter for 400, 420, 422 and 444
334        { MONOCHROME_12, MAIN_12,       MAIN_422_12,       MAIN_444_12       }, // 12-bit inter for 400, 420, 422 and 444
335        { MONOCHROME_16, NONE,          NONE,              MAIN_444_16       }  // 16-bit inter for 400, 420, 422 and 444 (the latter is non standard used for development)
336    },
337    {
338        { NONE,          MAIN_INTRA,    NONE,              MAIN_444_INTRA    }, // 8-bit  intra for 400, 420, 422 and 444
339        { NONE,          MAIN_10_INTRA, MAIN_422_10_INTRA, MAIN_444_10_INTRA }, // 10-bit intra for 400, 420, 422 and 444
340        { NONE,          MAIN_12_INTRA, MAIN_422_12_INTRA, MAIN_444_12_INTRA }, // 12-bit intra for 400, 420, 422 and 444
341        { NONE,          NONE,          NONE,              MAIN_444_16_INTRA }  // 16-bit intra for 400, 420, 422 and 444
342    }
343};
344
345static const struct MapStrToTier
346{
347  const Char* str;
348  Level::Tier value;
349}
350strToTier[] =
351{
352  {"main", Level::MAIN},
353  {"high", Level::HIGH},
354};
355
356static const struct MapStrToLevel
357{
358  const Char* str;
359  Level::Name value;
360}
361strToLevel[] =
362{
363  {"none",Level::NONE},
364  {"1",   Level::LEVEL1},
365  {"2",   Level::LEVEL2},
366  {"2.1", Level::LEVEL2_1},
367  {"3",   Level::LEVEL3},
368  {"3.1", Level::LEVEL3_1},
369  {"4",   Level::LEVEL4},
370  {"4.1", Level::LEVEL4_1},
371  {"5",   Level::LEVEL5},
372  {"5.1", Level::LEVEL5_1},
373  {"5.2", Level::LEVEL5_2},
374  {"6",   Level::LEVEL6},
375  {"6.1", Level::LEVEL6_1},
376  {"6.2", Level::LEVEL6_2},
377  {"8.5", Level::LEVEL8_5},
378};
379
380static const struct MapStrToCostMode
381{
382  const Char* str;
383  CostMode    value;
384}
385strToCostMode[] =
386{
387  {"lossy",                     COST_STANDARD_LOSSY},
388  {"sequence_level_lossless",   COST_SEQUENCE_LEVEL_LOSSLESS},
389  {"lossless",                  COST_LOSSLESS_CODING},
390  {"mixed_lossless_lossy",      COST_MIXED_LOSSLESS_LOSSY_CODING}
391};
392
393static const struct MapStrToScalingListMode
394{
395  const Char* str;
396  ScalingListMode value;
397}
398strToScalingListMode[] =
399{
400  {"0",       SCALING_LIST_OFF},
401  {"1",       SCALING_LIST_DEFAULT},
402  {"2",       SCALING_LIST_FILE_READ},
403  {"off",     SCALING_LIST_OFF},
404  {"default", SCALING_LIST_DEFAULT},
405  {"file",    SCALING_LIST_FILE_READ}
406};
407
408template<typename T, typename P>
409static std::string enumToString(P map[], UInt mapLen, const T val)
410{
411  for (UInt i = 0; i < mapLen; i++)
412  {
413    if (val == map[i].value)
414    {
415      return map[i].str;
416    }
417  }
418  return std::string();
419}
420
421template<typename T, typename P>
422static istream& readStrToEnum(P map[], UInt mapLen, istream &in, T &val)
423{
424  string str;
425  in >> str;
426
427  for (UInt i = 0; i < mapLen; i++)
428  {
429    if (str == map[i].str)
430    {
431      val = map[i].value;
432      goto found;
433    }
434  }
435  /* not found */
436  in.setstate(ios::failbit);
437found:
438  return in;
439}
440
441//inline to prevent compiler warnings for "unused static function"
442
443static inline istream& operator >> (istream &in, ExtendedProfileName &profile)
444{
445  return readStrToEnum(strToExtendedProfile, sizeof(strToExtendedProfile)/sizeof(*strToExtendedProfile), in, profile);
446}
447
448namespace Level
449{
450  static inline istream& operator >> (istream &in, Tier &tier)
451  {
452    return readStrToEnum(strToTier, sizeof(strToTier)/sizeof(*strToTier), in, tier);
453  }
454
455  static inline istream& operator >> (istream &in, Name &level)
456  {
457    return readStrToEnum(strToLevel, sizeof(strToLevel)/sizeof(*strToLevel), in, level);
458  }
459}
460
461static inline istream& operator >> (istream &in, CostMode &mode)
462{
463  return readStrToEnum(strToCostMode, sizeof(strToCostMode)/sizeof(*strToCostMode), in, mode);
464}
465
466static inline istream& operator >> (istream &in, ScalingListMode &mode)
467{
468  return readStrToEnum(strToScalingListMode, sizeof(strToScalingListMode)/sizeof(*strToScalingListMode), in, mode);
469}
470
471template <class T>
472struct SMultiValueInput
473{
474  const T              minValIncl;
475  const T              maxValIncl; // Use 0 for unlimited
476  const std::size_t    minNumValuesIncl;
477  const std::size_t    maxNumValuesIncl; // Use 0 for unlimited
478        std::vector<T> values;
479  SMultiValueInput() : minValIncl(0), maxValIncl(0), minNumValuesIncl(0), maxNumValuesIncl(0), values() { }
480  SMultiValueInput(std::vector<T> &defaults) : minValIncl(0), maxValIncl(0), minNumValuesIncl(0), maxNumValuesIncl(0), values(defaults) { }
481  SMultiValueInput(const T &minValue, const T &maxValue, std::size_t minNumberValues=0, std::size_t maxNumberValues=0)
482    : minValIncl(minValue), maxValIncl(maxValue), minNumValuesIncl(minNumberValues), maxNumValuesIncl(maxNumberValues), values()  { }
483  SMultiValueInput(const T &minValue, const T &maxValue, std::size_t minNumberValues, std::size_t maxNumberValues, const T* defValues, const UInt numDefValues)
484    : minValIncl(minValue), maxValIncl(maxValue), minNumValuesIncl(minNumberValues), maxNumValuesIncl(maxNumberValues), values(defValues, defValues+numDefValues)  { }
485  SMultiValueInput<T> &operator=(const std::vector<T> &userValues) { values=userValues; return *this; }
486  SMultiValueInput<T> &operator=(const SMultiValueInput<T> &userValues) { values=userValues.values; return *this; }
487};
488
489static inline istream& operator >> (istream &in, SMultiValueInput<UInt> &values)
490{
491  values.values.clear();
492  string str;
493  while (!in.eof())
494  {
495    string tmp; in >> tmp; str+=" " + tmp;
496  }
497  if (!str.empty())
498  {
499    const Char *pStr=str.c_str();
500    // soak up any whitespace
501    for(;isspace(*pStr);pStr++);
502
503    while (*pStr != 0)
504    {
505      Char *eptr;
506      UInt val=strtoul(pStr, &eptr, 0);
507      if (*eptr!=0 && !isspace(*eptr) && *eptr!=',')
508      {
509        in.setstate(ios::failbit);
510        break;
511      }
512      if (val<values.minValIncl || val>values.maxValIncl)
513      {
514        in.setstate(ios::failbit);
515        break;
516      }
517
518      if (values.maxNumValuesIncl != 0 && values.values.size() >= values.maxNumValuesIncl)
519      {
520        in.setstate(ios::failbit);
521        break;
522      }
523      values.values.push_back(val);
524      // soak up any whitespace and up to 1 comma.
525      pStr=eptr;
526      for(;isspace(*pStr);pStr++);
527      if (*pStr == ',')
528      {
529        pStr++;
530      }
531      for(;isspace(*pStr);pStr++);
532    }
533  }
534  if (values.values.size() < values.minNumValuesIncl)
535  {
536    in.setstate(ios::failbit);
537  }
538  return in;
539}
540
541static inline istream& operator >> (istream &in, SMultiValueInput<Int> &values)
542{
543  values.values.clear();
544  string str;
545  while (!in.eof())
546  {
547    string tmp; in >> tmp; str+=" " + tmp;
548  }
549  if (!str.empty())
550  {
551    const Char *pStr=str.c_str();
552    // soak up any whitespace
553    for(;isspace(*pStr);pStr++);
554
555    while (*pStr != 0)
556    {
557      Char *eptr;
558      Int val=strtol(pStr, &eptr, 0);
559      if (*eptr!=0 && !isspace(*eptr) && *eptr!=',')
560      {
561        in.setstate(ios::failbit);
562        break;
563      }
564      if (val<values.minValIncl || val>values.maxValIncl)
565      {
566        in.setstate(ios::failbit);
567        break;
568      }
569
570      if (values.maxNumValuesIncl != 0 && values.values.size() >= values.maxNumValuesIncl)
571      {
572        in.setstate(ios::failbit);
573        break;
574      }
575      values.values.push_back(val);
576      // soak up any whitespace and up to 1 comma.
577      pStr=eptr;
578      for(;isspace(*pStr);pStr++);
579      if (*pStr == ',')
580      {
581        pStr++;
582      }
583      for(;isspace(*pStr);pStr++);
584    }
585  }
586  if (values.values.size() < values.minNumValuesIncl)
587  {
588    in.setstate(ios::failbit);
589  }
590  return in;
591}
592
593static inline istream& operator >> (istream &in, SMultiValueInput<Bool> &values)
594{
595  values.values.clear();
596  string str;
597  while (!in.eof())
598  {
599    string tmp; in >> tmp; str+=" " + tmp;
600  }
601  if (!str.empty())
602  {
603    const Char *pStr=str.c_str();
604    // soak up any whitespace
605    for(;isspace(*pStr);pStr++);
606
607    while (*pStr != 0)
608    {
609      Char *eptr;
610      Int val=strtol(pStr, &eptr, 0);
611      if (*eptr!=0 && !isspace(*eptr) && *eptr!=',')
612      {
613        in.setstate(ios::failbit);
614        break;
615      }
616      if (val<Int(values.minValIncl) || val>Int(values.maxValIncl))
617      {
618        in.setstate(ios::failbit);
619        break;
620      }
621
622      if (values.maxNumValuesIncl != 0 && values.values.size() >= values.maxNumValuesIncl)
623      {
624        in.setstate(ios::failbit);
625        break;
626      }
627      values.values.push_back(val!=0);
628      // soak up any whitespace and up to 1 comma.
629      pStr=eptr;
630      for(;isspace(*pStr);pStr++);
631      if (*pStr == ',')
632      {
633        pStr++;
634      }
635      for(;isspace(*pStr);pStr++);
636    }
637  }
638  if (values.values.size() < values.minNumValuesIncl)
639  {
640    in.setstate(ios::failbit);
641  }
642  return in;
643}
644
645static Void
646automaticallySelectRExtProfile(const Bool bUsingGeneralRExtTools,
647                               const Bool bUsingChromaQPAdjustment,
648                               const Bool bUsingExtendedPrecision,
649                               const Bool bIntraConstraintFlag,
650                               UInt &bitDepthConstraint,
651                               ChromaFormat &chromaFormatConstraint,
652                               const Int  maxBitDepth,
653                               const ChromaFormat chromaFormat)
654{
655  // Try to choose profile, according to table in Q1013.
656  UInt trialBitDepthConstraint=maxBitDepth;
657  if (trialBitDepthConstraint<8)
658  {
659    trialBitDepthConstraint=8;
660  }
661  else if (trialBitDepthConstraint==9 || trialBitDepthConstraint==11)
662  {
663    trialBitDepthConstraint++;
664  }
665  else if (trialBitDepthConstraint>12)
666  {
667    trialBitDepthConstraint=16;
668  }
669
670  // both format and bit depth constraints are unspecified
671  if (bUsingExtendedPrecision || trialBitDepthConstraint==16)
672  {
673    bitDepthConstraint = 16;
674    chromaFormatConstraint = (!bIntraConstraintFlag && chromaFormat==CHROMA_400) ? CHROMA_400 : CHROMA_444;
675  }
676  else if (bUsingGeneralRExtTools)
677  {
678    if (chromaFormat == CHROMA_400 && !bIntraConstraintFlag)
679    {
680      bitDepthConstraint = 16;
681      chromaFormatConstraint = CHROMA_400;
682    }
683    else
684    {
685      bitDepthConstraint = trialBitDepthConstraint;
686      chromaFormatConstraint = CHROMA_444;
687    }
688  }
689  else if (chromaFormat == CHROMA_400)
690  {
691    if (bIntraConstraintFlag)
692    {
693      chromaFormatConstraint = CHROMA_420; // there is no intra 4:0:0 profile.
694      bitDepthConstraint     = trialBitDepthConstraint;
695    }
696    else
697    {
698      chromaFormatConstraint = CHROMA_400;
699      bitDepthConstraint     = trialBitDepthConstraint == 8 ? 8 : 12;
700    }
701  }
702  else
703  {
704    bitDepthConstraint = trialBitDepthConstraint;
705    chromaFormatConstraint = chromaFormat;
706    if (bUsingChromaQPAdjustment && chromaFormat == CHROMA_420)
707    {
708      chromaFormatConstraint = CHROMA_422; // 4:2:0 cannot use the chroma qp tool.
709    }
710    if (chromaFormatConstraint == CHROMA_422 && bitDepthConstraint == 8)
711    {
712      bitDepthConstraint = 10; // there is no 8-bit 4:2:2 profile.
713    }
714    if (chromaFormatConstraint == CHROMA_420 && !bIntraConstraintFlag)
715    {
716      bitDepthConstraint = 12; // there is no 8 or 10-bit 4:2:0 inter RExt profile.
717    }
718  }
719}
720// ====================================================================================================================
721// Public member functions
722// ====================================================================================================================
723
724/** \param  argc        number of arguments
725    \param  argv        array of arguments
726    \retval             true when success
727 */
728Bool TAppEncCfg::parseCfg( Int argc, Char* argv[] )
729{
730  Bool do_help = false;
731
732#if !NH_MV
733  string cfg_InputFile;
734#endif
735  string cfg_BitstreamFile;
736#if !NH_MV
737  string cfg_ReconFile;
738#endif
739#if NH_MV
740  vector<Int>   cfg_dimensionLength; 
741  string        cfg_profiles;
742  string        cfg_levels; 
743  string        cfg_tiers; 
744  cfg_dimensionLength.push_back( 64 ); 
745#endif
746  string cfg_dQPFile;
747  string cfg_ScalingListFile;
748
749  Int tmpChromaFormat;
750  Int tmpInputChromaFormat;
751  Int tmpConstraintChromaFormat;
752  string inputColourSpaceConvert;
753#if NH_MV
754  std::vector<ExtendedProfileName> extendedProfiles;
755#else
756  ExtendedProfileName extendedProfile;
757#endif
758  Int saoOffsetBitShift[MAX_NUM_CHANNEL_TYPE];
759
760  // Multi-value input fields:                                // minval, maxval (incl), min_entries, max_entries (incl) [, default values, number of default values]
761  SMultiValueInput<UInt> cfg_ColumnWidth                     (0, std::numeric_limits<UInt>::max(), 0, std::numeric_limits<UInt>::max());
762  SMultiValueInput<UInt> cfg_RowHeight                       (0, std::numeric_limits<UInt>::max(), 0, std::numeric_limits<UInt>::max());
763  SMultiValueInput<Int>  cfg_startOfCodedInterval            (std::numeric_limits<Int>::min(), std::numeric_limits<Int>::max(), 0, 1<<16);
764  SMultiValueInput<Int>  cfg_codedPivotValue                 (std::numeric_limits<Int>::min(), std::numeric_limits<Int>::max(), 0, 1<<16);
765  SMultiValueInput<Int>  cfg_targetPivotValue                (std::numeric_limits<Int>::min(), std::numeric_limits<Int>::max(), 0, 1<<16);
766
767  const UInt defaultInputKneeCodes[3]  = { 600, 800, 900 };
768  const UInt defaultOutputKneeCodes[3] = { 100, 250, 450 };
769  SMultiValueInput<UInt> cfg_kneeSEIInputKneePointValue      (1,  999, 0, 999, defaultInputKneeCodes,  sizeof(defaultInputKneeCodes )/sizeof(UInt));
770  SMultiValueInput<UInt> cfg_kneeSEIOutputKneePointValue     (0, 1000, 0, 999, defaultOutputKneeCodes, sizeof(defaultOutputKneeCodes)/sizeof(UInt));
771  const Int defaultPrimaryCodes[6]     = { 0,50000, 0,0, 50000,0 };
772  const Int defaultWhitePointCode[2]   = { 16667, 16667 };
773  SMultiValueInput<Int>  cfg_DisplayPrimariesCode            (0, 50000, 3, 3, defaultPrimaryCodes,   sizeof(defaultPrimaryCodes  )/sizeof(Int));
774  SMultiValueInput<Int>  cfg_DisplayWhitePointCode           (0, 50000, 2, 2, defaultWhitePointCode, sizeof(defaultWhitePointCode)/sizeof(Int));
775
776  SMultiValueInput<Bool> cfg_timeCodeSeiTimeStampFlag        (0,  1, 0, MAX_TIMECODE_SEI_SETS);
777  SMultiValueInput<Bool> cfg_timeCodeSeiNumUnitFieldBasedFlag(0,  1, 0, MAX_TIMECODE_SEI_SETS);
778  SMultiValueInput<Int>  cfg_timeCodeSeiCountingType         (0,  6, 0, MAX_TIMECODE_SEI_SETS);
779  SMultiValueInput<Bool> cfg_timeCodeSeiFullTimeStampFlag    (0,  1, 0, MAX_TIMECODE_SEI_SETS);
780  SMultiValueInput<Bool> cfg_timeCodeSeiDiscontinuityFlag    (0,  1, 0, MAX_TIMECODE_SEI_SETS);
781  SMultiValueInput<Bool> cfg_timeCodeSeiCntDroppedFlag       (0,  1, 0, MAX_TIMECODE_SEI_SETS);
782  SMultiValueInput<Int>  cfg_timeCodeSeiNumberOfFrames       (0,511, 0, MAX_TIMECODE_SEI_SETS);
783  SMultiValueInput<Int>  cfg_timeCodeSeiSecondsValue         (0, 59, 0, MAX_TIMECODE_SEI_SETS);
784  SMultiValueInput<Int>  cfg_timeCodeSeiMinutesValue         (0, 59, 0, MAX_TIMECODE_SEI_SETS);
785  SMultiValueInput<Int>  cfg_timeCodeSeiHoursValue           (0, 23, 0, MAX_TIMECODE_SEI_SETS);
786  SMultiValueInput<Bool> cfg_timeCodeSeiSecondsFlag          (0,  1, 0, MAX_TIMECODE_SEI_SETS);
787  SMultiValueInput<Bool> cfg_timeCodeSeiMinutesFlag          (0,  1, 0, MAX_TIMECODE_SEI_SETS);
788  SMultiValueInput<Bool> cfg_timeCodeSeiHoursFlag            (0,  1, 0, MAX_TIMECODE_SEI_SETS);
789  SMultiValueInput<Int>  cfg_timeCodeSeiTimeOffsetLength     (0, 31, 0, MAX_TIMECODE_SEI_SETS);
790  SMultiValueInput<Int>  cfg_timeCodeSeiTimeOffsetValue      (std::numeric_limits<Int>::min(), std::numeric_limits<Int>::max(), 0, MAX_TIMECODE_SEI_SETS);
791  Int warnUnknowParameter = 0;
792
793  po::Options opts;
794  opts.addOptions()
795  ("help",                                            do_help,                                          false, "this help text")
796  ("c",    po::parseConfigFile, "configuration file name")
797  ("WarnUnknowParameter,w",                           warnUnknowParameter,                                  0, "warn for unknown configuration parameters instead of failing")
798
799  // File, I/O and source parameters
800#if NH_MV
801  ("InputFile_%d,i_%d",       m_pchInputFileList,       (char *) 0 , MAX_NUM_LAYER_IDS , "original Yuv input file name %d")
802#else
803  ("InputFile,i",                                     cfg_InputFile,                               string(""), "Original YUV input file name")
804#endif
805  ("BitstreamFile,b",                                 cfg_BitstreamFile,                           string(""), "Bitstream output file name")
806#if NH_MV
807  ("ReconFile_%d,o_%d",       m_pchReconFileList,       (char *) 0 , MAX_NUM_LAYER_IDS , "reconstructed Yuv output file name %d")
808#else
809  ("ReconFile,o",                                     cfg_ReconFile,                               string(""), "Reconstructed YUV output file name")
810#endif
811#if NH_MV
812  ("NumberOfLayers",        m_numberOfLayers     , 1,                     "Number of layers")
813  ("ScalabilityMask",       m_scalabilityMask    , 2                    , "Scalability Mask: 2: Multiview, 8: Auxiliary, 10: Multiview + Auxiliary")   
814  ("DimensionIdLen",        m_dimensionIdLen     , cfg_dimensionLength  , "Number of bits used to store dimensions Id")
815  ("ViewOrderIndex",        m_viewOrderIndex     , std::vector<Int>(1,0), "View Order Index per layer")
816  ("ViewId",                m_viewId             , std::vector<Int>(1,0), "View Id per View Order Index")
817  ("AuxId",                 m_auxId              , std::vector<Int>(1,0), "AuxId per layer")
818  ("TargetEncLayerIdList",  m_targetEncLayerIdList, std::vector<Int>(0,0), "LayerIds in Nuh to be encoded") 
819  ("LayerIdInNuh",          m_layerIdInNuh        , std::vector<Int>(1,0), "LayerId in Nuh") 
820  ("SplittingFlag",         m_splittingFlag       , false                , "Splitting Flag")   
821
822  // Layer Sets + Output Layer Sets + Profile Tier Level
823  ("VpsNumLayerSets",       m_vpsNumLayerSets    , 1                    , "Number of layer sets")   
824  ("LayerIdsInSet_%d",      m_layerIdsInSets     , std::vector<Int>(1,0), MAX_VPS_OP_SETS_PLUS1 ,"LayerIds of Layer set") 
825  ("NumAddLayerSets"     , m_numAddLayerSets     , 0                                              , "NumAddLayerSets     ")
826  ("HighestLayerIdxPlus1_%d", m_highestLayerIdxPlus1, std::vector< Int  >(0,0)  ,MAX_VPS_NUM_ADD_LAYER_SETS, "HighestLayerIdxPlus1")
827  ("DefaultTargetOutputLayerIdc"     , m_defaultOutputLayerIdc     , 0, "Specifies output layers of layer sets, 0: output all layers, 1: output highest layer, 2: specified by LayerIdsInDefOutputLayerSet")
828  ("OutputLayerSetIdx",     m_outputLayerSetIdx  , std::vector<Int>(0,0), "Indices of layer sets used as additional output layer sets") 
829
830  ("LayerIdsInAddOutputLayerSet_%d", m_layerIdsInAddOutputLayerSet      , std::vector<Int>(0,0), MAX_VPS_ADD_OUTPUT_LAYER_SETS, "Indices in VPS of output layers in additional output layer set") 
831  ("LayerIdsInDefOutputLayerSet_%d", m_layerIdsInDefOutputLayerSet      , std::vector<Int>(0,0), MAX_VPS_OP_SETS_PLUS1, "Indices in VPS of output layers in layer set") 
832  ("AltOutputLayerFlag",    m_altOutputLayerFlag , std::vector<Bool>(1,0), "Alt output layer flag")
833 
834  ("ProfileTierLevelIdx_%d",  m_profileTierLevelIdx, std::vector<Int>(0), MAX_NUM_LAYERS, "Indices to profile level tier for ols")
835  // Layer dependencies
836  ("DirectRefLayers_%d",    m_directRefLayers    , std::vector<Int>(0,0), MAX_NUM_LAYERS, "LayerIdx in VPS of direct reference layers")
837  ("DependencyTypes_%d",    m_dependencyTypes    , std::vector<Int>(0,0), MAX_NUM_LAYERS, "Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion")
838#endif
839  ("SourceWidth,-wdt",                                m_iSourceWidth,                                       0, "Source picture width")
840  ("SourceHeight,-hgt",                               m_iSourceHeight,                                      0, "Source picture height")
841  ("InputBitDepth",                                   m_inputBitDepth[CHANNEL_TYPE_LUMA],                   8, "Bit-depth of input file")
842  ("OutputBitDepth",                                  m_outputBitDepth[CHANNEL_TYPE_LUMA],                  0, "Bit-depth of output file (default:InternalBitDepth)")
843  ("MSBExtendedBitDepth",                             m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA],             0, "bit depth of luma component after addition of MSBs of value 0 (used for synthesising High Dynamic Range source material). (default:InputBitDepth)")
844  ("InternalBitDepth",                                m_internalBitDepth[CHANNEL_TYPE_LUMA],                0, "Bit-depth the codec operates at. (default:MSBExtendedBitDepth). If different to MSBExtendedBitDepth, source data will be converted")
845  ("InputBitDepthC",                                  m_inputBitDepth[CHANNEL_TYPE_CHROMA],                 0, "As per InputBitDepth but for chroma component. (default:InputBitDepth)")
846  ("OutputBitDepthC",                                 m_outputBitDepth[CHANNEL_TYPE_CHROMA],                0, "As per OutputBitDepth but for chroma component. (default:InternalBitDepthC)")
847  ("MSBExtendedBitDepthC",                            m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA],           0, "As per MSBExtendedBitDepth but for chroma component. (default:MSBExtendedBitDepth)")
848  ("InternalBitDepthC",                               m_internalBitDepth[CHANNEL_TYPE_CHROMA],              0, "As per InternalBitDepth but for chroma component. (default:InternalBitDepth)")
849  ("ExtendedPrecision",                               m_extendedPrecisionProcessingFlag,                false, "Increased internal accuracies to support high bit depths (not valid in V1 profiles)")
850  ("HighPrecisionPredictionWeighting",                m_highPrecisionOffsetsEnabledFlag,                false, "Use high precision option for weighted prediction (not valid in V1 profiles)")
851  ("InputColourSpaceConvert",                         inputColourSpaceConvert,                     string(""), "Colour space conversion to apply to input video. Permitted values are (empty string=UNCHANGED) " + getListOfColourSpaceConverts(true))
852  ("SNRInternalColourSpace",                          m_snrInternalColourSpace,                         false, "If true, then no colour space conversion is applied prior to SNR, otherwise inverse of input is applied.")
853  ("OutputInternalColourSpace",                       m_outputInternalColourSpace,                      false, "If true, then no colour space conversion is applied for reconstructed video, otherwise inverse of input is applied.")
854  ("InputChromaFormat",                               tmpInputChromaFormat,                               420, "InputChromaFormatIDC")
855  ("MSEBasedSequencePSNR",                            m_printMSEBasedSequencePSNR,                      false, "0 (default) emit sequence PSNR only as a linear average of the frame PSNRs, 1 = also emit a sequence PSNR based on an average of the frame MSEs")
856  ("PrintFrameMSE",                                   m_printFrameMSE,                                  false, "0 (default) emit only bit count and PSNRs for each frame, 1 = also emit MSE values")
857  ("PrintSequenceMSE",                                m_printSequenceMSE,                               false, "0 (default) emit only bit rate and PSNRs for the whole sequence, 1 = also emit MSE values")
858  ("CabacZeroWordPaddingEnabled",                     m_cabacZeroWordPaddingEnabled,                     true, "0 do not add conforming cabac-zero-words to bit streams, 1 (default) = add cabac-zero-words as required")
859  ("ChromaFormatIDC,-cf",                             tmpChromaFormat,                                      0, "ChromaFormatIDC (400|420|422|444 or set 0 (default) for same as InputChromaFormat)")
860  ("ConformanceMode",                                 m_conformanceWindowMode,                              0, "Deprecated alias of ConformanceWindowMode")
861  ("ConformanceWindowMode",                           m_conformanceWindowMode,                              0, "Window conformance mode (0: no window, 1:automatic padding, 2:padding, 3:conformance")
862  ("HorizontalPadding,-pdx",                          m_aiPad[0],                                           0, "Horizontal source padding for conformance window mode 2")
863  ("VerticalPadding,-pdy",                            m_aiPad[1],                                           0, "Vertical source padding for conformance window mode 2")
864  ("ConfLeft",                                        m_confWinLeft,                                        0, "Deprecated alias of ConfWinLeft")
865  ("ConfRight",                                       m_confWinRight,                                       0, "Deprecated alias of ConfWinRight")
866  ("ConfTop",                                         m_confWinTop,                                         0, "Deprecated alias of ConfWinTop")
867  ("ConfBottom",                                      m_confWinBottom,                                      0, "Deprecated alias of ConfWinBottom")
868  ("ConfWinLeft",                                     m_confWinLeft,                                        0, "Left offset for window conformance mode 3")
869  ("ConfWinRight",                                    m_confWinRight,                                       0, "Right offset for window conformance mode 3")
870  ("ConfWinTop",                                      m_confWinTop,                                         0, "Top offset for window conformance mode 3")
871  ("ConfWinBottom",                                   m_confWinBottom,                                      0, "Bottom offset for window conformance mode 3")
872  ("FrameRate,-fr",                                   m_iFrameRate,                                         0, "Frame rate")
873  ("FrameSkip,-fs",                                   m_FrameSkip,                                         0u, "Number of frames to skip at start of input YUV")
874  ("FramesToBeEncoded,f",                             m_framesToBeEncoded,                                  0, "Number of frames to be encoded (default=all)")
875  ("ClipInputVideoToRec709Range",                     m_bClipInputVideoToRec709Range,                   false, "If true then clip input video to the Rec. 709 Range on loading when InternalBitDepth is less than MSBExtendedBitDepth")
876  ("ClipOutputVideoToRec709Range",                    m_bClipOutputVideoToRec709Range,                  false, "If true then clip output video to the Rec. 709 Range on saving when OutputBitDepth is less than InternalBitDepth")
877  ("SummaryOutFilename",                              m_summaryOutFilename,                          string(), "Filename to use for producing summary output file. If empty, do not produce a file.")
878  ("SummaryPicFilenameBase",                          m_summaryPicFilenameBase,                      string(), "Base filename to use for producing summary picture output files. The actual filenames used will have I.txt, P.txt and B.txt appended. If empty, do not produce a file.")
879  ("SummaryVerboseness",                              m_summaryVerboseness,                                0u, "Specifies the level of the verboseness of the text output")
880
881  //Field coding parameters
882  ("FieldCoding",                                     m_isField,                                        false, "Signals if it's a field based coding")
883  ("TopFieldFirst, Tff",                              m_isTopFieldFirst,                                false, "In case of field based coding, signals whether if it's a top field first or not")
884  ("EfficientFieldIRAPEnabled",                       m_bEfficientFieldIRAPEnabled,                      true, "Enable to code fields in a specific, potentially more efficient, order.")
885  ("HarmonizeGopFirstFieldCoupleEnabled",             m_bHarmonizeGopFirstFieldCoupleEnabled,            true, "Enables harmonization of Gop first field couple")
886
887  // Profile and level
888#if NH_MV
889  ("Profile" ,                                        cfg_profiles,                                string(""), "Profile in VpsProfileTierLevel (Indication only)")
890  ("Level"   ,                                        cfg_levels ,                                 string(""), "Level indication in VpsProfileTierLevel (Indication only)")
891  ("Tier"    ,                                        cfg_tiers  ,                                 string(""), "Tier indication in VpsProfileTierLevel (Indication only)")
892  ("InblFlag",                                        m_inblFlag ,                       std::vector<Bool>(0), "InblFlags in VpsProfileTierLevel (Indication only)" )
893#else
894  ("Profile",                                         extendedProfile,                                   NONE, "Profile name to use for encoding. Use main (for main), main10 (for main10), main-still-picture, main-RExt (for Range Extensions profile), any of the RExt specific profile names, or none")
895  ("Level",                                           m_level,                                    Level::NONE, "Level limit to be used, eg 5.1, or none")
896  ("Tier",                                            m_levelTier,                                Level::MAIN, "Tier to use for interpretation of --Level (main or high only)")
897#endif
898  ("MaxBitDepthConstraint",                           m_bitDepthConstraint,                                0u, "Bit depth to use for profile-constraint for RExt profiles. 0=automatically choose based upon other parameters")
899  ("MaxChromaFormatConstraint",                       tmpConstraintChromaFormat,                            0, "Chroma-format to use for the profile-constraint for RExt profiles. 0=automatically choose based upon other parameters")
900  ("IntraConstraintFlag",                             m_intraConstraintFlag,                            false, "Value of general_intra_constraint_flag to use for RExt profiles (not used if an explicit RExt sub-profile is specified)")
901  ("OnePictureOnlyConstraintFlag",                    m_onePictureOnlyConstraintFlag,                   false, "Value of general_one_picture_only_constraint_flag to use for RExt profiles (not used if an explicit RExt sub-profile is specified)")
902  ("LowerBitRateConstraintFlag",                      m_lowerBitRateConstraintFlag,                      true, "Value of general_lower_bit_rate_constraint_flag to use for RExt profiles")
903
904  ("ProgressiveSource",                               m_progressiveSourceFlag,                          false, "Indicate that source is progressive")
905  ("InterlacedSource",                                m_interlacedSourceFlag,                           false, "Indicate that source is interlaced")
906  ("NonPackedSource",                                 m_nonPackedConstraintFlag,                        false, "Indicate that source does not contain frame packing")
907  ("FrameOnly",                                       m_frameOnlyConstraintFlag,                        false, "Indicate that the bitstream contains only frames")
908
909  // Unit definition parameters
910  ("MaxCUWidth",                                      m_uiMaxCUWidth,                                     64u)
911  ("MaxCUHeight",                                     m_uiMaxCUHeight,                                    64u)
912  // todo: remove defaults from MaxCUSize
913  ("MaxCUSize,s",                                     m_uiMaxCUWidth,                                     64u, "Maximum CU size")
914  ("MaxCUSize,s",                                     m_uiMaxCUHeight,                                    64u, "Maximum CU size")
915  ("MaxPartitionDepth,h",                             m_uiMaxCUDepth,                                      4u, "CU depth")
916
917  ("QuadtreeTULog2MaxSize",                           m_uiQuadtreeTULog2MaxSize,                           6u, "Maximum TU size in logarithm base 2")
918  ("QuadtreeTULog2MinSize",                           m_uiQuadtreeTULog2MinSize,                           2u, "Minimum TU size in logarithm base 2")
919
920  ("QuadtreeTUMaxDepthIntra",                         m_uiQuadtreeTUMaxDepthIntra,                         1u, "Depth of TU tree for intra CUs")
921  ("QuadtreeTUMaxDepthInter",                         m_uiQuadtreeTUMaxDepthInter,                         2u, "Depth of TU tree for inter CUs")
922#if NH_MV 
923  // Coding structure parameters
924  ("IntraPeriod,-ip",                                 m_iIntraPeriod,std::vector<Int>(1,-1)                  , "Intra period in frames, (-1: only first frame), per layer")
925#else
926  // Coding structure paramters
927  ("IntraPeriod,-ip",                                 m_iIntraPeriod,                                      -1, "Intra period in frames, (-1: only first frame)")
928#endif
929  ("DecodingRefreshType,-dr",                         m_iDecodingRefreshType,                               0, "Intra refresh type (0:none 1:CRA 2:IDR 3:RecPointSEI)")
930  ("GOPSize,g",                                       m_iGOPSize,                                           1, "GOP size of temporal structure")
931
932  // motion search options
933  ("DisableIntraInInter",                             m_bDisableIntraPUsInInterSlices,                  false, "Flag to disable intra PUs in inter slices")
934  ("FastSearch",                                      m_iFastSearch,                                        1, "0:Full search  1:Diamond  2:PMVFAST")
935  ("SearchRange,-sr",                                 m_iSearchRange,                                      96, "Motion search range")
936#if NH_MV
937  ("DispSearchRangeRestriction",  m_bUseDisparitySearchRangeRestriction, false, "restrict disparity search range")
938  ("VerticalDispSearchRange",     m_iVerticalDisparitySearchRange, 56, "vertical disparity search range")
939#endif
940  ("BipredSearchRange",                               m_bipredSearchRange,                                  4, "Motion search range for bipred refinement")
941  ("ClipForBiPredMEEnabled",                          m_bClipForBiPredMeEnabled,                        false, "Enables clipping in the Bi-Pred ME. It is disabled to reduce encoder run-time")
942  ("FastMEAssumingSmootherMVEnabled",                 m_bFastMEAssumingSmootherMVEnabled,                true, "Enables fast ME assuming a smoother MV.")
943
944  ("HadamardME",                                      m_bUseHADME,                                       true, "Hadamard ME for fractional-pel")
945  ("ASR",                                             m_bUseASR,                                        false, "Adaptive motion search range")
946
947  // Mode decision parameters
948  ("LambdaModifier0,-LM0",                            m_adLambdaModifier[ 0 ],                  ( Double )1.0, "Lambda modifier for temporal layer 0")
949  ("LambdaModifier1,-LM1",                            m_adLambdaModifier[ 1 ],                  ( Double )1.0, "Lambda modifier for temporal layer 1")
950  ("LambdaModifier2,-LM2",                            m_adLambdaModifier[ 2 ],                  ( Double )1.0, "Lambda modifier for temporal layer 2")
951  ("LambdaModifier3,-LM3",                            m_adLambdaModifier[ 3 ],                  ( Double )1.0, "Lambda modifier for temporal layer 3")
952  ("LambdaModifier4,-LM4",                            m_adLambdaModifier[ 4 ],                  ( Double )1.0, "Lambda modifier for temporal layer 4")
953  ("LambdaModifier5,-LM5",                            m_adLambdaModifier[ 5 ],                  ( Double )1.0, "Lambda modifier for temporal layer 5")
954  ("LambdaModifier6,-LM6",                            m_adLambdaModifier[ 6 ],                  ( Double )1.0, "Lambda modifier for temporal layer 6")
955
956  /* Quantization parameters */
957#if NH_MV
958  ("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")
959#else
960  ("QP,q",                                            m_fQP,                                             30.0, "Qp value, if value is float, QP is switched once during encoding")
961#endif
962  ("DeltaQpRD,-dqr",                                  m_uiDeltaQpRD,                                       0u, "max dQp offset for slice")
963  ("MaxDeltaQP,d",                                    m_iMaxDeltaQP,                                        0, "max dQp offset for block")
964  ("MaxCuDQPDepth,-dqd",                              m_iMaxCuDQPDepth,                                     0, "max depth for a minimum CuDQP")
965  ("MaxCUChromaQpAdjustmentDepth",                    m_diffCuChromaQpOffsetDepth,                         -1, "Maximum depth for CU chroma Qp adjustment - set less than 0 to disable")
966  ("FastDeltaQP",                                     m_bFastDeltaQP,                                   false, "Fast Delta QP Algorithm")
967
968  ("CbQpOffset,-cbqpofs",                             m_cbQpOffset,                                         0, "Chroma Cb QP Offset")
969  ("CrQpOffset,-crqpofs",                             m_crQpOffset,                                         0, "Chroma Cr QP Offset")
970
971#if ADAPTIVE_QP_SELECTION
972  ("AdaptiveQpSelection,-aqps",                       m_bUseAdaptQpSelect,                              false, "AdaptiveQpSelection")
973#endif
974
975  ("AdaptiveQP,-aq",                                  m_bUseAdaptiveQP,                                 false, "QP adaptation based on a psycho-visual model")
976  ("MaxQPAdaptationRange,-aqr",                       m_iQPAdaptationRange,                                 6, "QP adaptation range")
977  ("dQPFile,m",                                       cfg_dQPFile,                                 string(""), "dQP file name")
978  ("RDOQ",                                            m_useRDOQ,                                         true)
979  ("RDOQTS",                                          m_useRDOQTS,                                       true)
980#if T0196_SELECTIVE_RDOQ
981  ("SelectiveRDOQ",                                   m_useSelectiveRDOQ,                               false, "Enable selective RDOQ")
982#endif
983  ("RDpenalty",                                       m_rdPenalty,                                          0,  "RD-penalty for 32x32 TU for intra in non-intra slices. 0:disabled  1:RD-penalty  2:maximum RD-penalty")
984
985  // Deblocking filter parameters
986#if NH_MV
987  ("LoopFilterDisable",                               m_bLoopFilterDisable,                             std::vector<Bool>(1,false), "Disable Loop Filter per Layer" )
988#else
989  ("LoopFilterDisable",                               m_bLoopFilterDisable,                             false)
990#endif
991  ("LoopFilterOffsetInPPS",                           m_loopFilterOffsetInPPS,                           true)
992  ("LoopFilterBetaOffset_div2",                       m_loopFilterBetaOffsetDiv2,                           0)
993  ("LoopFilterTcOffset_div2",                         m_loopFilterTcOffsetDiv2,                             0)
994  ("DeblockingFilterMetric",                          m_DeblockingFilterMetric,                         false)
995
996  // Coding tools
997  ("AMP",                                             m_enableAMP,                                       true, "Enable asymmetric motion partitions")
998  ("CrossComponentPrediction",                        m_crossComponentPredictionEnabledFlag,            false, "Enable the use of cross-component prediction (not valid in V1 profiles)")
999  ("ReconBasedCrossCPredictionEstimate",              m_reconBasedCrossCPredictionEstimate,             false, "When determining the alpha value for cross-component prediction, use the decoded residual rather than the pre-transform encoder-side residual")
1000  ("SaoLumaOffsetBitShift",                           saoOffsetBitShift[CHANNEL_TYPE_LUMA],                 0, "Specify the luma SAO bit-shift. If negative, automatically calculate a suitable value based upon bit depth and initial QP")
1001  ("SaoChromaOffsetBitShift",                         saoOffsetBitShift[CHANNEL_TYPE_CHROMA],               0, "Specify the chroma SAO bit-shift. If negative, automatically calculate a suitable value based upon bit depth and initial QP")
1002  ("TransformSkip",                                   m_useTransformSkip,                               false, "Intra transform skipping")
1003  ("TransformSkipFast",                               m_useTransformSkipFast,                           false, "Fast intra transform skipping")
1004  ("TransformSkipLog2MaxSize",                        m_log2MaxTransformSkipBlockSize,                     2U, "Specify transform-skip maximum size. Minimum 2. (not valid in V1 profiles)")
1005  ("ImplicitResidualDPCM",                            m_rdpcmEnabledFlag[RDPCM_SIGNAL_IMPLICIT],        false, "Enable implicitly signalled residual DPCM for intra (also known as sample-adaptive intra predict) (not valid in V1 profiles)")
1006  ("ExplicitResidualDPCM",                            m_rdpcmEnabledFlag[RDPCM_SIGNAL_EXPLICIT],        false, "Enable explicitly signalled residual DPCM for inter (not valid in V1 profiles)")
1007  ("ResidualRotation",                                m_transformSkipRotationEnabledFlag,               false, "Enable rotation of transform-skipped and transquant-bypassed TUs through 180 degrees prior to entropy coding (not valid in V1 profiles)")
1008  ("SingleSignificanceMapContext",                    m_transformSkipContextEnabledFlag,                false, "Enable, for transform-skipped and transquant-bypassed TUs, the selection of a single significance map context variable for all coefficients (not valid in V1 profiles)")
1009  ("GolombRiceParameterAdaptation",                   m_persistentRiceAdaptationEnabledFlag,            false, "Enable the adaptation of the Golomb-Rice parameter over the course of each slice")
1010  ("AlignCABACBeforeBypass",                          m_cabacBypassAlignmentEnabledFlag,                false, "Align the CABAC engine to a defined fraction of a bit prior to coding bypass data. Must be 1 in high bit rate profile, 0 otherwise" )
1011#if NH_MV
1012  ("SAO",                      m_bUseSAO, std::vector<Bool>(1,true), "Enable Sample Adaptive Offset per Layer")
1013#else
1014  ("SAO",                                             m_bUseSAO,                                         true, "Enable Sample Adaptive Offset")
1015#endif
1016  ("TestSAODisableAtPictureLevel",                    m_bTestSAODisableAtPictureLevel,                  false, "Enables the testing of disabling SAO at the picture level after having analysed all blocks")
1017  ("SaoEncodingRate",                                 m_saoEncodingRate,                                 0.75, "When >0 SAO early picture termination is enabled for luma and chroma")
1018  ("SaoEncodingRateChroma",                           m_saoEncodingRateChroma,                            0.5, "The SAO early picture termination rate to use for chroma (when m_SaoEncodingRate is >0). If <=0, use results for luma")
1019  ("MaxNumOffsetsPerPic",                             m_maxNumOffsetsPerPic,                             2048, "Max number of SAO offset per picture (Default: 2048)")
1020  ("SAOLcuBoundary",                                  m_saoCtuBoundary,                                 false, "0: right/bottom CTU boundary areas skipped from SAO parameter estimation, 1: non-deblocked pixels are used for those areas")
1021  ("SliceMode",                                       m_sliceMode,                                          0, "0: Disable all Recon slice limits, 1: Enforce max # of CTUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
1022  ("SliceArgument",                                   m_sliceArgument,                                      0, "Depending on SliceMode being:"
1023                                                                                                               "\t1: max number of CTUs per slice"
1024                                                                                                               "\t2: max number of bytes per slice"
1025                                                                                                               "\t3: max number of tiles per slice")
1026  ("SliceSegmentMode",                                m_sliceSegmentMode,                                   0, "0: Disable all slice segment limits, 1: Enforce max # of CTUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
1027  ("SliceSegmentArgument",                            m_sliceSegmentArgument,                               0, "Depending on SliceSegmentMode being:"
1028                                                                                                               "\t1: max number of CTUs per slice segment"
1029                                                                                                               "\t2: max number of bytes per slice segment"
1030                                                                                                               "\t3: max number of tiles per slice segment")
1031  ("LFCrossSliceBoundaryFlag",                        m_bLFCrossSliceBoundaryFlag,                       true)
1032
1033  ("ConstrainedIntraPred",                            m_bUseConstrainedIntraPred,                       false, "Constrained Intra Prediction")
1034  ("FastUDIUseMPMEnabled",                            m_bFastUDIUseMPMEnabled,                           true, "If enabled, adapt intra direction search, accounting for MPM")
1035  ("FastMEForGenBLowDelayEnabled",                    m_bFastMEForGenBLowDelayEnabled,                   true, "If enabled use a fast ME for generalised B Low Delay slices")
1036  ("UseBLambdaForNonKeyLowDelayPictures",             m_bUseBLambdaForNonKeyLowDelayPictures,            true, "Enables use of B-Lambda for non-key low-delay pictures")
1037  ("PCMEnabledFlag",                                  m_usePCM,                                         false)
1038  ("PCMLog2MaxSize",                                  m_pcmLog2MaxSize,                                    5u)
1039  ("PCMLog2MinSize",                                  m_uiPCMLog2MinSize,                                  3u)
1040
1041  ("PCMInputBitDepthFlag",                            m_bPCMInputBitDepthFlag,                           true)
1042  ("PCMFilterDisableFlag",                            m_bPCMFilterDisableFlag,                          false)
1043  ("IntraReferenceSmoothing",                         m_enableIntraReferenceSmoothing,                   true, "0: Disable use of intra reference smoothing. 1: Enable use of intra reference smoothing (not valid in V1 profiles)")
1044  ("WeightedPredP,-wpP",                              m_useWeightedPred,                                false, "Use weighted prediction in P slices")
1045  ("WeightedPredB,-wpB",                              m_useWeightedBiPred,                              false, "Use weighted (bidirectional) prediction in B slices")
1046  ("Log2ParallelMergeLevel",                          m_log2ParallelMergeLevel,                            2u, "Parallel merge estimation region")
1047    //deprecated copies of renamed tile parameters
1048  ("UniformSpacingIdc",                               m_tileUniformSpacingFlag,                         false,      "deprecated alias of TileUniformSpacing")
1049  ("ColumnWidthArray",                                cfg_ColumnWidth,                        cfg_ColumnWidth, "deprecated alias of TileColumnWidthArray")
1050  ("RowHeightArray",                                  cfg_RowHeight,                            cfg_RowHeight, "deprecated alias of TileRowHeightArray")
1051
1052  ("TileUniformSpacing",                              m_tileUniformSpacingFlag,                         false,      "Indicates that tile columns and rows are distributed uniformly")
1053  ("NumTileColumnsMinus1",                            m_numTileColumnsMinus1,                               0,          "Number of tile columns in a picture minus 1")
1054  ("NumTileRowsMinus1",                               m_numTileRowsMinus1,                                  0,          "Number of rows in a picture minus 1")
1055  ("TileColumnWidthArray",                            cfg_ColumnWidth,                        cfg_ColumnWidth, "Array containing tile column width values in units of CTU")
1056  ("TileRowHeightArray",                              cfg_RowHeight,                            cfg_RowHeight, "Array containing tile row height values in units of CTU")
1057  ("LFCrossTileBoundaryFlag",                         m_bLFCrossTileBoundaryFlag,                        true, "1: cross-tile-boundary loop filtering. 0:non-cross-tile-boundary loop filtering")
1058  ("WaveFrontSynchro",                                m_iWaveFrontSynchro,                                  0, "0: no synchro; 1 synchro with top-right-right")
1059  ("ScalingList",                                     m_useScalingListId,                    SCALING_LIST_OFF, "0/off: no scaling list, 1/default: default scaling lists, 2/file: scaling lists specified in ScalingListFile")
1060  ("ScalingListFile",                                 cfg_ScalingListFile,                         string(""), "Scaling list file name. Use an empty string to produce help.")
1061  ("SignHideFlag,-SBH",                               m_signHideFlag,                                    true)
1062  ("MaxNumMergeCand",                                 m_maxNumMergeCand,                                   5u, "Maximum number of merge candidates")
1063  /* Misc. */
1064  ("SEIDecodedPictureHash",                           m_decodedPictureHashSEIEnabled,                       0, "Control generation of decode picture hash SEI messages\n"
1065                                                                                                               "\t3: checksum\n"
1066                                                                                                               "\t2: CRC\n"
1067                                                                                                               "\t1: use MD5\n"
1068                                                                                                               "\t0: disable")
1069  ("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")
1070  ("FEN",                                             m_bUseFastEnc,                                    false, "fast encoder setting")
1071  ("ECU",                                             m_bUseEarlyCU,                                    false, "Early CU setting")
1072  ("FDM",                                             m_useFastDecisionForMerge,                         true, "Fast decision for Merge RD Cost")
1073  ("CFM",                                             m_bUseCbfFastMode,                                false, "Cbf fast mode setting")
1074  ("ESD",                                             m_useEarlySkipDetection,                          false, "Early SKIP detection setting")
1075  ( "RateControl",                                    m_RCEnableRateControl,                            false, "Rate control: enable rate control" )
1076  ( "TargetBitrate",                                  m_RCTargetBitrate,                                    0, "Rate control: target bit-rate" )
1077  ( "KeepHierarchicalBit",                            m_RCKeepHierarchicalBit,                              0, "Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation" )
1078  ( "LCULevelRateControl",                            m_RCLCULevelRC,                                    true, "Rate control: true: CTU level RC; false: picture level RC" )
1079  ( "RCLCUSeparateModel",                             m_RCUseLCUSeparateModel,                           true, "Rate control: use CTU level separate R-lambda model" )
1080  ( "InitialQP",                                      m_RCInitialQP,                                        0, "Rate control: initial QP" )
1081  ( "RCForceIntraQP",                                 m_RCForceIntraQP,                                 false, "Rate control: force intra QP to be equal to initial QP" )
1082
1083#if NH_MV
1084// A lot of this stuff could should actually be derived by the encoder.
1085  // VPS VUI
1086  ("VpsVuiPresentFlag"           , m_vpsVuiPresentFlag           , false                                           , "VpsVuiPresentFlag           ")
1087  ("CrossLayerPicTypeAlignedFlag", m_crossLayerPicTypeAlignedFlag, false                                           , "CrossLayerPicTypeAlignedFlag")  // Could actually be derived by the encoder
1088  ("CrossLayerIrapAlignedFlag"   , m_crossLayerIrapAlignedFlag   , false                                           , "CrossLayerIrapAlignedFlag   ")  // Could actually be derived by the encoder
1089  ("AllLayersIdrAlignedFlag"     , m_allLayersIdrAlignedFlag     , false                                           , "CrossLayerIrapAlignedFlag   ")  // Could actually be derived by the encoder
1090  ("BitRatePresentVpsFlag"       , m_bitRatePresentVpsFlag       , false                                           , "BitRatePresentVpsFlag       ")
1091  ("PicRatePresentVpsFlag"       , m_picRatePresentVpsFlag       , false                                           , "PicRatePresentVpsFlag       ")
1092  ("BitRatePresentFlag"          , m_bitRatePresentFlag          , BoolAry1d(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "BitRatePresentFlag per sub layer for the N-th layer set")
1093  ("PicRatePresentFlag"          , m_picRatePresentFlag          , BoolAry1d(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "PicRatePresentFlag per sub layer for the N-th layer set")
1094  ("AvgBitRate"                  , m_avgBitRate                  , std::vector< Int  >(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "AvgBitRate         per sub layer for the N-th layer set")
1095  ("MaxBitRate"                  , m_maxBitRate                  , std::vector< Int  >(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "MaxBitRate         per sub layer for the N-th layer set")
1096  ("ConstantPicRateIdc"          , m_constantPicRateIdc          , std::vector< Int  >(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "ConstantPicRateIdc per sub layer for the N-th layer set")
1097  ("AvgPicRate"                  , m_avgPicRate                  , std::vector< Int  >(1,0)  ,MAX_VPS_OP_SETS_PLUS1, "AvgPicRate         per sub layer for the N-th layer set")
1098  ("TilesNotInUseFlag"            , m_tilesNotInUseFlag            , true                                          , "TilesNotInUseFlag            ")
1099  ("TilesInUseFlag"               , m_tilesInUseFlag               , BoolAry1d(1,false)                   , "TilesInUseFlag               ")
1100  ("LoopFilterNotAcrossTilesFlag" , m_loopFilterNotAcrossTilesFlag , BoolAry1d(1,false)                  , "LoopFilterNotAcrossTilesFlag ")
1101  ("WppNotInUseFlag"              , m_wppNotInUseFlag              , true                                          , "WppNotInUseFlag              ")
1102  ("WppInUseFlag"                 , m_wppInUseFlag                 , BoolAry1d(1,0)                      , "WppInUseFlag                 ")
1103  ("TileBoundariesAlignedFlag"   , m_tileBoundariesAlignedFlag   , BoolAry1d(1,0)  ,MAX_NUM_LAYERS       , "TileBoundariesAlignedFlag    per direct reference for the N-th layer")
1104  ("IlpRestrictedRefLayersFlag"  , m_ilpRestrictedRefLayersFlag  , false                                           , "IlpRestrictedRefLayersFlag")
1105  ("MinSpatialSegmentOffsetPlus1", m_minSpatialSegmentOffsetPlus1, std::vector< Int  >(1,0)  ,MAX_NUM_LAYERS       , "MinSpatialSegmentOffsetPlus1 per direct reference for the N-th layer")
1106  ("CtuBasedOffsetEnabledFlag"   , m_ctuBasedOffsetEnabledFlag   , BoolAry1d(1,0)  ,MAX_NUM_LAYERS       , "CtuBasedOffsetEnabledFlag    per direct reference for the N-th layer")
1107  ("MinHorizontalCtuOffsetPlus1" , m_minHorizontalCtuOffsetPlus1 , std::vector< Int  >(1,0)  ,MAX_NUM_LAYERS       , "MinHorizontalCtuOffsetPlus1  per direct reference for the N-th layer")
1108  ("SingleLayerForNonIrapFlag", m_singleLayerForNonIrapFlag, false                                          , "SingleLayerForNonIrapFlag")
1109  ("HigherLayerIrapSkipFlag"  , m_higherLayerIrapSkipFlag  , false                                          , "HigherLayerIrapSkipFlag  ")
1110#endif
1111
1112  ("TransquantBypassEnableFlag",                      m_TransquantBypassEnableFlag,                     false, "transquant_bypass_enable_flag indicator in PPS")
1113  ("CUTransquantBypassFlagForce",                     m_CUTransquantBypassFlagForce,                    false, "Force transquant bypass mode, when transquant_bypass_enable_flag is enabled")
1114  ("CostMode",                                        m_costMode,                         COST_STANDARD_LOSSY, "Use alternative cost functions: choose between 'lossy', 'sequence_level_lossless', 'lossless' (which forces QP to " MACRO_TO_STRING(LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP) ") and 'mixed_lossless_lossy' (which used QP'=" MACRO_TO_STRING(LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME) " for pre-estimates of transquant-bypass blocks).")
1115  ("RecalculateQPAccordingToLambda",                  m_recalculateQPAccordingToLambda,                 false, "Recalculate QP values according to lambda values. Do not suggest to be enabled in all intra case")
1116  ("StrongIntraSmoothing,-sis",                       m_useStrongIntraSmoothing,                         true, "Enable strong intra smoothing for 32x32 blocks")
1117  ("SEIActiveParameterSets",                          m_activeParameterSetsSEIEnabled,                      0, "Enable generation of active parameter sets SEI messages")
1118  ("VuiParametersPresent,-vui",                       m_vuiParametersPresentFlag,                       false, "Enable generation of vui_parameters()")
1119  ("AspectRatioInfoPresent",                          m_aspectRatioInfoPresentFlag,                     false, "Signals whether aspect_ratio_idc is present")
1120  ("AspectRatioIdc",                                  m_aspectRatioIdc,                                     0, "aspect_ratio_idc")
1121  ("SarWidth",                                        m_sarWidth,                                           0, "horizontal size of the sample aspect ratio")
1122  ("SarHeight",                                       m_sarHeight,                                          0, "vertical size of the sample aspect ratio")
1123  ("OverscanInfoPresent",                             m_overscanInfoPresentFlag,                        false, "Indicates whether conformant decoded pictures are suitable for display using overscan\n")
1124  ("OverscanAppropriate",                             m_overscanAppropriateFlag,                        false, "Indicates whether conformant decoded pictures are suitable for display using overscan\n")
1125  ("VideoSignalTypePresent",                          m_videoSignalTypePresentFlag,                     false, "Signals whether video_format, video_full_range_flag, and colour_description_present_flag are present")
1126  ("VideoFormat",                                     m_videoFormat,                                        5, "Indicates representation of pictures")
1127  ("VideoFullRange",                                  m_videoFullRangeFlag,                             false, "Indicates the black level and range of luma and chroma signals")
1128  ("ColourDescriptionPresent",                        m_colourDescriptionPresentFlag,                   false, "Signals whether colour_primaries, transfer_characteristics and matrix_coefficients are present")
1129  ("ColourPrimaries",                                 m_colourPrimaries,                                    2, "Indicates chromaticity coordinates of the source primaries")
1130  ("TransferCharacteristics",                         m_transferCharacteristics,                            2, "Indicates the opto-electronic transfer characteristics of the source")
1131  ("MatrixCoefficients",                              m_matrixCoefficients,                                 2, "Describes the matrix coefficients used in deriving luma and chroma from RGB primaries")
1132  ("ChromaLocInfoPresent",                            m_chromaLocInfoPresentFlag,                       false, "Signals whether chroma_sample_loc_type_top_field and chroma_sample_loc_type_bottom_field are present")
1133  ("ChromaSampleLocTypeTopField",                     m_chromaSampleLocTypeTopField,                        0, "Specifies the location of chroma samples for top field")
1134  ("ChromaSampleLocTypeBottomField",                  m_chromaSampleLocTypeBottomField,                     0, "Specifies the location of chroma samples for bottom field")
1135  ("NeutralChromaIndication",                         m_neutralChromaIndicationFlag,                    false, "Indicates that the value of all decoded chroma samples is equal to 1<<(BitDepthCr-1)")
1136  ("DefaultDisplayWindowFlag",                        m_defaultDisplayWindowFlag,                       false, "Indicates the presence of the Default Window parameters")
1137  ("DefDispWinLeftOffset",                            m_defDispWinLeftOffset,                               0, "Specifies the left offset of the default display window from the conformance window")
1138  ("DefDispWinRightOffset",                           m_defDispWinRightOffset,                              0, "Specifies the right offset of the default display window from the conformance window")
1139  ("DefDispWinTopOffset",                             m_defDispWinTopOffset,                                0, "Specifies the top offset of the default display window from the conformance window")
1140  ("DefDispWinBottomOffset",                          m_defDispWinBottomOffset,                             0, "Specifies the bottom offset of the default display window from the conformance window")
1141  ("FrameFieldInfoPresentFlag",                       m_frameFieldInfoPresentFlag,                      false, "Indicates that pic_struct and field coding related values are present in picture timing SEI messages")
1142  ("PocProportionalToTimingFlag",                     m_pocProportionalToTimingFlag,                    false, "Indicates that the POC value is proportional to the output time w.r.t. first picture in CVS")
1143  ("NumTicksPocDiffOneMinus1",                        m_numTicksPocDiffOneMinus1,                           0, "Number of ticks minus 1 that for a POC difference of one")
1144  ("BitstreamRestriction",                            m_bitstreamRestrictionFlag,                       false, "Signals whether bitstream restriction parameters are present")
1145  ("TilesFixedStructure",                             m_tilesFixedStructureFlag,                        false, "Indicates that each active picture parameter set has the same values of the syntax elements related to tiles")
1146  ("MotionVectorsOverPicBoundaries",                  m_motionVectorsOverPicBoundariesFlag,             false, "Indicates that no samples outside the picture boundaries are used for inter prediction")
1147  ("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")
1148  ("MaxBitsPerMinCuDenom",                            m_maxBitsPerMinCuDenom,                               1, "Indicates an upper bound for the number of bits of coding_unit() data")
1149  ("Log2MaxMvLengthHorizontal",                       m_log2MaxMvLengthHorizontal,                         15, "Indicate the maximum absolute value of a decoded horizontal MV component in quarter-pel luma units")
1150  ("Log2MaxMvLengthVertical",                         m_log2MaxMvLengthVertical,                           15, "Indicate the maximum absolute value of a decoded vertical MV component in quarter-pel luma units")
1151  ("SEIRecoveryPoint",                                m_recoveryPointSEIEnabled,                            0, "Control generation of recovery point SEI messages")
1152  ("SEIBufferingPeriod",                              m_bufferingPeriodSEIEnabled,                          0, "Control generation of buffering period SEI messages")
1153  ("SEIPictureTiming",                                m_pictureTimingSEIEnabled,                            0, "Control generation of picture timing SEI messages")
1154  ("SEIToneMappingInfo",                              m_toneMappingInfoSEIEnabled,                      false, "Control generation of Tone Mapping SEI messages")
1155  ("SEIToneMapId",                                    m_toneMapId,                                          0, "Specifies Id of Tone Mapping SEI message for a given session")
1156  ("SEIToneMapCancelFlag",                            m_toneMapCancelFlag,                              false, "Indicates that Tone Mapping SEI message cancels the persistence or follows")
1157  ("SEIToneMapPersistenceFlag",                       m_toneMapPersistenceFlag,                          true, "Specifies the persistence of the Tone Mapping SEI message")
1158  ("SEIToneMapCodedDataBitDepth",                     m_toneMapCodedDataBitDepth,                           8, "Specifies Coded Data BitDepth of Tone Mapping SEI messages")
1159  ("SEIToneMapTargetBitDepth",                        m_toneMapTargetBitDepth,                              8, "Specifies Output BitDepth of Tone mapping function")
1160  ("SEIToneMapModelId",                               m_toneMapModelId,                                     0, "Specifies Model utilized for mapping coded data into target_bit_depth range\n"
1161                                                                                                               "\t0:  linear mapping with clipping\n"
1162                                                                                                               "\t1:  sigmoidal mapping\n"
1163                                                                                                               "\t2:  user-defined table mapping\n"
1164                                                                                                               "\t3:  piece-wise linear mapping\n"
1165                                                                                                               "\t4:  luminance dynamic range information ")
1166  ("SEIToneMapMinValue",                              m_toneMapMinValue,                                    0, "Specifies the minimum value in mode 0")
1167  ("SEIToneMapMaxValue",                              m_toneMapMaxValue,                                 1023, "Specifies the maximum value in mode 0")
1168  ("SEIToneMapSigmoidMidpoint",                       m_sigmoidMidpoint,                                  512, "Specifies the centre point in mode 1")
1169  ("SEIToneMapSigmoidWidth",                          m_sigmoidWidth,                                     960, "Specifies the distance between 5% and 95% values of the target_bit_depth in mode 1")
1170  ("SEIToneMapStartOfCodedInterval",                  cfg_startOfCodedInterval,      cfg_startOfCodedInterval, "Array of user-defined mapping table")
1171  ("SEIToneMapNumPivots",                             m_numPivots,                                          0, "Specifies the number of pivot points in mode 3")
1172  ("SEIToneMapCodedPivotValue",                       cfg_codedPivotValue,                cfg_codedPivotValue, "Array of pivot point")
1173  ("SEIToneMapTargetPivotValue",                      cfg_targetPivotValue,              cfg_targetPivotValue, "Array of pivot point")
1174  ("SEIToneMapCameraIsoSpeedIdc",                     m_cameraIsoSpeedIdc,                                  0, "Indicates the camera ISO speed for daylight illumination")
1175  ("SEIToneMapCameraIsoSpeedValue",                   m_cameraIsoSpeedValue,                              400, "Specifies the camera ISO speed for daylight illumination of Extended_ISO")
1176  ("SEIToneMapExposureIndexIdc",                      m_exposureIndexIdc,                                   0, "Indicates the exposure index setting of the camera")
1177  ("SEIToneMapExposureIndexValue",                    m_exposureIndexValue,                               400, "Specifies the exposure index setting of the camera of Extended_ISO")
1178  ("SEIToneMapExposureCompensationValueSignFlag",     m_exposureCompensationValueSignFlag,               false, "Specifies the sign of ExposureCompensationValue")
1179  ("SEIToneMapExposureCompensationValueNumerator",    m_exposureCompensationValueNumerator,                 0, "Specifies the numerator of ExposureCompensationValue")
1180  ("SEIToneMapExposureCompensationValueDenomIdc",     m_exposureCompensationValueDenomIdc,                  2, "Specifies the denominator of ExposureCompensationValue")
1181  ("SEIToneMapRefScreenLuminanceWhite",               m_refScreenLuminanceWhite,                          350, "Specifies reference screen brightness setting in units of candela per square metre")
1182  ("SEIToneMapExtendedRangeWhiteLevel",               m_extendedRangeWhiteLevel,                          800, "Indicates the luminance dynamic range")
1183  ("SEIToneMapNominalBlackLevelLumaCodeValue",        m_nominalBlackLevelLumaCodeValue,                    16, "Specifies luma sample value of the nominal black level assigned decoded pictures")
1184  ("SEIToneMapNominalWhiteLevelLumaCodeValue",        m_nominalWhiteLevelLumaCodeValue,                   235, "Specifies luma sample value of the nominal white level assigned decoded pictures")
1185  ("SEIToneMapExtendedWhiteLevelLumaCodeValue",       m_extendedWhiteLevelLumaCodeValue,                  300, "Specifies luma sample value of the extended dynamic range assigned decoded pictures")
1186  ("SEIChromaSamplingFilterHint",                     m_chromaSamplingFilterSEIenabled,                 false, "Control generation of the chroma sampling filter hint SEI message")
1187  ("SEIChromaSamplingHorizontalFilterType",           m_chromaSamplingHorFilterIdc,                         2, "Defines the Index of the chroma sampling horizontal filter\n"
1188                                                                                                               "\t0: unspecified  - Chroma filter is unknown or is determined by the application"
1189                                                                                                               "\t1: User-defined - Filter coefficients are specified in the chroma sampling filter hint SEI message"
1190                                                                                                               "\t2: Standards-defined - ITU-T Rec. T.800 | ISO/IEC15444-1, 5/3 filter")
1191  ("SEIChromaSamplingVerticalFilterType",             m_chromaSamplingVerFilterIdc,                         2, "Defines the Index of the chroma sampling vertical filter\n"
1192                                                                                                               "\t0: unspecified  - Chroma filter is unknown or is determined by the application"
1193                                                                                                               "\t1: User-defined - Filter coefficients are specified in the chroma sampling filter hint SEI message"
1194                                                                                                               "\t2: Standards-defined - ITU-T Rec. T.800 | ISO/IEC15444-1, 5/3 filter")
1195  ("SEIFramePacking",                                 m_framePackingSEIEnabled,                             0, "Control generation of frame packing SEI messages")
1196  ("SEIFramePackingType",                             m_framePackingSEIType,                                0, "Define frame packing arrangement\n"
1197                                                                                                               "\t3: side by side - frames are displayed horizontally\n"
1198                                                                                                               "\t4: top bottom - frames are displayed vertically\n"
1199                                                                                                               "\t5: frame alternation - one frame is alternated with the other")
1200  ("SEIFramePackingId",                               m_framePackingSEIId,                                  0, "Id of frame packing SEI message for a given session")
1201  ("SEIFramePackingQuincunx",                         m_framePackingSEIQuincunx,                            0, "Indicate the presence of a Quincunx type video frame")
1202  ("SEIFramePackingInterpretation",                   m_framePackingSEIInterpretation,                      0, "Indicate the interpretation of the frame pair\n"
1203                                                                                                               "\t0: unspecified\n"
1204                                                                                                               "\t1: stereo pair, frame0 represents left view\n"
1205                                                                                                               "\t2: stereo pair, frame0 represents right view")
1206  ("SEISegmentedRectFramePacking",                    m_segmentedRectFramePackingSEIEnabled,                0, "Controls generation of segmented rectangular frame packing SEI messages")
1207  ("SEISegmentedRectFramePackingCancel",              m_segmentedRectFramePackingSEICancel,             false, "If equal to 1, cancels the persistence of any previous SRFPA SEI message")
1208  ("SEISegmentedRectFramePackingType",                m_segmentedRectFramePackingSEIType,                   0, "Specifies the arrangement of the frames in the reconstructed picture")
1209  ("SEISegmentedRectFramePackingPersistence",         m_segmentedRectFramePackingSEIPersistence,        false, "If equal to 0, the SEI applies to the current frame only")
1210  ("SEIDisplayOrientation",                           m_displayOrientationSEIAngle,                         0, "Control generation of display orientation SEI messages\n"
1211                                                                                                               "\tN: 0 < N < (2^16 - 1) enable display orientation SEI message with anticlockwise_rotation = N and display_orientation_repetition_period = 1\n"
1212                                                                                                               "\t0: disable")
1213  ("SEITemporalLevel0Index",                          m_temporalLevel0IndexSEIEnabled,                      0, "Control generation of temporal level 0 index SEI messages")
1214  ("SEIGradualDecodingRefreshInfo",                   m_gradualDecodingRefreshInfoEnabled,                  0, "Control generation of gradual decoding refresh information SEI message")
1215  ("SEINoDisplay",                                    m_noDisplaySEITLayer,                                 0, "Control generation of no display SEI message\n"
1216                                                                                                               "\tN: 0 < N enable no display SEI message for temporal layer N or higher\n"
1217                                                                                                               "\t0: disable")
1218  ("SEIDecodingUnitInfo",                             m_decodingUnitInfoSEIEnabled,                         0, "Control generation of decoding unit information SEI message.")
1219  ("SEISOPDescription",                               m_SOPDescriptionSEIEnabled,                           0, "Control generation of SOP description SEI messages")
1220  ("SEIScalableNesting",                              m_scalableNestingSEIEnabled,                          0, "Control generation of scalable nesting SEI messages")
1221  ("SEITempMotionConstrainedTileSets",                m_tmctsSEIEnabled,                                false, "Control generation of temporal motion constrained tile sets SEI message")
1222  ("SEITimeCodeEnabled",                              m_timeCodeSEIEnabled,                             false, "Control generation of time code information SEI message")
1223  ("SEITimeCodeNumClockTs",                           m_timeCodeSEINumTs,                                   0, "Number of clock time sets [0..3]")
1224  ("SEITimeCodeTimeStampFlag",                        cfg_timeCodeSeiTimeStampFlag,          cfg_timeCodeSeiTimeStampFlag,         "Time stamp flag associated to each time set")
1225  ("SEITimeCodeFieldBasedFlag",                       cfg_timeCodeSeiNumUnitFieldBasedFlag,  cfg_timeCodeSeiNumUnitFieldBasedFlag, "Field based flag associated to each time set")
1226  ("SEITimeCodeCountingType",                         cfg_timeCodeSeiCountingType,           cfg_timeCodeSeiCountingType,          "Counting type associated to each time set")
1227  ("SEITimeCodeFullTsFlag",                           cfg_timeCodeSeiFullTimeStampFlag,      cfg_timeCodeSeiFullTimeStampFlag,     "Full time stamp flag associated to each time set")
1228  ("SEITimeCodeDiscontinuityFlag",                    cfg_timeCodeSeiDiscontinuityFlag,      cfg_timeCodeSeiDiscontinuityFlag,     "Discontinuity flag associated to each time set")
1229  ("SEITimeCodeCntDroppedFlag",                       cfg_timeCodeSeiCntDroppedFlag,         cfg_timeCodeSeiCntDroppedFlag,        "Counter dropped flag associated to each time set")
1230  ("SEITimeCodeNumFrames",                            cfg_timeCodeSeiNumberOfFrames,         cfg_timeCodeSeiNumberOfFrames,        "Number of frames associated to each time set")
1231  ("SEITimeCodeSecondsValue",                         cfg_timeCodeSeiSecondsValue,           cfg_timeCodeSeiSecondsValue,          "Seconds value for each time set")
1232  ("SEITimeCodeMinutesValue",                         cfg_timeCodeSeiMinutesValue,           cfg_timeCodeSeiMinutesValue,          "Minutes value for each time set")
1233  ("SEITimeCodeHoursValue",                           cfg_timeCodeSeiHoursValue,             cfg_timeCodeSeiHoursValue,            "Hours value for each time set")
1234  ("SEITimeCodeSecondsFlag",                          cfg_timeCodeSeiSecondsFlag,            cfg_timeCodeSeiSecondsFlag,           "Flag to signal seconds value presence in each time set")
1235  ("SEITimeCodeMinutesFlag",                          cfg_timeCodeSeiMinutesFlag,            cfg_timeCodeSeiMinutesFlag,           "Flag to signal minutes value presence in each time set")
1236  ("SEITimeCodeHoursFlag",                            cfg_timeCodeSeiHoursFlag,              cfg_timeCodeSeiHoursFlag,             "Flag to signal hours value presence in each time set")
1237  ("SEITimeCodeOffsetLength",                         cfg_timeCodeSeiTimeOffsetLength,       cfg_timeCodeSeiTimeOffsetLength,      "Time offset length associated to each time set")
1238  ("SEITimeCodeTimeOffset",                           cfg_timeCodeSeiTimeOffsetValue,        cfg_timeCodeSeiTimeOffsetValue,       "Time offset associated to each time set")
1239  ("SEIKneeFunctionInfo",                             m_kneeSEIEnabled,                                 false, "Control generation of Knee function SEI messages")
1240  ("SEIKneeFunctionId",                               m_kneeSEIId,                                          0, "Specifies Id of Knee function SEI message for a given session")
1241  ("SEIKneeFunctionCancelFlag",                       m_kneeSEICancelFlag,                              false, "Indicates that Knee function SEI message cancels the persistence or follows")
1242  ("SEIKneeFunctionPersistenceFlag",                  m_kneeSEIPersistenceFlag,                          true, "Specifies the persistence of the Knee function SEI message")
1243  ("SEIKneeFunctionInputDrange",                      m_kneeSEIInputDrange,                              1000, "Specifies the peak luminance level for the input picture of Knee function SEI messages")
1244  ("SEIKneeFunctionInputDispLuminance",               m_kneeSEIInputDispLuminance,                        100, "Specifies the expected display brightness for the input picture of Knee function SEI messages")
1245  ("SEIKneeFunctionOutputDrange",                     m_kneeSEIOutputDrange,                             4000, "Specifies the peak luminance level for the output picture of Knee function SEI messages")
1246  ("SEIKneeFunctionOutputDispLuminance",              m_kneeSEIOutputDispLuminance,                       800, "Specifies the expected display brightness for the output picture of Knee function SEI messages")
1247  ("SEIKneeFunctionNumKneePointsMinus1",              m_kneeSEINumKneePointsMinus1,                         2, "Specifies the number of knee points - 1")
1248  ("SEIKneeFunctionInputKneePointValue",              cfg_kneeSEIInputKneePointValue,   cfg_kneeSEIInputKneePointValue, "Array of input knee point")
1249  ("SEIKneeFunctionOutputKneePointValue",             cfg_kneeSEIOutputKneePointValue, cfg_kneeSEIOutputKneePointValue, "Array of output knee point")
1250  ("SEIMasteringDisplayColourVolume",                 m_masteringDisplay.colourVolumeSEIEnabled,         false, "Control generation of mastering display colour volume SEI messages")
1251  ("SEIMasteringDisplayMaxLuminance",                 m_masteringDisplay.maxLuminance,                  10000u, "Specifies the mastering display maximum luminance value in units of 1/10000 candela per square metre (32-bit code value)")
1252  ("SEIMasteringDisplayMinLuminance",                 m_masteringDisplay.minLuminance,                      0u, "Specifies the mastering display minimum luminance value in units of 1/10000 candela per square metre (32-bit code value)")
1253  ("SEIMasteringDisplayPrimaries",                    cfg_DisplayPrimariesCode,       cfg_DisplayPrimariesCode, "Mastering display primaries for all three colour planes in CIE xy coordinates in increments of 1/50000 (results in the ranges 0 to 50000 inclusive)")
1254  ("SEIMasteringDisplayWhitePoint",                   cfg_DisplayWhitePointCode,     cfg_DisplayWhitePointCode, "Mastering display white point CIE xy coordinates in normalised increments of 1/50000 (e.g. 0.333 = 16667)")
1255#if NH_MV
1256  ("SubBitstreamPropSEIEnabled",                      m_subBistreamPropSEIEnabled,    false                     ,"Enable signaling of sub-bitstream property SEI message")
1257  ("SEISubBitstreamNumAdditionalSubStreams",          m_sbPropNumAdditionalSubStreams,0                         ,"Number of substreams for which additional information is signalled")
1258  ("SEISubBitstreamSubBitstreamMode",                 m_sbPropSubBitstreamMode,       std::vector< Int  >(1,0)  ,"Specifies mode of generation of the i-th sub-bitstream (0 or 1)")
1259  ("SEISubBitstreamOutputLayerSetIdxToVps",           m_sbPropOutputLayerSetIdxToVps, std::vector< Int  >(1,0)  ,"Specifies output layer set index of the i-th sub-bitstream ")
1260  ("SEISubBitstreamHighestSublayerId",                m_sbPropHighestSublayerId,      std::vector< Int  >(1,0)  ,"Specifies highest TemporalId of the i-th sub-bitstream")
1261  ("SEISubBitstreamAvgBitRate",                       m_sbPropAvgBitRate,             std::vector< Int  >(1,0)  ,"Specifies average bit rate of the i-th sub-bitstream")
1262  ("SEISubBitstreamMaxBitRate",                       m_sbPropMaxBitRate,             std::vector< Int  >(1,0)  ,"Specifies maximum bit rate of the i-th sub-bitstream")
1263
1264  ("OutputVpsInfo",                                   m_outputVpsInfo,                false                     ,"Output information about the layer dependencies and layer sets")
1265#endif
1266   
1267  ;
1268
1269#if NH_MV
1270  // parse coding structure
1271  for( Int k = 0; k < MAX_NUM_LAYERS; k++ )
1272  {
1273    m_GOPListMvc.push_back( new GOPEntry[MAX_GOP + 1] );
1274    if( k == 0 )
1275    {
1276      m_GOPListMvc[0][0].m_sliceType = 'I'; 
1277      for( Int i = 1; i < MAX_GOP + 1; i++ ) 
1278      {
1279        std::ostringstream cOSS;
1280        cOSS<<"Frame"<<i;
1281        opts.addOptions()( cOSS.str(), m_GOPListMvc[k][i-1], GOPEntry() );
1282        if ( i != 1 )
1283        {
1284          opts.opt_list.back()->opt->opt_duplicate = true; 
1285        }       
1286      }
1287    }
1288    else
1289    {
1290      std::ostringstream cOSS1;
1291      cOSS1<<"FrameI"<<"_l"<<k;
1292
1293      opts.addOptions()(cOSS1.str(), m_GOPListMvc[k][MAX_GOP], GOPEntry());
1294      if ( k > 1 )
1295      {
1296        opts.opt_list.back()->opt->opt_duplicate = true; 
1297      }       
1298
1299
1300  for(Int i=1; i<MAX_GOP+1; i++)
1301  {
1302        std::ostringstream cOSS2;
1303        cOSS2<<"Frame"<<i<<"_l"<<k;
1304        opts.addOptions()(cOSS2.str(), m_GOPListMvc[k][i-1], GOPEntry());
1305        if ( i != 1 || k > 0 )
1306        {
1307          opts.opt_list.back()->opt->opt_duplicate = true; 
1308        }       
1309      }
1310    }
1311  }
1312#else
1313  for(Int i=1; i<MAX_GOP+1; i++)
1314  {
1315    std::ostringstream cOSS;
1316    cOSS<<"Frame"<<i;
1317    opts.addOptions()(cOSS.str(), m_GOPList[i-1], GOPEntry());
1318  }
1319#endif
1320  po::setDefaults(opts);
1321  po::ErrorReporter err;
1322  const list<const Char*>& argv_unhandled = po::scanArgv(opts, argc, (const Char**) argv, err);
1323
1324  for (list<const Char*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
1325  {
1326    fprintf(stderr, "Unhandled argument ignored: `%s'\n", *it);
1327  }
1328
1329  if (argc == 1 || do_help)
1330  {
1331    /* argc == 1: no options have been specified */
1332    po::doHelp(cout, opts);
1333    return false;
1334  }
1335
1336  if (err.is_errored)
1337  {
1338    if (!warnUnknowParameter)
1339    {
1340      /* error report has already been printed on stderr */
1341      return false;
1342    }
1343  }
1344
1345  /*
1346   * Set any derived parameters
1347   */
1348  /* convert std::string to c string for compatability */
1349#if !NH_MV
1350  m_pchInputFile = cfg_InputFile.empty() ? NULL : strdup(cfg_InputFile.c_str());
1351#endif
1352  m_pchBitstreamFile = cfg_BitstreamFile.empty() ? NULL : strdup(cfg_BitstreamFile.c_str());
1353#if !NH_MV
1354  m_pchReconFile = cfg_ReconFile.empty() ? NULL : strdup(cfg_ReconFile.c_str());
1355#endif
1356  m_pchdQPFile = cfg_dQPFile.empty() ? NULL : strdup(cfg_dQPFile.c_str());
1357
1358  if(m_isField)
1359  {
1360    //Frame height
1361    m_iSourceHeightOrg = m_iSourceHeight;
1362    //Field height
1363    m_iSourceHeight = m_iSourceHeight >> 1;
1364    //number of fields to encode
1365    m_framesToBeEncoded *= 2;
1366  }
1367
1368  if( !m_tileUniformSpacingFlag && m_numTileColumnsMinus1 > 0 )
1369  {
1370    if (cfg_ColumnWidth.values.size() > m_numTileColumnsMinus1)
1371    {
1372      printf( "The number of columns whose width are defined is larger than the allowed number of columns.\n" );
1373      exit( EXIT_FAILURE );
1374    }
1375    else if (cfg_ColumnWidth.values.size() < m_numTileColumnsMinus1)
1376    {
1377      printf( "The width of some columns is not defined.\n" );
1378      exit( EXIT_FAILURE );
1379    }
1380    else
1381    {
1382      m_tileColumnWidth.resize(m_numTileColumnsMinus1);
1383      for(UInt i=0; i<cfg_ColumnWidth.values.size(); i++)
1384      {
1385        m_tileColumnWidth[i]=cfg_ColumnWidth.values[i];
1386      }
1387    }
1388  }
1389  else
1390  {
1391    m_tileColumnWidth.clear();
1392  }
1393
1394  if( !m_tileUniformSpacingFlag && m_numTileRowsMinus1 > 0 )
1395  {
1396    if (cfg_RowHeight.values.size() > m_numTileRowsMinus1)
1397    {
1398      printf( "The number of rows whose height are defined is larger than the allowed number of rows.\n" );
1399      exit( EXIT_FAILURE );
1400    }
1401    else if (cfg_RowHeight.values.size() < m_numTileRowsMinus1)
1402    {
1403      printf( "The height of some rows is not defined.\n" );
1404      exit( EXIT_FAILURE );
1405    }
1406    else
1407    {
1408      m_tileRowHeight.resize(m_numTileRowsMinus1);
1409      for(UInt i=0; i<cfg_RowHeight.values.size(); i++)
1410      {
1411        m_tileRowHeight[i]=cfg_RowHeight.values[i];
1412      }
1413    }
1414  }
1415  else
1416  {
1417    m_tileRowHeight.clear();
1418  }
1419
1420  m_scalingListFile = cfg_ScalingListFile.empty() ? NULL : strdup(cfg_ScalingListFile.c_str());
1421
1422  /* rules for input, output and internal bitdepths as per help text */
1423  if (m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ] == 0)
1424  {
1425    m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ] = m_inputBitDepth      [CHANNEL_TYPE_LUMA  ];
1426  }
1427  if (m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] == 0)
1428  {
1429    m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] = m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ];
1430  }
1431  if (m_internalBitDepth   [CHANNEL_TYPE_LUMA  ] == 0)
1432  {
1433    m_internalBitDepth   [CHANNEL_TYPE_LUMA  ] = m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ];
1434  }
1435  if (m_internalBitDepth   [CHANNEL_TYPE_CHROMA] == 0)
1436  {
1437    m_internalBitDepth   [CHANNEL_TYPE_CHROMA] = m_internalBitDepth   [CHANNEL_TYPE_LUMA  ];
1438  }
1439  if (m_inputBitDepth      [CHANNEL_TYPE_CHROMA] == 0)
1440  {
1441    m_inputBitDepth      [CHANNEL_TYPE_CHROMA] = m_inputBitDepth      [CHANNEL_TYPE_LUMA  ];
1442  }
1443  if (m_outputBitDepth     [CHANNEL_TYPE_LUMA  ] == 0)
1444  {
1445    m_outputBitDepth     [CHANNEL_TYPE_LUMA  ] = m_internalBitDepth   [CHANNEL_TYPE_LUMA  ];
1446  }
1447  if (m_outputBitDepth     [CHANNEL_TYPE_CHROMA] == 0)
1448  {
1449    m_outputBitDepth     [CHANNEL_TYPE_CHROMA] = m_internalBitDepth   [CHANNEL_TYPE_CHROMA];
1450  }
1451
1452  m_InputChromaFormatIDC = numberToChromaFormat(tmpInputChromaFormat);
1453  m_chromaFormatIDC      = ((tmpChromaFormat == 0) ? (m_InputChromaFormatIDC) : (numberToChromaFormat(tmpChromaFormat)));
1454
1455#if NH_MV
1456  // parse PTL
1457  Bool anyEmpty = false; 
1458  if( cfg_profiles.empty() )
1459  {
1460    cfg_profiles = string("main main multiview-main");   
1461    fprintf(stderr, "\nWarning: No profiles given, using defaults: %s", cfg_profiles.c_str() );
1462    anyEmpty = true; 
1463  }
1464
1465  if( cfg_levels.empty() )
1466  {
1467    cfg_levels = string("5.1 5.1 5.1");
1468    fprintf(stderr, "\nWarning: No levels given, using defaults: %s", cfg_levels.c_str() );
1469    anyEmpty = true; 
1470  }
1471
1472  if( cfg_tiers.empty() )
1473  {
1474    cfg_tiers = string("main main main");
1475    fprintf(stderr, "\nWarning: No tiers given, using defaults: %s", cfg_tiers.c_str());
1476    anyEmpty = true; 
1477  }
1478
1479  if( m_inblFlag.empty() )
1480  {
1481    fprintf(stderr, "\nWarning: No inblFlags given, using defaults:");
1482    for( Int i = 0; i < 3; i++)
1483    {
1484      m_inblFlag.push_back( false );
1485      fprintf(stderr," %d", (Int) m_inblFlag[i]);
1486    }
1487    anyEmpty = true; 
1488  }   
1489
1490  if ( anyEmpty )
1491  {
1492    fprintf( stderr, "\n" );
1493  }
1494
1495  xReadStrToEnum( cfg_profiles, extendedProfiles  ); 
1496  xReadStrToEnum( cfg_levels,   m_level     ); 
1497  xReadStrToEnum( cfg_tiers ,   m_levelTier ); 
1498
1499
1500#if NH_MV
1501  m_profiles.resize( extendedProfiles.size()); 
1502
1503  for (Int i = 0; i < m_profiles.size(); i++)
1504  {
1505    Profile::Name& m_profile             = m_profiles      [i]; 
1506    ExtendedProfileName& extendedProfile = extendedProfiles[i]; 
1507#endif
1508#endif
1509
1510  if (extendedProfile >= 1000 && extendedProfile <= 12316)
1511    {
1512      m_profile = Profile::MAINREXT;
1513      if (m_bitDepthConstraint != 0 || tmpConstraintChromaFormat != 0)
1514      {
1515        fprintf(stderr, "Error: The bit depth and chroma format constraints are not used when an explicit RExt profile is specified\n");
1516        exit(EXIT_FAILURE);
1517      }
1518      m_bitDepthConstraint     = (extendedProfile%100);
1519    m_intraConstraintFlag          = ((extendedProfile%10000)>=2000);
1520    m_onePictureOnlyConstraintFlag = (extendedProfile >= 10000);
1521      switch ((extendedProfile/100)%10)
1522      {
1523      case 0:  tmpConstraintChromaFormat=400; break;
1524      case 1:  tmpConstraintChromaFormat=420; break;
1525      case 2:  tmpConstraintChromaFormat=422; break;
1526      default: tmpConstraintChromaFormat=444; break;
1527      }
1528    }
1529    else
1530    {
1531      m_profile = Profile::Name(extendedProfile);
1532    }
1533
1534    if (m_profile == Profile::HIGHTHROUGHPUTREXT )
1535    {
1536      if (m_bitDepthConstraint == 0)
1537      {
1538        m_bitDepthConstraint = 16;
1539      }
1540      m_chromaFormatConstraint = (tmpConstraintChromaFormat == 0) ? CHROMA_444 : numberToChromaFormat(tmpConstraintChromaFormat);
1541    }
1542    else if (m_profile == Profile::MAINREXT)
1543    {
1544      if (m_bitDepthConstraint == 0 && tmpConstraintChromaFormat == 0)
1545      {
1546        // produce a valid combination, if possible.
1547      const Bool bUsingGeneralRExtTools  = m_transformSkipRotationEnabledFlag        ||
1548                                           m_transformSkipContextEnabledFlag         ||
1549                                           m_rdpcmEnabledFlag[RDPCM_SIGNAL_IMPLICIT] ||
1550                                           m_rdpcmEnabledFlag[RDPCM_SIGNAL_EXPLICIT] ||
1551          !m_enableIntraReferenceSmoothing         ||
1552                                           m_persistentRiceAdaptationEnabledFlag     ||
1553                                           m_log2MaxTransformSkipBlockSize!=2;
1554      const Bool bUsingChromaQPAdjustment= m_diffCuChromaQpOffsetDepth >= 0;
1555      const Bool bUsingExtendedPrecision = m_extendedPrecisionProcessingFlag;
1556      if (m_onePictureOnlyConstraintFlag)
1557      {
1558        m_chromaFormatConstraint = CHROMA_444;
1559        if (m_intraConstraintFlag != true)
1560        {
1561          fprintf(stderr, "Error: Intra constraint flag must be true when one_picture_only_constraint_flag is true\n");
1562          exit(EXIT_FAILURE);
1563        }
1564        const Int maxBitDepth = m_chromaFormatIDC==CHROMA_400 ? m_internalBitDepth[CHANNEL_TYPE_LUMA] : std::max(m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA]);
1565        m_bitDepthConstraint = maxBitDepth>8 ? 16:8;
1566      }
1567      else
1568      {
1569        m_chromaFormatConstraint = NUM_CHROMA_FORMAT;
1570        automaticallySelectRExtProfile(bUsingGeneralRExtTools,
1571          bUsingChromaQPAdjustment,
1572          bUsingExtendedPrecision,
1573          m_intraConstraintFlag,
1574          m_bitDepthConstraint,
1575          m_chromaFormatConstraint,
1576          m_chromaFormatIDC==CHROMA_400 ? m_internalBitDepth[CHANNEL_TYPE_LUMA] : std::max(m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA]),
1577          m_chromaFormatIDC);
1578      }
1579    }
1580      else if (m_bitDepthConstraint == 0 || tmpConstraintChromaFormat == 0)
1581      {
1582        fprintf(stderr, "Error: The bit depth and chroma format constraints must either both be specified or both be configured automatically\n");
1583        exit(EXIT_FAILURE);
1584      }
1585      else
1586      {
1587        m_chromaFormatConstraint = numberToChromaFormat(tmpConstraintChromaFormat);
1588      }
1589    }
1590    else
1591    {
1592      m_chromaFormatConstraint = (tmpConstraintChromaFormat == 0) ? m_chromaFormatIDC : numberToChromaFormat(tmpConstraintChromaFormat);
1593      m_bitDepthConstraint = (m_profile == Profile::MAIN10?10:8);
1594    }
1595#if NH_MV
1596  }
1597
1598  if ( m_numberOfLayers != 0 && ( m_profiles[0] != Profile::MAIN || m_profiles[1] != Profile::MAIN )  )
1599  {
1600    fprintf(stderr, "Error: The base layer must conform to the Main profile for Multilayer coding.\n");
1601    exit(EXIT_FAILURE);
1602  }
1603#endif
1604
1605
1606  m_inputColourSpaceConvert = stringToInputColourSpaceConvert(inputColourSpaceConvert, true);
1607
1608  switch (m_conformanceWindowMode)
1609  {
1610  case 0:
1611    {
1612      // no conformance or padding
1613      m_confWinLeft = m_confWinRight = m_confWinTop = m_confWinBottom = 0;
1614      m_aiPad[1] = m_aiPad[0] = 0;
1615      break;
1616    }
1617  case 1:
1618    {
1619      // automatic padding to minimum CU size
1620      Int minCuSize = m_uiMaxCUHeight >> (m_uiMaxCUDepth - 1);
1621      if (m_iSourceWidth % minCuSize)
1622      {
1623        m_aiPad[0] = m_confWinRight  = ((m_iSourceWidth / minCuSize) + 1) * minCuSize - m_iSourceWidth;
1624        m_iSourceWidth  += m_confWinRight;
1625      }
1626      if (m_iSourceHeight % minCuSize)
1627      {
1628        m_aiPad[1] = m_confWinBottom = ((m_iSourceHeight / minCuSize) + 1) * minCuSize - m_iSourceHeight;
1629        m_iSourceHeight += m_confWinBottom;
1630        if ( m_isField )
1631        {
1632          m_iSourceHeightOrg += m_confWinBottom << 1;
1633          m_aiPad[1] = m_confWinBottom << 1;
1634        }
1635      }
1636      if (m_aiPad[0] % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0)
1637      {
1638        fprintf(stderr, "Error: picture width is not an integer multiple of the specified chroma subsampling\n");
1639        exit(EXIT_FAILURE);
1640      }
1641      if (m_aiPad[1] % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0)
1642      {
1643        fprintf(stderr, "Error: picture height is not an integer multiple of the specified chroma subsampling\n");
1644        exit(EXIT_FAILURE);
1645      }
1646      break;
1647    }
1648  case 2:
1649    {
1650      //padding
1651      m_iSourceWidth  += m_aiPad[0];
1652      m_iSourceHeight += m_aiPad[1];
1653      m_confWinRight  = m_aiPad[0];
1654      m_confWinBottom = m_aiPad[1];
1655      break;
1656    }
1657  case 3:
1658    {
1659      // conformance
1660      if ((m_confWinLeft == 0) && (m_confWinRight == 0) && (m_confWinTop == 0) && (m_confWinBottom == 0))
1661      {
1662        fprintf(stderr, "Warning: Conformance window enabled, but all conformance window parameters set to zero\n");
1663      }
1664      if ((m_aiPad[1] != 0) || (m_aiPad[0]!=0))
1665      {
1666        fprintf(stderr, "Warning: Conformance window enabled, padding parameters will be ignored\n");
1667      }
1668      m_aiPad[1] = m_aiPad[0] = 0;
1669      break;
1670    }
1671  }
1672
1673  // allocate slice-based dQP values
1674#if NH_MV
1675  for (Int i = (Int)m_layerIdInNuh.size(); i < m_numberOfLayers; i++ )
1676  {
1677    m_layerIdInNuh.push_back( i == 0 ? 0 : m_layerIdInNuh[ i - 1 ] + 1 ); 
1678  }
1679  xResizeVector( m_layerIdInNuh ); 
1680
1681  xResizeVector( m_viewOrderIndex    ); 
1682
1683  std::vector<Int> uniqueViewOrderIndices; 
1684  for( Int layer = 0; layer < m_numberOfLayers; layer++ )
1685  {   
1686    Bool isIn = false; 
1687    for ( Int i = 0 ; i < uniqueViewOrderIndices.size(); i++ )
1688    {
1689      isIn = isIn || ( m_viewOrderIndex[ layer ] == uniqueViewOrderIndices[ i ] ); 
1690    }
1691    if ( !isIn ) 
1692    {
1693      uniqueViewOrderIndices.push_back( m_viewOrderIndex[ layer ] ); 
1694    } 
1695  }
1696  m_iNumberOfViews = (Int) uniqueViewOrderIndices.size(); 
1697  xResizeVector( m_auxId );
1698
1699  xResizeVector( m_fQP ); 
1700
1701  for( Int layer = 0; layer < m_numberOfLayers; layer++ )
1702  {
1703    m_aidQP.push_back( new Int[ m_framesToBeEncoded + m_iGOPSize + 1 ] );
1704    ::memset( m_aidQP[layer], 0, sizeof(Int)*( m_framesToBeEncoded + m_iGOPSize + 1 ) );
1705
1706    // handling of floating-point QP values
1707    // if QP is not integer, sequence is split into two sections having QP and QP+1
1708    m_iQP.push_back((Int)( m_fQP[layer] ));
1709    if ( m_iQP[layer] < m_fQP[layer] )
1710    {
1711      Int iSwitchPOC = (Int)( m_framesToBeEncoded - (m_fQP[layer] - m_iQP[layer])*m_framesToBeEncoded + 0.5 );
1712
1713      iSwitchPOC = (Int)( (Double)iSwitchPOC / m_iGOPSize + 0.5 )*m_iGOPSize;
1714      for ( Int i=iSwitchPOC; i<m_framesToBeEncoded + m_iGOPSize + 1; i++ )
1715      {
1716        m_aidQP[layer][i] = 1;
1717      }
1718    }
1719
1720    for(UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
1721    {
1722      if (saoOffsetBitShift[ch]<0)
1723      {
1724        if (m_internalBitDepth[ch]>10)
1725        {
1726          m_log2SaoOffsetScale[layer][ch]=UInt(Clip3<Int>(0, m_internalBitDepth[ch]-10, Int(m_internalBitDepth[ch]-10 + 0.165*m_iQP[layer] - 3.22 + 0.5) ) );
1727        }
1728        else
1729        {
1730          m_log2SaoOffsetScale[layer][ch]=0;
1731        }
1732      }
1733      else
1734      {
1735        m_log2SaoOffsetScale[layer][ch]=UInt(saoOffsetBitShift[ch]);
1736      }
1737    }
1738  }
1739
1740  xResizeVector( m_bLoopFilterDisable ); 
1741  xResizeVector( m_bUseSAO ); 
1742  xResizeVector( m_iIntraPeriod ); 
1743  xResizeVector( m_tilesInUseFlag ); 
1744  xResizeVector( m_loopFilterNotAcrossTilesFlag ); 
1745  xResizeVector( m_wppInUseFlag ); 
1746
1747  for (Int olsIdx = 0; olsIdx < m_vpsNumLayerSets + m_numAddLayerSets + (Int) m_outputLayerSetIdx.size(); olsIdx++)
1748  {   
1749    m_altOutputLayerFlag.push_back( false );     
1750  }
1751#else
1752  m_aidQP = new Int[ m_framesToBeEncoded + m_iGOPSize + 1 ];
1753  ::memset( m_aidQP, 0, sizeof(Int)*( m_framesToBeEncoded + m_iGOPSize + 1 ) );
1754
1755  // handling of floating-point QP values
1756  // if QP is not integer, sequence is split into two sections having QP and QP+1
1757  m_iQP = (Int)( m_fQP );
1758  if ( m_iQP < m_fQP )
1759  {
1760    Int iSwitchPOC = (Int)( m_framesToBeEncoded - (m_fQP - m_iQP)*m_framesToBeEncoded + 0.5 );
1761
1762    iSwitchPOC = (Int)( (Double)iSwitchPOC / m_iGOPSize + 0.5 )*m_iGOPSize;
1763    for ( Int i=iSwitchPOC; i<m_framesToBeEncoded + m_iGOPSize + 1; i++ )
1764    {
1765      m_aidQP[i] = 1;
1766    }
1767  }
1768
1769  for(UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
1770  {
1771    if (saoOffsetBitShift[ch]<0)
1772    {
1773      if (m_internalBitDepth[ch]>10)
1774      {
1775        m_log2SaoOffsetScale[ch]=UInt(Clip3<Int>(0, m_internalBitDepth[ch]-10, Int(m_internalBitDepth[ch]-10 + 0.165*m_iQP - 3.22 + 0.5) ) );
1776      }
1777      else
1778      {
1779        m_log2SaoOffsetScale[ch]=0;
1780      }
1781    }
1782    else
1783    {
1784      m_log2SaoOffsetScale[ch]=UInt(saoOffsetBitShift[ch]);
1785    }
1786  }
1787
1788#endif
1789
1790  // reading external dQP description from file
1791  if ( m_pchdQPFile )
1792  {
1793    FILE* fpt=fopen( m_pchdQPFile, "r" );
1794    if ( fpt )
1795    {
1796#if NH_MV
1797      for( Int layer = 0; layer < m_numberOfLayers; layer++ )
1798      {
1799#endif
1800      Int iValue;
1801      Int iPOC = 0;
1802      while ( iPOC < m_framesToBeEncoded )
1803      {
1804        if ( fscanf(fpt, "%d", &iValue ) == EOF )
1805        {
1806          break;
1807        }
1808#if NH_MV
1809        m_aidQP[layer][ iPOC ] = iValue;
1810        iPOC++;
1811      }
1812#else
1813        m_aidQP[ iPOC ] = iValue;
1814        iPOC++;
1815#endif
1816      }
1817      fclose(fpt);
1818    }
1819  }
1820
1821  if( m_masteringDisplay.colourVolumeSEIEnabled )
1822  {
1823    for(UInt idx=0; idx<6; idx++)
1824    {
1825      m_masteringDisplay.primaries[idx/2][idx%2] = UShort((cfg_DisplayPrimariesCode.values.size() > idx) ? cfg_DisplayPrimariesCode.values[idx] : 0);
1826    }
1827    for(UInt idx=0; idx<2; idx++)
1828    {
1829      m_masteringDisplay.whitePoint[idx] = UShort((cfg_DisplayWhitePointCode.values.size() > idx) ? cfg_DisplayWhitePointCode.values[idx] : 0);
1830    }
1831  }
1832   
1833  if( m_toneMappingInfoSEIEnabled && !m_toneMapCancelFlag )
1834  {
1835    if( m_toneMapModelId == 2 && !cfg_startOfCodedInterval.values.empty() )
1836    {
1837      const UInt num = 1u<< m_toneMapTargetBitDepth;
1838      m_startOfCodedInterval = new Int[num];
1839      for(UInt i=0; i<num; i++)
1840      {
1841        m_startOfCodedInterval[i] = cfg_startOfCodedInterval.values.size() > i ? cfg_startOfCodedInterval.values[i] : 0;
1842      }
1843    }
1844    else
1845    {
1846      m_startOfCodedInterval = NULL;
1847    }
1848    if( ( m_toneMapModelId == 3 ) && ( m_numPivots > 0 ) )
1849    {
1850      if( !cfg_codedPivotValue.values.empty() && !cfg_targetPivotValue.values.empty() )
1851      {
1852        m_codedPivotValue  = new Int[m_numPivots];
1853        m_targetPivotValue = new Int[m_numPivots];
1854        for(UInt i=0; i<m_numPivots; i++)
1855        {
1856          m_codedPivotValue[i]  = cfg_codedPivotValue.values.size()  > i ? cfg_codedPivotValue.values [i] : 0;
1857          m_targetPivotValue[i] = cfg_targetPivotValue.values.size() > i ? cfg_targetPivotValue.values[i] : 0;
1858        }
1859      }
1860    }
1861    else
1862    {
1863      m_codedPivotValue = NULL;
1864      m_targetPivotValue = NULL;
1865    }
1866  }
1867
1868  if( m_kneeSEIEnabled && !m_kneeSEICancelFlag )
1869  {
1870    assert ( m_kneeSEINumKneePointsMinus1 >= 0 && m_kneeSEINumKneePointsMinus1 < 999 );
1871    m_kneeSEIInputKneePoint  = new Int[m_kneeSEINumKneePointsMinus1+1];
1872    m_kneeSEIOutputKneePoint = new Int[m_kneeSEINumKneePointsMinus1+1];
1873    for(Int i=0; i<(m_kneeSEINumKneePointsMinus1+1); i++)
1874    {
1875      m_kneeSEIInputKneePoint[i]  = cfg_kneeSEIInputKneePointValue.values.size()  > i ? cfg_kneeSEIInputKneePointValue.values[i]  : 1;
1876      m_kneeSEIOutputKneePoint[i] = cfg_kneeSEIOutputKneePointValue.values.size() > i ? cfg_kneeSEIOutputKneePointValue.values[i] : 0;
1877    }
1878  }
1879
1880  if(m_timeCodeSEIEnabled)
1881  {
1882    for(Int i = 0; i < m_timeCodeSEINumTs && i < MAX_TIMECODE_SEI_SETS; i++)
1883    {
1884      m_timeSetArray[i].clockTimeStampFlag    = cfg_timeCodeSeiTimeStampFlag        .values.size()>i ? cfg_timeCodeSeiTimeStampFlag        .values [i] : false;
1885      m_timeSetArray[i].numUnitFieldBasedFlag = cfg_timeCodeSeiNumUnitFieldBasedFlag.values.size()>i ? cfg_timeCodeSeiNumUnitFieldBasedFlag.values [i] : 0;
1886      m_timeSetArray[i].countingType          = cfg_timeCodeSeiCountingType         .values.size()>i ? cfg_timeCodeSeiCountingType         .values [i] : 0;
1887      m_timeSetArray[i].fullTimeStampFlag     = cfg_timeCodeSeiFullTimeStampFlag    .values.size()>i ? cfg_timeCodeSeiFullTimeStampFlag    .values [i] : 0;
1888      m_timeSetArray[i].discontinuityFlag     = cfg_timeCodeSeiDiscontinuityFlag    .values.size()>i ? cfg_timeCodeSeiDiscontinuityFlag    .values [i] : 0;
1889      m_timeSetArray[i].cntDroppedFlag        = cfg_timeCodeSeiCntDroppedFlag       .values.size()>i ? cfg_timeCodeSeiCntDroppedFlag       .values [i] : 0;
1890      m_timeSetArray[i].numberOfFrames        = cfg_timeCodeSeiNumberOfFrames       .values.size()>i ? cfg_timeCodeSeiNumberOfFrames       .values [i] : 0;
1891      m_timeSetArray[i].secondsValue          = cfg_timeCodeSeiSecondsValue         .values.size()>i ? cfg_timeCodeSeiSecondsValue         .values [i] : 0;
1892      m_timeSetArray[i].minutesValue          = cfg_timeCodeSeiMinutesValue         .values.size()>i ? cfg_timeCodeSeiMinutesValue         .values [i] : 0;
1893      m_timeSetArray[i].hoursValue            = cfg_timeCodeSeiHoursValue           .values.size()>i ? cfg_timeCodeSeiHoursValue           .values [i] : 0;
1894      m_timeSetArray[i].secondsFlag           = cfg_timeCodeSeiSecondsFlag          .values.size()>i ? cfg_timeCodeSeiSecondsFlag          .values [i] : 0;
1895      m_timeSetArray[i].minutesFlag           = cfg_timeCodeSeiMinutesFlag          .values.size()>i ? cfg_timeCodeSeiMinutesFlag          .values [i] : 0;
1896      m_timeSetArray[i].hoursFlag             = cfg_timeCodeSeiHoursFlag            .values.size()>i ? cfg_timeCodeSeiHoursFlag            .values [i] : 0;
1897      m_timeSetArray[i].timeOffsetLength      = cfg_timeCodeSeiTimeOffsetLength     .values.size()>i ? cfg_timeCodeSeiTimeOffsetLength     .values [i] : 0;
1898      m_timeSetArray[i].timeOffsetValue       = cfg_timeCodeSeiTimeOffsetValue      .values.size()>i ? cfg_timeCodeSeiTimeOffsetValue      .values [i] : 0;
1899    }
1900  }
1901
1902
1903  // check validity of input parameters
1904  xCheckParameter();
1905
1906  // compute actual CU depth with respect to config depth and max transform size
1907  UInt uiAddCUDepth  = 0;
1908  while( (m_uiMaxCUWidth>>m_uiMaxCUDepth) > ( 1 << ( m_uiQuadtreeTULog2MinSize + uiAddCUDepth )  ) )
1909  {
1910    uiAddCUDepth++;
1911  }
1912
1913  m_uiMaxTotalCUDepth = m_uiMaxCUDepth + uiAddCUDepth + getMaxCUDepthOffset(m_chromaFormatIDC, m_uiQuadtreeTULog2MinSize); // if minimum TU larger than 4x4, allow for additional part indices for 4:2:2 SubTUs.
1914  m_uiLog2DiffMaxMinCodingBlockSize = m_uiMaxCUDepth - 1;
1915
1916  // print-out parameters
1917  xPrintParameter();
1918
1919  return true;
1920}
1921
1922
1923// ====================================================================================================================
1924// Private member functions
1925// ====================================================================================================================
1926
1927Void TAppEncCfg::xCheckParameter()
1928{
1929  if (!m_decodedPictureHashSEIEnabled)
1930  {
1931    fprintf(stderr, "******************************************************************\n");
1932    fprintf(stderr, "** WARNING: --SEIDecodedPictureHash is now disabled by default. **\n");
1933    fprintf(stderr, "**          Automatic verification of decoded pictures by a     **\n");
1934    fprintf(stderr, "**          decoder requires this option to be enabled.         **\n");
1935    fprintf(stderr, "******************************************************************\n");
1936  }
1937
1938
1939#if !NH_MV
1940  if( m_profile==Profile::NONE )
1941  {
1942    fprintf(stderr, "***************************************************************************\n");
1943    fprintf(stderr, "** WARNING: For conforming bitstreams a valid Profile value must be set! **\n");
1944    fprintf(stderr, "***************************************************************************\n");
1945  }
1946  if( m_level==Level::NONE )
1947  {
1948    fprintf(stderr, "***************************************************************************\n");
1949    fprintf(stderr, "** WARNING: For conforming bitstreams a valid Level value must be set!   **\n");
1950    fprintf(stderr, "***************************************************************************\n");
1951  }
1952#endif
1953
1954  Bool check_failed = false; /* abort if there is a fatal configuration problem */
1955#define xConfirmPara(a,b) check_failed |= confirmPara(a,b)
1956
1957  xConfirmPara(m_pchBitstreamFile==NULL, "A bitstream file name must be specified (BitstreamFile)");
1958  const UInt maxBitDepth=(m_chromaFormatIDC==CHROMA_400) ? m_internalBitDepth[CHANNEL_TYPE_LUMA] : std::max(m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA]);
1959  xConfirmPara(m_bitDepthConstraint<maxBitDepth, "The internalBitDepth must not be greater than the bitDepthConstraint value");
1960  xConfirmPara(m_chromaFormatConstraint<m_chromaFormatIDC, "The chroma format used must not be greater than the chromaFormatConstraint value");
1961#if NH_MV
1962  Profile::Name & m_profile = m_profiles[0];
1963#endif
1964
1965  if (m_profile==Profile::MAINREXT || m_profile==Profile::HIGHTHROUGHPUTREXT)
1966  {
1967    xConfirmPara(m_lowerBitRateConstraintFlag==false && m_intraConstraintFlag==false, "The lowerBitRateConstraint flag cannot be false when intraConstraintFlag is false");
1968    xConfirmPara(m_cabacBypassAlignmentEnabledFlag && m_profile!=Profile::HIGHTHROUGHPUTREXT, "AlignCABACBeforeBypass must not be enabled unless the high throughput profile is being used.");
1969    if (m_profile == Profile::MAINREXT)
1970    {
1971      const UInt intraIdx = m_intraConstraintFlag ? 1:0;
1972      const UInt bitDepthIdx = (m_bitDepthConstraint == 8 ? 0 : (m_bitDepthConstraint ==10 ? 1 : (m_bitDepthConstraint == 12 ? 2 : (m_bitDepthConstraint == 16 ? 3 : 4 ))));
1973      const UInt chromaFormatIdx = UInt(m_chromaFormatConstraint);
1974      const Bool bValidProfile = (bitDepthIdx > 3 || chromaFormatIdx>3) ? false : (validRExtProfileNames[intraIdx][bitDepthIdx][chromaFormatIdx] != NONE);
1975      xConfirmPara(!bValidProfile, "Invalid intra constraint flag, bit depth constraint flag and chroma format constraint flag combination for a RExt profile");
1976      const Bool bUsingGeneralRExtTools  = m_transformSkipRotationEnabledFlag        ||
1977                                           m_transformSkipContextEnabledFlag         ||
1978                                           m_rdpcmEnabledFlag[RDPCM_SIGNAL_IMPLICIT] ||
1979                                           m_rdpcmEnabledFlag[RDPCM_SIGNAL_EXPLICIT] ||
1980                                           !m_enableIntraReferenceSmoothing         ||
1981                                           m_persistentRiceAdaptationEnabledFlag     ||
1982                                           m_log2MaxTransformSkipBlockSize!=2;
1983      const Bool bUsingChromaQPTool      = m_diffCuChromaQpOffsetDepth >= 0;
1984      const Bool bUsingExtendedPrecision = m_extendedPrecisionProcessingFlag;
1985
1986      xConfirmPara((m_chromaFormatConstraint==CHROMA_420 || m_chromaFormatConstraint==CHROMA_400) && bUsingChromaQPTool, "CU Chroma QP adjustment cannot be used for 4:0:0 or 4:2:0 RExt profiles");
1987      xConfirmPara(m_bitDepthConstraint != 16 && bUsingExtendedPrecision, "Extended precision can only be used in 16-bit RExt profiles");
1988      if (!(m_chromaFormatConstraint == CHROMA_400 && m_bitDepthConstraint == 16) && m_chromaFormatConstraint!=CHROMA_444)
1989      {
1990        xConfirmPara(bUsingGeneralRExtTools, "Combination of tools and profiles are not possible in the specified RExt profile.");
1991      }
1992      xConfirmPara( m_onePictureOnlyConstraintFlag && m_chromaFormatConstraint!=CHROMA_444, "chroma format constraint must be 4:4:4 when one-picture-only constraint flag is 1");
1993      xConfirmPara( m_onePictureOnlyConstraintFlag && m_bitDepthConstraint != 8 && m_bitDepthConstraint != 16, "bit depth constraint must be 8 or 16 when one-picture-only constraint flag is 1");
1994      xConfirmPara( m_onePictureOnlyConstraintFlag && m_framesToBeEncoded > 1, "Number of frames to be encoded must be 1 when one-picture-only constraint flag is 1.");
1995
1996      if (!m_intraConstraintFlag && m_bitDepthConstraint==16 && m_chromaFormatConstraint==CHROMA_444)
1997      {
1998        fprintf(stderr, "********************************************************************************************************\n");
1999        fprintf(stderr, "** WARNING: The RExt constraint flags describe a non standard combination (used for development only) **\n");
2000        fprintf(stderr, "********************************************************************************************************\n");
2001      }
2002    }
2003    else
2004    {
2005      xConfirmPara( m_chromaFormatConstraint != CHROMA_444, "chroma format constraint must be 4:4:4 in the High Throughput 4:4:4 16-bit Intra profile.");
2006      xConfirmPara( m_bitDepthConstraint     != 16,         "bit depth constraint must be 4:4:4 in the High Throughput 4:4:4 16-bit Intra profile.");
2007      xConfirmPara( m_intraConstraintFlag    != 1,          "intra constraint flag must be 1 in the High Throughput 4:4:4 16-bit Intra profile.");
2008    }
2009  }
2010  else
2011  {
2012    xConfirmPara(m_bitDepthConstraint!=((m_profile==Profile::MAIN10)?10:8), "BitDepthConstraint must be 8 for MAIN profile and 10 for MAIN10 profile.");
2013    xConfirmPara(m_chromaFormatConstraint!=CHROMA_420, "ChromaFormatConstraint must be 420 for non main-RExt profiles.");
2014    xConfirmPara(m_intraConstraintFlag==true, "IntraConstraintFlag must be false for non main_RExt profiles.");
2015    xConfirmPara(m_lowerBitRateConstraintFlag==false, "LowerBitrateConstraintFlag must be true for non main-RExt profiles.");
2016    xConfirmPara(m_profile == Profile::MAINSTILLPICTURE && m_framesToBeEncoded > 1, "Number of frames to be encoded must be 1 when main still picture profile is used.");
2017
2018    xConfirmPara(m_crossComponentPredictionEnabledFlag==true, "CrossComponentPrediction must not be used for non main-RExt profiles.");
2019    xConfirmPara(m_log2MaxTransformSkipBlockSize!=2, "Transform Skip Log2 Max Size must be 2 for V1 profiles.");
2020    xConfirmPara(m_transformSkipRotationEnabledFlag==true, "UseResidualRotation must not be enabled for non main-RExt profiles.");
2021    xConfirmPara(m_transformSkipContextEnabledFlag==true, "UseSingleSignificanceMapContext must not be enabled for non main-RExt profiles.");
2022    xConfirmPara(m_rdpcmEnabledFlag[RDPCM_SIGNAL_IMPLICIT]==true, "ImplicitResidualDPCM must not be enabled for non main-RExt profiles.");
2023    xConfirmPara(m_rdpcmEnabledFlag[RDPCM_SIGNAL_EXPLICIT]==true, "ExplicitResidualDPCM must not be enabled for non main-RExt profiles.");
2024    xConfirmPara(m_persistentRiceAdaptationEnabledFlag==true, "GolombRiceParameterAdaption must not be enabled for non main-RExt profiles.");
2025    xConfirmPara(m_extendedPrecisionProcessingFlag==true, "UseExtendedPrecision must not be enabled for non main-RExt profiles.");
2026    xConfirmPara(m_highPrecisionOffsetsEnabledFlag==true, "UseHighPrecisionPredictionWeighting must not be enabled for non main-RExt profiles.");
2027    xConfirmPara(m_enableIntraReferenceSmoothing==false, "EnableIntraReferenceSmoothing must be enabled for non main-RExt profiles.");
2028    xConfirmPara(m_cabacBypassAlignmentEnabledFlag, "AlignCABACBeforeBypass cannot be enabled for non main-RExt profiles.");
2029  }
2030
2031  // check range of parameters
2032  xConfirmPara( m_inputBitDepth[CHANNEL_TYPE_LUMA  ] < 8,                                   "InputBitDepth must be at least 8" );
2033  xConfirmPara( m_inputBitDepth[CHANNEL_TYPE_CHROMA] < 8,                                   "InputBitDepthC must be at least 8" );
2034
2035#if !RExt__HIGH_BIT_DEPTH_SUPPORT
2036  if (m_extendedPrecisionProcessingFlag)
2037  {
2038    for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
2039    {
2040      xConfirmPara((m_internalBitDepth[channelType] > 8) , "Model is not configured to support high enough internal accuracies - enable RExt__HIGH_BIT_DEPTH_SUPPORT to use increased precision internal data types etc...");
2041    }
2042  }
2043  else
2044  {
2045    for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
2046    {
2047      xConfirmPara((m_internalBitDepth[channelType] > 12) , "Model is not configured to support high enough internal accuracies - enable RExt__HIGH_BIT_DEPTH_SUPPORT to use increased precision internal data types etc...");
2048    }
2049  }
2050#endif
2051
2052  xConfirmPara( (m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ] < m_inputBitDepth[CHANNEL_TYPE_LUMA  ]), "MSB-extended bit depth for luma channel (--MSBExtendedBitDepth) must be greater than or equal to input bit depth for luma channel (--InputBitDepth)" );
2053  xConfirmPara( (m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] < m_inputBitDepth[CHANNEL_TYPE_CHROMA]), "MSB-extended bit depth for chroma channel (--MSBExtendedBitDepthC) must be greater than or equal to input bit depth for chroma channel (--InputBitDepthC)" );
2054
2055#if NH_MV
2056  for (Int i = 0; i < m_numberOfLayers; i++)
2057  {
2058    xConfirmPara( m_log2SaoOffsetScale[i][CHANNEL_TYPE_LUMA]   > (m_internalBitDepth[CHANNEL_TYPE_LUMA  ]<10?0:(m_internalBitDepth[CHANNEL_TYPE_LUMA  ]-10)), "SaoLumaOffsetBitShift must be in the range of 0 to InternalBitDepth-10, inclusive");
2059    xConfirmPara( m_log2SaoOffsetScale[i][CHANNEL_TYPE_CHROMA] > (m_internalBitDepth[CHANNEL_TYPE_CHROMA]<10?0:(m_internalBitDepth[CHANNEL_TYPE_CHROMA]-10)), "SaoChromaOffsetBitShift must be in the range of 0 to InternalBitDepthC-10, inclusive");
2060  }
2061#else
2062  xConfirmPara( m_log2SaoOffsetScale[CHANNEL_TYPE_LUMA]   > (m_internalBitDepth[CHANNEL_TYPE_LUMA  ]<10?0:(m_internalBitDepth[CHANNEL_TYPE_LUMA  ]-10)), "SaoLumaOffsetBitShift must be in the range of 0 to InternalBitDepth-10, inclusive");
2063  xConfirmPara( m_log2SaoOffsetScale[CHANNEL_TYPE_CHROMA] > (m_internalBitDepth[CHANNEL_TYPE_CHROMA]<10?0:(m_internalBitDepth[CHANNEL_TYPE_CHROMA]-10)), "SaoChromaOffsetBitShift must be in the range of 0 to InternalBitDepthC-10, inclusive");
2064#endif
2065
2066  xConfirmPara( m_chromaFormatIDC >= NUM_CHROMA_FORMAT,                                     "ChromaFormatIDC must be either 400, 420, 422 or 444" );
2067  std::string sTempIPCSC="InputColourSpaceConvert must be empty, "+getListOfColourSpaceConverts(true);
2068  xConfirmPara( m_inputColourSpaceConvert >= NUMBER_INPUT_COLOUR_SPACE_CONVERSIONS,         sTempIPCSC.c_str() );
2069  xConfirmPara( m_InputChromaFormatIDC >= NUM_CHROMA_FORMAT,                                "InputChromaFormatIDC must be either 400, 420, 422 or 444" );
2070  xConfirmPara( m_iFrameRate <= 0,                                                          "Frame rate must be more than 1" );
2071  xConfirmPara( m_framesToBeEncoded <= 0,                                                   "Total Number Of Frames encoded must be more than 0" );
2072#if NH_MV
2073  xConfirmPara( m_numberOfLayers > MAX_NUM_LAYER_IDS ,                                      "NumberOfLayers must be less than or equal to MAX_NUM_LAYER_IDS");
2074
2075
2076  xConfirmPara( m_layerIdInNuh[0] != 0      , "LayerIdInNuh must be 0 for the first layer. ");
2077  xConfirmPara( (m_layerIdInNuh.size()!=1) && (m_layerIdInNuh.size() < m_numberOfLayers) , "LayerIdInNuh must be given for all layers. ");
2078
2079  xConfirmPara( m_scalabilityMask != 2 && m_scalabilityMask != 8 && m_scalabilityMask != 10, "Scalability Mask must be equal to 2, 8 or 10");
2080
2081
2082  m_dimIds.push_back( m_viewOrderIndex );   
2083  for (Int i = 0; i < m_auxId.size(); i++)
2084  {
2085    xConfirmPara( !( ( m_auxId[i] >= 0 && m_auxId[i] <= 2 ) || ( m_auxId[i] >= 128 && m_auxId[i] <= 159 ) ) , "AuxId shall be in the range of 0 to 2, inclusive, or 128 to 159, inclusive");
2086  }
2087  if ( m_scalabilityMask & ( 1 << AUX_ID ) )
2088  {
2089    m_dimIds.push_back ( m_auxId );
2090  }
2091  xConfirmPara(  m_dimensionIdLen.size() < m_dimIds.size(), "DimensionIdLen must be given for all dimensions. "   );
2092  Int dimBitOffset[MAX_NUM_SCALABILITY_TYPES+1]; 
2093
2094  dimBitOffset[ 0 ] = 0; 
2095  for (Int j = 1; j <= (((Int) m_dimIds.size() - m_splittingFlag) ? 1 : 0); j++ )
2096  {
2097    dimBitOffset[ j ] = dimBitOffset[ j - 1 ] + m_dimensionIdLen[ j - 1]; 
2098  }
2099
2100  if ( m_splittingFlag )
2101  {
2102    dimBitOffset[ (Int) m_dimIds.size() ] = 6; 
2103  }
2104
2105  for( Int j = 0; j < m_dimIds.size(); j++ )
2106  {   
2107    xConfirmPara( m_dimIds[j].size() < m_numberOfLayers,  "DimensionId must be given for all layers and all dimensions. ");   
2108    xConfirmPara( (m_dimIds[j][0] != 0)                 , "DimensionId of layer 0 must be 0. " );
2109    xConfirmPara( m_dimensionIdLen[j] < 1 || m_dimensionIdLen[j] > 8, "DimensionIdLen must be greater than 0 and less than 9 in all dimensions. " ); 
2110
2111
2112    for( Int i = 1; i < m_numberOfLayers; i++ )
2113    {     
2114      xConfirmPara(  ( m_dimIds[j][i] < 0 ) || ( m_dimIds[j][i] > ( ( 1 << m_dimensionIdLen[j] ) - 1 ) )   , "DimensionId shall be in the range of 0 to 2^DimensionIdLen - 1. " );
2115      if ( m_splittingFlag )
2116      {
2117        Int layerIdInNuh = (m_layerIdInNuh.size()!=1) ? m_layerIdInNuh[i] :  i; 
2118        xConfirmPara( ( ( layerIdInNuh & ( (1 << dimBitOffset[ j + 1 ] ) - 1) ) >> dimBitOffset[ j ] )  != m_dimIds[j][ i ]  , "When Splitting Flag is equal to 1 dimension ids shall match values derived from layer ids. "); 
2119      }
2120    }
2121  }
2122
2123  for( Int i = 0; i < m_numberOfLayers; i++ )
2124  {
2125    for( Int j = 0; j < i; j++ )
2126    {     
2127      Int numDiff  = 0; 
2128      Int lastDiff = -1; 
2129      for( Int dim = 0; dim < m_dimIds.size(); dim++ )
2130      {
2131        if ( m_dimIds[dim][i] != m_dimIds[dim][j] )
2132        {
2133          numDiff ++; 
2134          lastDiff = dim; 
2135        }
2136      }
2137
2138      Bool allEqual = ( numDiff == 0 ); 
2139
2140      if ( allEqual ) 
2141      {
2142        printf( "\nError: Positions of Layers %d and %d are identical in scalability space\n", i, j);
2143      }
2144
2145      xConfirmPara( allEqual , "Each layer shall have a different position in scalability space." );
2146
2147      if ( numDiff  == 1 ) 
2148      {
2149        Bool inc = m_dimIds[ lastDiff ][ i ] > m_dimIds[ lastDiff ][ j ]; 
2150        Bool shallBeButIsNotIncreasing = ( !inc  ) ; 
2151        if ( shallBeButIsNotIncreasing )
2152        {       
2153          printf( "\nError: Positions of Layers %d and %d is not increasing in dimension %d \n", i, j, lastDiff);       
2154        }
2155        xConfirmPara( shallBeButIsNotIncreasing,  "DimensionIds shall be increasing within one dimension. " );
2156      }
2157    }
2158  }
2159
2160  /// ViewId
2161  xConfirmPara( m_viewId.size() != m_iNumberOfViews, "The number of ViewIds must be equal to the number of views." ); 
2162
2163  /// Layer sets
2164  xConfirmPara( m_vpsNumLayerSets < 0 || m_vpsNumLayerSets > 1024, "VpsNumLayerSets must be greater than 0 and less than 1025. ") ; 
2165  for( Int lsIdx = 0; lsIdx < m_vpsNumLayerSets; lsIdx++ )
2166  {
2167    if (lsIdx == 0)
2168    {
2169      xConfirmPara( m_layerIdsInSets[lsIdx].size() != 1 || m_layerIdsInSets[lsIdx][0] != 0 , "0-th layer shall only include layer 0. ");
2170    }
2171    for ( Int i = 0; i < m_layerIdsInSets[lsIdx].size(); i++ )
2172    {
2173      xConfirmPara( m_layerIdsInSets[lsIdx][i] < 0 || m_layerIdsInSets[lsIdx][i] >= MAX_NUM_LAYER_IDS, "LayerIdsInSet must be greater than 0 and less than MAX_NUM_LAYER_IDS" ); 
2174    }
2175  }
2176
2177  // Output layer sets
2178  xConfirmPara( m_outputLayerSetIdx.size() > 1024, "The number of output layer set indices must be less than 1025.") ;
2179  for (Int lsIdx = 0; lsIdx < m_outputLayerSetIdx.size(); lsIdx++)
2180  {   
2181    Int refLayerSetIdx = m_outputLayerSetIdx[ lsIdx ]; 
2182    xConfirmPara(  refLayerSetIdx < 0 || refLayerSetIdx >= m_vpsNumLayerSets + m_numAddLayerSets, "Output layer set idx must be greater or equal to 0 and less than the VpsNumLayerSets plus NumAddLayerSets." );
2183  }
2184
2185  xConfirmPara( m_defaultOutputLayerIdc < 0 || m_defaultOutputLayerIdc > 2, "Default target output layer idc must greater than or equal to 0 and less than or equal to 2." ); 
2186
2187  if( m_defaultOutputLayerIdc != 2 )
2188  {
2189    Bool anyDefaultOutputFlag = false;   
2190    for (Int lsIdx = 0; lsIdx < m_vpsNumLayerSets; lsIdx++)
2191    { 
2192      anyDefaultOutputFlag = anyDefaultOutputFlag || ( m_layerIdsInDefOutputLayerSet[lsIdx].size() != 0 );
2193    }   
2194    if ( anyDefaultOutputFlag )
2195    {   
2196      printf( "\nWarning: Ignoring LayerIdsInDefOutputLayerSet parameters, since defaultTargetOuputLayerIdc is not equal 2.\n" );   
2197    }
2198  }
2199  else 
2200  { 
2201    for (Int lsIdx = 0; lsIdx < m_vpsNumLayerSets; lsIdx++)
2202    { 
2203      for (Int i = 0; i < m_layerIdsInDefOutputLayerSet[ lsIdx ].size(); i++)
2204      {
2205        Bool inLayerSetFlag = false; 
2206        for (Int j = 0; j < m_layerIdsInSets[ lsIdx].size(); j++ )
2207        {
2208          if ( m_layerIdsInSets[ lsIdx ][ j ] == m_layerIdsInDefOutputLayerSet[ lsIdx ][ i ] )
2209          {
2210            inLayerSetFlag = true; 
2211            break; 
2212          }       
2213        }
2214        xConfirmPara( !inLayerSetFlag, "All output layers of a output layer set must be included in corresponding layer set.");
2215      }
2216    }
2217  }
2218
2219  xConfirmPara( m_altOutputLayerFlag.size() < m_vpsNumLayerSets + m_numAddLayerSets + m_outputLayerSetIdx.size(), "The number of alt output layer flags must be equal to the number of layer set additional output layer sets plus the number of output layer set indices" );
2220
2221  // PTL
2222  xConfirmPara( ( m_profiles.size() != m_inblFlag.size() || m_profiles.size() != m_level.size()  ||  m_profiles.size() != m_levelTier.size() ), "The number of Profiles, Levels, Tiers and InblFlags must be equal." ); 
2223
2224  if ( m_numberOfLayers > 1)
2225  {
2226    xConfirmPara( m_profiles.size() <= 1, "The number of profiles, tiers, levels, and inblFlags must be greater than 1.");
2227    xConfirmPara( m_inblFlag[0], "VpsProfileTierLevel[0] must have inblFlag equal to 0");
2228    if (m_profiles.size() > 1 )
2229    {
2230      xConfirmPara( m_profiles[0]  != m_profiles[1], "The profile in VpsProfileTierLevel[1] must be equal to the profile in VpsProfileTierLevel[0].");
2231      xConfirmPara( m_inblFlag[0] != m_inblFlag[1], "inblFlag in VpsProfileTierLevel[1] must be equal to the inblFlag in VpsProfileTierLevel[0].");
2232    }
2233  }
2234
2235  // Layer Dependencies 
2236  for (Int i = 0; i < m_numberOfLayers; i++ )
2237  {
2238    xConfirmPara( (i == 0)  && m_directRefLayers[0].size() != 0, "Layer 0 shall not have reference layers." ); 
2239    xConfirmPara( m_directRefLayers[i].size() != m_dependencyTypes[ i ].size(), "Each reference layer shall have a reference type." ); 
2240    for (Int j = 0; j < m_directRefLayers[i].size(); j++)
2241    {
2242      xConfirmPara( m_directRefLayers[i][j] < 0 || m_directRefLayers[i][j] >= i , "Reference layer id shall be greater than or equal to 0 and less than dependent layer id"); 
2243      xConfirmPara( m_dependencyTypes[i][j] < 0 || m_dependencyTypes[i][j] >  6 , "Dependency type shall be greater than or equal to 0 and less than 7");
2244    }       
2245  } 
2246#endif
2247
2248  xConfirmPara( m_iGOPSize < 1 ,                                                            "GOP Size must be greater or equal to 1" );
2249  xConfirmPara( m_iGOPSize > 1 &&  m_iGOPSize % 2,                                          "GOP Size must be a multiple of 2, if GOP Size is greater than 1" );
2250#if NH_MV
2251  for( Int layer = 0; layer < m_numberOfLayers; layer++ )
2252  {
2253    xConfirmPara( (m_iIntraPeriod[layer] > 0 && m_iIntraPeriod[layer] < m_iGOPSize) || m_iIntraPeriod[layer] == 0, "Intra period must be more than GOP size, or -1 , not 0" );
2254  }
2255#else
2256  xConfirmPara( (m_iIntraPeriod > 0 && m_iIntraPeriod < m_iGOPSize) || m_iIntraPeriod == 0, "Intra period must be more than GOP size, or -1 , not 0" );
2257#endif
2258  xConfirmPara( m_iDecodingRefreshType < 0 || m_iDecodingRefreshType > 3,                   "Decoding Refresh Type must be comprised between 0 and 3 included" );
2259  if(m_iDecodingRefreshType == 3)
2260  {
2261    xConfirmPara( !m_recoveryPointSEIEnabled,                                               "When using RecoveryPointSEI messages as RA points, recoveryPointSEI must be enabled" );
2262  }
2263
2264  if (m_isField)
2265  {
2266    if (!m_pictureTimingSEIEnabled)
2267    {
2268      fprintf(stderr, "****************************************************************************\n");
2269      fprintf(stderr, "** WARNING: Picture Timing SEI should be enabled for field coding!        **\n");
2270      fprintf(stderr, "****************************************************************************\n");
2271    }
2272  }
2273
2274  if(m_crossComponentPredictionEnabledFlag && (m_chromaFormatIDC != CHROMA_444))
2275  {
2276    fprintf(stderr, "****************************************************************************\n");
2277    fprintf(stderr, "** WARNING: Cross-component prediction is specified for 4:4:4 format only **\n");
2278    fprintf(stderr, "****************************************************************************\n");
2279
2280    m_crossComponentPredictionEnabledFlag = false;
2281  }
2282
2283  if ( m_CUTransquantBypassFlagForce && m_bUseHADME )
2284  {
2285    fprintf(stderr, "****************************************************************************\n");
2286    fprintf(stderr, "** WARNING: --HadamardME has been disabled due to the enabling of         **\n");
2287    fprintf(stderr, "**          --CUTransquantBypassFlagForce                                 **\n");
2288    fprintf(stderr, "****************************************************************************\n");
2289
2290    m_bUseHADME = false; // this has been disabled so that the lambda is calculated slightly differently for lossless modes (as a result of JCTVC-R0104).
2291  }
2292
2293  xConfirmPara (m_log2MaxTransformSkipBlockSize < 2, "Transform Skip Log2 Max Size must be at least 2 (4x4)");
2294
2295  if (m_log2MaxTransformSkipBlockSize!=2 && m_useTransformSkipFast)
2296  {
2297    fprintf(stderr, "***************************************************************************\n");
2298    fprintf(stderr, "** WARNING: Transform skip fast is enabled (which only tests NxN splits),**\n");
2299    fprintf(stderr, "**          but transform skip log2 max size is not 2 (4x4)              **\n");
2300    fprintf(stderr, "**          It may be better to disable transform skip fast mode         **\n");
2301    fprintf(stderr, "***************************************************************************\n");
2302  }
2303#if NH_MV
2304  for( Int layer = 0; layer < m_numberOfLayers; layer++ )
2305  {
2306    xConfirmPara( m_iQP[layer] <  -6 * (m_internalBitDepth[CHANNEL_TYPE_LUMA] - 8) || m_iQP[layer] > 51,      "QP exceeds supported range (-QpBDOffsety to 51)" );
2307    xConfirmPara( m_DeblockingFilterMetric && (m_bLoopFilterDisable[layer] || m_loopFilterOffsetInPPS), "If DeblockingFilterMetric is true then both LoopFilterDisable and LoopFilterOffsetInPPS must be 0");
2308  }
2309#else
2310  xConfirmPara( m_iQP <  -6 * (m_internalBitDepth[CHANNEL_TYPE_LUMA] - 8) || m_iQP > 51,    "QP exceeds supported range (-QpBDOffsety to 51)" );
2311  xConfirmPara( m_DeblockingFilterMetric && (m_bLoopFilterDisable || m_loopFilterOffsetInPPS), "If DeblockingFilterMetric is true then both LoopFilterDisable and LoopFilterOffsetInPPS must be 0");
2312#endif
2313 
2314  xConfirmPara( m_loopFilterBetaOffsetDiv2 < -6 || m_loopFilterBetaOffsetDiv2 > 6,        "Loop Filter Beta Offset div. 2 exceeds supported range (-6 to 6)");
2315  xConfirmPara( m_loopFilterTcOffsetDiv2 < -6 || m_loopFilterTcOffsetDiv2 > 6,            "Loop Filter Tc Offset div. 2 exceeds supported range (-6 to 6)");
2316  xConfirmPara( m_iFastSearch < 0 || m_iFastSearch > 2,                                     "Fast Search Mode is not supported value (0:Full search  1:Diamond  2:PMVFAST)" );
2317  xConfirmPara( m_iSearchRange < 0 ,                                                        "Search Range must be more than 0" );
2318  xConfirmPara( m_bipredSearchRange < 0 ,                                                   "Search Range must be more than 0" );
2319#if NH_MV
2320  xConfirmPara( m_iVerticalDisparitySearchRange <= 0 ,                                      "Vertical Disparity Search Range must be more than 0" );
2321#endif
2322  xConfirmPara( m_iMaxDeltaQP > 7,                                                          "Absolute Delta QP exceeds supported range (0 to 7)" );
2323  xConfirmPara( m_iMaxCuDQPDepth > m_uiMaxCUDepth - 1,                                          "Absolute depth for a minimum CuDQP exceeds maximum coding unit depth" );
2324
2325  xConfirmPara( m_cbQpOffset < -12,   "Min. Chroma Cb QP Offset is -12" );
2326  xConfirmPara( m_cbQpOffset >  12,   "Max. Chroma Cb QP Offset is  12" );
2327  xConfirmPara( m_crQpOffset < -12,   "Min. Chroma Cr QP Offset is -12" );
2328  xConfirmPara( m_crQpOffset >  12,   "Max. Chroma Cr QP Offset is  12" );
2329
2330  xConfirmPara( m_iQPAdaptationRange <= 0,                                                  "QP Adaptation Range must be more than 0" );
2331  if (m_iDecodingRefreshType == 2)
2332  {
2333#if NH_MV
2334    for (Int i = 0; i < m_numberOfLayers; i++ )
2335    {
2336      xConfirmPara( m_iIntraPeriod[i] > 0 && m_iIntraPeriod[i] <= m_iGOPSize ,                      "Intra period must be larger than GOP size for periodic IDR pictures");
2337    }
2338#else
2339    xConfirmPara( m_iIntraPeriod > 0 && m_iIntraPeriod <= m_iGOPSize ,                      "Intra period must be larger than GOP size for periodic IDR pictures");
2340#endif
2341  }
2342  xConfirmPara( m_uiMaxCUDepth < 1,                                                         "MaxPartitionDepth must be greater than zero");
2343  xConfirmPara( (m_uiMaxCUWidth  >> m_uiMaxCUDepth) < 4,                                    "Minimum partition width size should be larger than or equal to 8");
2344  xConfirmPara( (m_uiMaxCUHeight >> m_uiMaxCUDepth) < 4,                                    "Minimum partition height size should be larger than or equal to 8");
2345  xConfirmPara( m_uiMaxCUWidth < 16,                                                        "Maximum partition width size should be larger than or equal to 16");
2346  xConfirmPara( m_uiMaxCUHeight < 16,                                                       "Maximum partition height size should be larger than or equal to 16");
2347  xConfirmPara( (m_iSourceWidth  % (m_uiMaxCUWidth  >> (m_uiMaxCUDepth-1)))!=0,             "Resulting coded frame width must be a multiple of the minimum CU size");
2348  xConfirmPara( (m_iSourceHeight % (m_uiMaxCUHeight >> (m_uiMaxCUDepth-1)))!=0,             "Resulting coded frame height must be a multiple of the minimum CU size");
2349
2350  xConfirmPara( m_uiQuadtreeTULog2MinSize < 2,                                        "QuadtreeTULog2MinSize must be 2 or greater.");
2351  xConfirmPara( m_uiQuadtreeTULog2MaxSize > 5,                                        "QuadtreeTULog2MaxSize must be 5 or smaller.");
2352  xConfirmPara( m_uiQuadtreeTULog2MaxSize < m_uiQuadtreeTULog2MinSize,                "QuadtreeTULog2MaxSize must be greater than or equal to m_uiQuadtreeTULog2MinSize.");
2353  xConfirmPara( (1<<m_uiQuadtreeTULog2MaxSize) > m_uiMaxCUWidth,                      "QuadtreeTULog2MaxSize must be log2(maxCUSize) or smaller.");
2354  xConfirmPara( ( 1 << m_uiQuadtreeTULog2MinSize ) >= ( m_uiMaxCUWidth  >> (m_uiMaxCUDepth-1)), "QuadtreeTULog2MinSize must not be greater than or equal to minimum CU size" );
2355  xConfirmPara( ( 1 << m_uiQuadtreeTULog2MinSize ) >= ( m_uiMaxCUHeight >> (m_uiMaxCUDepth-1)), "QuadtreeTULog2MinSize must not be greater than or equal to minimum CU size" );
2356  xConfirmPara( m_uiQuadtreeTUMaxDepthInter < 1,                                                         "QuadtreeTUMaxDepthInter must be greater than or equal to 1" );
2357  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" );
2358  xConfirmPara( m_uiQuadtreeTUMaxDepthIntra < 1,                                                         "QuadtreeTUMaxDepthIntra must be greater than or equal to 1" );
2359  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" );
2360
2361  xConfirmPara(  m_maxNumMergeCand < 1,  "MaxNumMergeCand must be 1 or greater.");
2362  xConfirmPara(  m_maxNumMergeCand > 5,  "MaxNumMergeCand must be 5 or smaller.");
2363#if ADAPTIVE_QP_SELECTION
2364#if NH_MV
2365  for( Int layer = 0; layer < m_numberOfLayers; layer++ )
2366  {
2367    xConfirmPara( m_bUseAdaptQpSelect == true && m_iQP[layer] < 0,                                     "AdaptiveQpSelection must be disabled when QP < 0.");
2368  }
2369#else
2370  xConfirmPara( m_bUseAdaptQpSelect == true && m_iQP < 0,                                              "AdaptiveQpSelection must be disabled when QP < 0.");
2371#endif
2372  xConfirmPara( m_bUseAdaptQpSelect == true && (m_cbQpOffset !=0 || m_crQpOffset != 0 ),               "AdaptiveQpSelection must be disabled when ChromaQpOffset is not equal to 0.");
2373#endif
2374
2375  if( m_usePCM)
2376  {
2377    for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
2378    {
2379      xConfirmPara(((m_MSBExtendedBitDepth[channelType] > m_internalBitDepth[channelType]) && m_bPCMInputBitDepthFlag), "PCM bit depth cannot be greater than internal bit depth (PCMInputBitDepthFlag cannot be used when InputBitDepth or MSBExtendedBitDepth > InternalBitDepth)");
2380    }
2381    xConfirmPara(  m_uiPCMLog2MinSize < 3,                                      "PCMLog2MinSize must be 3 or greater.");
2382    xConfirmPara(  m_uiPCMLog2MinSize > 5,                                      "PCMLog2MinSize must be 5 or smaller.");
2383    xConfirmPara(  m_pcmLog2MaxSize > 5,                                        "PCMLog2MaxSize must be 5 or smaller.");
2384    xConfirmPara(  m_pcmLog2MaxSize < m_uiPCMLog2MinSize,                       "PCMLog2MaxSize must be equal to or greater than m_uiPCMLog2MinSize.");
2385  }
2386
2387  xConfirmPara( m_sliceMode < 0 || m_sliceMode > 3, "SliceMode exceeds supported range (0 to 3)" );
2388  if (m_sliceMode!=0)
2389  {
2390    xConfirmPara( m_sliceArgument < 1 ,         "SliceArgument should be larger than or equal to 1" );
2391  }
2392  xConfirmPara( m_sliceSegmentMode < 0 || m_sliceSegmentMode > 3, "SliceSegmentMode exceeds supported range (0 to 3)" );
2393  if (m_sliceSegmentMode!=0)
2394  {
2395    xConfirmPara( m_sliceSegmentArgument < 1 ,         "SliceSegmentArgument should be larger than or equal to 1" );
2396  }
2397
2398  Bool tileFlag = (m_numTileColumnsMinus1 > 0 || m_numTileRowsMinus1 > 0 );
2399  if (m_profile!=Profile::HIGHTHROUGHPUTREXT)
2400  {
2401    xConfirmPara( tileFlag && m_iWaveFrontSynchro,            "Tile and Wavefront can not be applied together, except in the High Throughput Intra 4:4:4 16 profile");
2402  }
2403
2404  xConfirmPara( m_iSourceWidth  % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Picture width must be an integer multiple of the specified chroma subsampling");
2405  xConfirmPara( m_iSourceHeight % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Picture height must be an integer multiple of the specified chroma subsampling");
2406
2407  xConfirmPara( m_aiPad[0] % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Horizontal padding must be an integer multiple of the specified chroma subsampling");
2408  xConfirmPara( m_aiPad[1] % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Vertical padding must be an integer multiple of the specified chroma subsampling");
2409
2410  xConfirmPara( m_confWinLeft   % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Left conformance window offset must be an integer multiple of the specified chroma subsampling");
2411  xConfirmPara( m_confWinRight  % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Right conformance window offset must be an integer multiple of the specified chroma subsampling");
2412  xConfirmPara( m_confWinTop    % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Top conformance window offset must be an integer multiple of the specified chroma subsampling");
2413  xConfirmPara( m_confWinBottom % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Bottom conformance window offset must be an integer multiple of the specified chroma subsampling");
2414
2415  xConfirmPara( m_defaultDisplayWindowFlag && !m_vuiParametersPresentFlag, "VUI needs to be enabled for default display window");
2416
2417  if (m_defaultDisplayWindowFlag)
2418  {
2419    xConfirmPara( m_defDispWinLeftOffset   % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Left default display window offset must be an integer multiple of the specified chroma subsampling");
2420    xConfirmPara( m_defDispWinRightOffset  % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Right default display window offset must be an integer multiple of the specified chroma subsampling");
2421    xConfirmPara( m_defDispWinTopOffset    % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Top default display window offset must be an integer multiple of the specified chroma subsampling");
2422    xConfirmPara( m_defDispWinBottomOffset % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Bottom default display window offset must be an integer multiple of the specified chroma subsampling");
2423  }
2424
2425  // max CU width and height should be power of 2
2426  UInt ui = m_uiMaxCUWidth;
2427  while(ui)
2428  {
2429    ui >>= 1;
2430    if( (ui & 1) == 1)
2431    {
2432      xConfirmPara( ui != 1 , "Width should be 2^n");
2433    }
2434  }
2435  ui = m_uiMaxCUHeight;
2436  while(ui)
2437  {
2438    ui >>= 1;
2439    if( (ui & 1) == 1)
2440    {
2441      xConfirmPara( ui != 1 , "Height should be 2^n");
2442    }
2443  }
2444
2445#if NH_MV
2446  // validate that POC of same frame is identical across multiple layers
2447  Bool bErrorMvePoc = false;
2448  if( m_numberOfLayers > 1 )
2449  {
2450    for( Int k = 1; k < m_numberOfLayers; k++ )
2451    {
2452      for( Int i = 0; i < MAX_GOP; i++ )
2453      {
2454        if( m_GOPListMvc[k][i].m_POC != m_GOPListMvc[0][i].m_POC )
2455        {
2456          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 );
2457          bErrorMvePoc = true;
2458        }
2459      }
2460    }
2461  }
2462  xConfirmPara( bErrorMvePoc,  "Invalid inter-layer POC structure given" );
2463
2464  // validate that baseview has no inter-view refs
2465  Bool bErrorIvpBase = false;
2466  for( Int i = 0; i < MAX_GOP; i++ )
2467  {
2468    if( m_GOPListMvc[0][i].m_numActiveRefLayerPics != 0 )
2469    {
2470      printf( "\nError: Frame%d inter_layer refs not available in layer 0\n", i );
2471      bErrorIvpBase = true;
2472    }
2473  }
2474  xConfirmPara( bErrorIvpBase, "Inter-layer refs not possible in base layer" );
2475
2476  // validate inter-view refs
2477  Bool bErrorIvpEnhV = false;
2478  if( m_numberOfLayers > 1 )
2479  {
2480    for( Int layer = 1; layer < m_numberOfLayers; layer++ )
2481    {
2482      for( Int i = 0; i < MAX_GOP+1; i++ )
2483      {
2484        GOPEntry gopEntry = m_GOPListMvc[layer][i]; 
2485        for( Int j = 0; j < gopEntry.m_numActiveRefLayerPics; j++ )
2486        {
2487          Int ilPredLayerIdc = gopEntry.m_interLayerPredLayerIdc[j];
2488          if( ilPredLayerIdc < 0 || ilPredLayerIdc >= m_directRefLayers[layer].size() )
2489          {
2490            printf( "\nError: inter-layer ref idc %d is not available for Frame%d_l%d\n", gopEntry.m_interLayerPredLayerIdc[j], i, layer );
2491            bErrorIvpEnhV = true;
2492          }
2493          if( gopEntry.m_interViewRefPosL[0][j] < -1 || gopEntry.m_interViewRefPosL[0][j] > gopEntry.m_numRefPicsActive )
2494          {
2495            printf( "\nError: inter-layer ref pos %d on L0 is not available for Frame%d_l%d\n", gopEntry.m_interViewRefPosL[0][j], i, layer );
2496            bErrorIvpEnhV = true;
2497          }
2498          if( gopEntry.m_interViewRefPosL[1][j] < -1  || gopEntry.m_interViewRefPosL[1][j] > gopEntry.m_numRefPicsActive )
2499          {
2500            printf( "\nError: inter-layer ref pos %d on L1 is not available for Frame%d_l%d\n", gopEntry.m_interViewRefPosL[1][j], i, layer );
2501            bErrorIvpEnhV = true;
2502          }
2503        }
2504        if( i == MAX_GOP ) // inter-view refs at I pic position in base view
2505        {
2506          if( gopEntry.m_sliceType != 'B' && gopEntry.m_sliceType != 'P' && gopEntry.m_sliceType != 'I' )
2507          {
2508            printf( "\nError: slice type of FrameI_l%d must be equal to B or P or I\n", layer );
2509            bErrorIvpEnhV = true;
2510          }
2511
2512          if( gopEntry.m_POC != 0 )
2513          {
2514            printf( "\nError: POC %d not possible for FrameI_l%d, must be 0\n", gopEntry.m_POC, layer );
2515            bErrorIvpEnhV = true;
2516          }
2517
2518          if( gopEntry.m_temporalId != 0 )
2519          {
2520            printf( "\nWarning: Temporal id of FrameI_l%d must be 0 (cp. I-frame in base layer)\n", layer );
2521            gopEntry.m_temporalId = 0;
2522          }
2523
2524          if( gopEntry.m_numRefPics != 0 )
2525          {
2526            printf( "\nWarning: temporal references not possible for FrameI_l%d\n", layer );
2527            for( Int j = 0; j < m_GOPListMvc[layer][MAX_GOP].m_numRefPics; j++ )
2528            {
2529              gopEntry.m_referencePics[j] = 0;
2530            }
2531            gopEntry.m_numRefPics = 0;
2532          }
2533
2534          if( gopEntry.m_interRPSPrediction )
2535          {
2536            printf( "\nError: inter RPS prediction not possible for FrameI_l%d, must be 0\n", layer );
2537            bErrorIvpEnhV = true;
2538          }
2539
2540          if( gopEntry.m_sliceType == 'I' && gopEntry.m_numActiveRefLayerPics != 0 )
2541          {
2542            printf( "\nError: inter-layer prediction not possible for FrameI_l%d with slice type I, #IL_ref_pics must be 0\n", layer );
2543            bErrorIvpEnhV = true;
2544          }
2545
2546          if( gopEntry.m_numRefPicsActive > gopEntry.m_numActiveRefLayerPics )
2547          {
2548            gopEntry.m_numRefPicsActive = gopEntry.m_numActiveRefLayerPics;
2549          }
2550
2551          if( gopEntry.m_sliceType == 'P' )
2552          {
2553            if( gopEntry.m_numActiveRefLayerPics < 1 )
2554            {
2555              printf( "\nError: #IL_ref_pics must be at least one for FrameI_l%d with slice type P\n", layer );
2556              bErrorIvpEnhV = true;
2557            }
2558            else
2559            {
2560              for( Int j = 0; j < gopEntry.m_numActiveRefLayerPics; j++ )
2561              {
2562                if( gopEntry.m_interViewRefPosL[1][j] != -1 )
2563                {
2564                  printf( "\nError: inter-layer ref pos %d on L1 not possible for FrameI_l%d with slice type P\n", gopEntry.m_interViewRefPosL[1][j], layer );
2565                  bErrorIvpEnhV = true;
2566                }
2567              }
2568            }
2569          }
2570
2571          if( gopEntry.m_sliceType == 'B' && gopEntry.m_numActiveRefLayerPics < 1 )
2572          {
2573            printf( "\nError: #IL_ref_pics must be at least one for FrameI_l%d with slice type B\n", layer );
2574            bErrorIvpEnhV = true;
2575          }
2576        }
2577      }
2578    }
2579  }
2580  xConfirmPara( bErrorIvpEnhV, "Invalid inter-layer coding structure for enhancement layers given" );
2581
2582  // validate temporal coding structure
2583  if( !bErrorMvePoc && !bErrorIvpBase && !bErrorIvpEnhV )
2584  {
2585    for( Int layer = 0; layer < m_numberOfLayers; layer++ )
2586    {
2587      GOPEntry* m_GOPList            = m_GOPListMvc           [layer]; // It is not a member, but this name helps avoiding code duplication !!!
2588      Int&      m_extraRPSs          = m_extraRPSsMvc         [layer]; // It is not a member, but this name helps avoiding code duplication !!!
2589      Int&      m_maxTempLayer       = m_maxTempLayerMvc      [layer]; // It is not a member, but this name helps avoiding code duplication !!!
2590      Int*      m_maxDecPicBuffering = m_maxDecPicBufferingMvc[layer]; // It is not a member, but this name helps avoiding code duplication !!!
2591      Int*      m_numReorderPics     = m_numReorderPicsMvc    [layer]; // It is not a member, but this name helps avoiding code duplication !!!
2592#endif
2593
2594  /* if this is an intra-only sequence, ie IntraPeriod=1, don't verify the GOP structure
2595   * This permits the ability to omit a GOP structure specification */
2596#if NH_MV
2597  if (m_iIntraPeriod[layer] == 1 && m_GOPList[0].m_POC == -1)
2598#else
2599  if (m_iIntraPeriod == 1 && m_GOPList[0].m_POC == -1)
2600#endif
2601  {
2602    m_GOPList[0] = GOPEntry();
2603    m_GOPList[0].m_QPFactor = 1;
2604    m_GOPList[0].m_betaOffsetDiv2 = 0;
2605    m_GOPList[0].m_tcOffsetDiv2 = 0;
2606    m_GOPList[0].m_POC = 1;
2607    m_GOPList[0].m_numRefPicsActive = 4;
2608  }
2609  else
2610  {
2611    xConfirmPara( m_intraConstraintFlag, "IntraConstraintFlag cannot be 1 for inter sequences");
2612  }
2613
2614  Bool verifiedGOP=false;
2615  Bool errorGOP=false;
2616  Int checkGOP=1;
2617  Int numRefs = m_isField ? 2 : 1;
2618  Int refList[MAX_NUM_REF_PICS+1];
2619  refList[0]=0;
2620  if(m_isField)
2621  {
2622    refList[1] = 1;
2623  }
2624  Bool isOK[MAX_GOP];
2625  for(Int i=0; i<MAX_GOP; i++)
2626  {
2627    isOK[i]=false;
2628  }
2629  Int numOK=0;
2630#if NH_MV
2631  xConfirmPara( m_iIntraPeriod[layer] >=0&&(m_iIntraPeriod[layer]%m_iGOPSize!=0), "Intra period must be a multiple of GOPSize, or -1" ); 
2632#else
2633  xConfirmPara( m_iIntraPeriod >=0&&(m_iIntraPeriod%m_iGOPSize!=0), "Intra period must be a multiple of GOPSize, or -1" );
2634#endif
2635
2636  for(Int i=0; i<m_iGOPSize; i++)
2637  {
2638    if(m_GOPList[i].m_POC==m_iGOPSize)
2639    {
2640      xConfirmPara( m_GOPList[i].m_temporalId!=0 , "The last frame in each GOP must have temporal ID = 0 " );
2641    }
2642  }
2643
2644#if NH_MV
2645  if ( (m_iIntraPeriod[layer] != 1) && !m_loopFilterOffsetInPPS && (!m_bLoopFilterDisable[layer]) )
2646#else
2647  if ( (m_iIntraPeriod != 1) && !m_loopFilterOffsetInPPS && (!m_bLoopFilterDisable) )
2648#endif
2649  {
2650    for(Int i=0; i<m_iGOPSize; i++)
2651    {
2652      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)" );
2653      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)" );
2654    }
2655  }
2656
2657  m_extraRPSs=0;
2658  //start looping through frames in coding order until we can verify that the GOP structure is correct.
2659  while(!verifiedGOP&&!errorGOP)
2660  {
2661    Int curGOP = (checkGOP-1)%m_iGOPSize;
2662    Int curPOC = ((checkGOP-1)/m_iGOPSize)*m_iGOPSize + m_GOPList[curGOP].m_POC;
2663    if(m_GOPList[curGOP].m_POC<0)
2664    {
2665#if NH_MV
2666      printf("\nError: found fewer Reference Picture Sets than GOPSize for layer %d\n", layer );
2667#else
2668      printf("\nError: found fewer Reference Picture Sets than GOPSize\n");
2669#endif
2670      errorGOP=true;
2671    }
2672    else
2673    {
2674      //check that all reference pictures are available, or have a POC < 0 meaning they might be available in the next GOP.
2675      Bool beforeI = false;
2676      for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++)
2677      {
2678        Int absPOC = curPOC+m_GOPList[curGOP].m_referencePics[i];
2679        if(absPOC < 0)
2680        {
2681          beforeI=true;
2682        }
2683        else
2684        {
2685          Bool found=false;
2686          for(Int j=0; j<numRefs; j++)
2687          {
2688            if(refList[j]==absPOC)
2689            {
2690              found=true;
2691              for(Int k=0; k<m_iGOPSize; k++)
2692              {
2693                if(absPOC%m_iGOPSize == m_GOPList[k].m_POC%m_iGOPSize)
2694                {
2695                  if(m_GOPList[k].m_temporalId==m_GOPList[curGOP].m_temporalId)
2696                  {
2697                    m_GOPList[k].m_refPic = true;
2698                  }
2699                  m_GOPList[curGOP].m_usedByCurrPic[i]=m_GOPList[k].m_temporalId<=m_GOPList[curGOP].m_temporalId;
2700                }
2701              }
2702            }
2703          }
2704          if(!found)
2705          {
2706#if NH_MV
2707            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);
2708#else
2709            printf("\nError: ref pic %d is not available for GOP frame %d\n",m_GOPList[curGOP].m_referencePics[i],curGOP+1);
2710#endif
2711            errorGOP=true;
2712          }
2713        }
2714      }
2715      if(!beforeI&&!errorGOP)
2716      {
2717        //all ref frames were present
2718        if(!isOK[curGOP])
2719        {
2720          numOK++;
2721          isOK[curGOP]=true;
2722          if(numOK==m_iGOPSize)
2723          {
2724            verifiedGOP=true;
2725          }
2726        }
2727      }
2728      else
2729      {
2730        //create a new GOPEntry for this frame containing all the reference pictures that were available (POC > 0)
2731        m_GOPList[m_iGOPSize+m_extraRPSs]=m_GOPList[curGOP];
2732        Int newRefs=0;
2733        for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++)
2734        {
2735          Int absPOC = curPOC+m_GOPList[curGOP].m_referencePics[i];
2736          if(absPOC>=0)
2737          {
2738            m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[newRefs]=m_GOPList[curGOP].m_referencePics[i];
2739            m_GOPList[m_iGOPSize+m_extraRPSs].m_usedByCurrPic[newRefs]=m_GOPList[curGOP].m_usedByCurrPic[i];
2740            newRefs++;
2741          }
2742        }
2743        Int numPrefRefs = m_GOPList[curGOP].m_numRefPicsActive;
2744
2745        for(Int offset = -1; offset>-checkGOP; offset--)
2746        {
2747          //step backwards in coding order and include any extra available pictures we might find useful to replace the ones with POC < 0.
2748          Int offGOP = (checkGOP-1+offset)%m_iGOPSize;
2749          Int offPOC = ((checkGOP-1+offset)/m_iGOPSize)*m_iGOPSize + m_GOPList[offGOP].m_POC;
2750          if(offPOC>=0&&m_GOPList[offGOP].m_temporalId<=m_GOPList[curGOP].m_temporalId)
2751          {
2752            Bool newRef=false;
2753            for(Int i=0; i<numRefs; i++)
2754            {
2755              if(refList[i]==offPOC)
2756              {
2757                newRef=true;
2758              }
2759            }
2760            for(Int i=0; i<newRefs; i++)
2761            {
2762              if(m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[i]==offPOC-curPOC)
2763              {
2764                newRef=false;
2765              }
2766            }
2767            if(newRef)
2768            {
2769              Int insertPoint=newRefs;
2770              //this picture can be added, find appropriate place in list and insert it.
2771              if(m_GOPList[offGOP].m_temporalId==m_GOPList[curGOP].m_temporalId)
2772              {
2773                m_GOPList[offGOP].m_refPic = true;
2774              }
2775              for(Int j=0; j<newRefs; j++)
2776              {
2777                if(m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j]<offPOC-curPOC||m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j]>0)
2778                {
2779                  insertPoint = j;
2780                  break;
2781                }
2782              }
2783              Int prev = offPOC-curPOC;
2784              Int prevUsed = m_GOPList[offGOP].m_temporalId<=m_GOPList[curGOP].m_temporalId;
2785              for(Int j=insertPoint; j<newRefs+1; j++)
2786              {
2787                Int newPrev = m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j];
2788                Int newUsed = m_GOPList[m_iGOPSize+m_extraRPSs].m_usedByCurrPic[j];
2789                m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j]=prev;
2790                m_GOPList[m_iGOPSize+m_extraRPSs].m_usedByCurrPic[j]=prevUsed;
2791                prevUsed=newUsed;
2792                prev=newPrev;
2793              }
2794              newRefs++;
2795            }
2796          }
2797          if(newRefs>=numPrefRefs)
2798          {
2799            break;
2800          }
2801        }
2802        m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefPics=newRefs;
2803        m_GOPList[m_iGOPSize+m_extraRPSs].m_POC = curPOC;
2804        if (m_extraRPSs == 0)
2805        {
2806          m_GOPList[m_iGOPSize+m_extraRPSs].m_interRPSPrediction = 0;
2807          m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefIdc = 0;
2808        }
2809        else
2810        {
2811          Int rIdx =  m_iGOPSize + m_extraRPSs - 1;
2812          Int refPOC = m_GOPList[rIdx].m_POC;
2813          Int refPics = m_GOPList[rIdx].m_numRefPics;
2814          Int newIdc=0;
2815          for(Int i = 0; i<= refPics; i++)
2816          {
2817            Int deltaPOC = ((i != refPics)? m_GOPList[rIdx].m_referencePics[i] : 0);  // check if the reference abs POC is >= 0
2818            Int absPOCref = refPOC+deltaPOC;
2819            Int refIdc = 0;
2820            for (Int j = 0; j < m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefPics; j++)
2821            {
2822              if ( (absPOCref - curPOC) == m_GOPList[m_iGOPSize+m_extraRPSs].m_referencePics[j])
2823              {
2824                if (m_GOPList[m_iGOPSize+m_extraRPSs].m_usedByCurrPic[j])
2825                {
2826                  refIdc = 1;
2827                }
2828                else
2829                {
2830                  refIdc = 2;
2831                }
2832              }
2833            }
2834            m_GOPList[m_iGOPSize+m_extraRPSs].m_refIdc[newIdc]=refIdc;
2835            newIdc++;
2836          }
2837          m_GOPList[m_iGOPSize+m_extraRPSs].m_interRPSPrediction = 1;
2838          m_GOPList[m_iGOPSize+m_extraRPSs].m_numRefIdc = newIdc;
2839          m_GOPList[m_iGOPSize+m_extraRPSs].m_deltaRPS = refPOC - m_GOPList[m_iGOPSize+m_extraRPSs].m_POC;
2840        }
2841        curGOP=m_iGOPSize+m_extraRPSs;
2842        m_extraRPSs++;
2843      }
2844      numRefs=0;
2845      for(Int i = 0; i< m_GOPList[curGOP].m_numRefPics; i++)
2846      {
2847        Int absPOC = curPOC+m_GOPList[curGOP].m_referencePics[i];
2848        if(absPOC >= 0)
2849        {
2850          refList[numRefs]=absPOC;
2851          numRefs++;
2852        }
2853      }
2854      refList[numRefs]=curPOC;
2855      numRefs++;
2856    }
2857    checkGOP++;
2858  }
2859  xConfirmPara(errorGOP,"Invalid GOP structure given");
2860  m_maxTempLayer = 1;
2861  for(Int i=0; i<m_iGOPSize; i++)
2862  {
2863    if(m_GOPList[i].m_temporalId >= m_maxTempLayer)
2864    {
2865      m_maxTempLayer = m_GOPList[i].m_temporalId+1;
2866    }
2867    xConfirmPara(m_GOPList[i].m_sliceType!='B' && m_GOPList[i].m_sliceType!='P' && m_GOPList[i].m_sliceType!='I', "Slice type must be equal to B or P or I");
2868  }
2869  for(Int i=0; i<MAX_TLAYER; i++)
2870  {
2871    m_numReorderPics[i] = 0;
2872    m_maxDecPicBuffering[i] = 1;
2873  }
2874  for(Int i=0; i<m_iGOPSize; i++)
2875  {
2876    if(m_GOPList[i].m_numRefPics+1 > m_maxDecPicBuffering[m_GOPList[i].m_temporalId])
2877    {
2878      m_maxDecPicBuffering[m_GOPList[i].m_temporalId] = m_GOPList[i].m_numRefPics + 1;
2879    }
2880    Int highestDecodingNumberWithLowerPOC = 0;
2881    for(Int j=0; j<m_iGOPSize; j++)
2882    {
2883      if(m_GOPList[j].m_POC <= m_GOPList[i].m_POC)
2884      {
2885        highestDecodingNumberWithLowerPOC = j;
2886      }
2887    }
2888    Int numReorder = 0;
2889    for(Int j=0; j<highestDecodingNumberWithLowerPOC; j++)
2890    {
2891      if(m_GOPList[j].m_temporalId <= m_GOPList[i].m_temporalId &&
2892        m_GOPList[j].m_POC > m_GOPList[i].m_POC)
2893      {
2894        numReorder++;
2895      }
2896    }
2897    if(numReorder > m_numReorderPics[m_GOPList[i].m_temporalId])
2898    {
2899      m_numReorderPics[m_GOPList[i].m_temporalId] = numReorder;
2900    }
2901  }
2902  for(Int i=0; i<MAX_TLAYER-1; i++)
2903  {
2904    // a lower layer can not have higher value of m_numReorderPics than a higher layer
2905    if(m_numReorderPics[i+1] < m_numReorderPics[i])
2906    {
2907      m_numReorderPics[i+1] = m_numReorderPics[i];
2908    }
2909    // the value of num_reorder_pics[ i ] shall be in the range of 0 to max_dec_pic_buffering[ i ] - 1, inclusive
2910    if(m_numReorderPics[i] > m_maxDecPicBuffering[i] - 1)
2911    {
2912      m_maxDecPicBuffering[i] = m_numReorderPics[i] + 1;
2913    }
2914    // a lower layer can not have higher value of m_uiMaxDecPicBuffering than a higher layer
2915    if(m_maxDecPicBuffering[i+1] < m_maxDecPicBuffering[i])
2916    {
2917      m_maxDecPicBuffering[i+1] = m_maxDecPicBuffering[i];
2918    }
2919  }
2920
2921  // the value of num_reorder_pics[ i ] shall be in the range of 0 to max_dec_pic_buffering[ i ] -  1, inclusive
2922  if(m_numReorderPics[MAX_TLAYER-1] > m_maxDecPicBuffering[MAX_TLAYER-1] - 1)
2923  {
2924    m_maxDecPicBuffering[MAX_TLAYER-1] = m_numReorderPics[MAX_TLAYER-1] + 1;
2925  }
2926
2927  if(m_vuiParametersPresentFlag && m_bitstreamRestrictionFlag)
2928  {
2929    Int PicSizeInSamplesY =  m_iSourceWidth * m_iSourceHeight;
2930    if(tileFlag)
2931    {
2932      Int maxTileWidth = 0;
2933      Int maxTileHeight = 0;
2934      Int widthInCU = (m_iSourceWidth % m_uiMaxCUWidth) ? m_iSourceWidth/m_uiMaxCUWidth + 1: m_iSourceWidth/m_uiMaxCUWidth;
2935      Int heightInCU = (m_iSourceHeight % m_uiMaxCUHeight) ? m_iSourceHeight/m_uiMaxCUHeight + 1: m_iSourceHeight/m_uiMaxCUHeight;
2936      if(m_tileUniformSpacingFlag)
2937      {
2938        maxTileWidth = m_uiMaxCUWidth*((widthInCU+m_numTileColumnsMinus1)/(m_numTileColumnsMinus1+1));
2939        maxTileHeight = m_uiMaxCUHeight*((heightInCU+m_numTileRowsMinus1)/(m_numTileRowsMinus1+1));
2940        // if only the last tile-row is one treeblock higher than the others
2941        // the maxTileHeight becomes smaller if the last row of treeblocks has lower height than the others
2942        if(!((heightInCU-1)%(m_numTileRowsMinus1+1)))
2943        {
2944          maxTileHeight = maxTileHeight - m_uiMaxCUHeight + (m_iSourceHeight % m_uiMaxCUHeight);
2945        }
2946        // if only the last tile-column is one treeblock wider than the others
2947        // the maxTileWidth becomes smaller if the last column of treeblocks has lower width than the others
2948        if(!((widthInCU-1)%(m_numTileColumnsMinus1+1)))
2949        {
2950          maxTileWidth = maxTileWidth - m_uiMaxCUWidth + (m_iSourceWidth % m_uiMaxCUWidth);
2951        }
2952      }
2953      else // not uniform spacing
2954      {
2955        if(m_numTileColumnsMinus1<1)
2956        {
2957          maxTileWidth = m_iSourceWidth;
2958        }
2959        else
2960        {
2961          Int accColumnWidth = 0;
2962          for(Int col=0; col<(m_numTileColumnsMinus1); col++)
2963          {
2964            maxTileWidth = m_tileColumnWidth[col]>maxTileWidth ? m_tileColumnWidth[col]:maxTileWidth;
2965            accColumnWidth += m_tileColumnWidth[col];
2966          }
2967          maxTileWidth = (widthInCU-accColumnWidth)>maxTileWidth ? m_uiMaxCUWidth*(widthInCU-accColumnWidth):m_uiMaxCUWidth*maxTileWidth;
2968        }
2969        if(m_numTileRowsMinus1<1)
2970        {
2971          maxTileHeight = m_iSourceHeight;
2972        }
2973        else
2974        {
2975          Int accRowHeight = 0;
2976          for(Int row=0; row<(m_numTileRowsMinus1); row++)
2977          {
2978            maxTileHeight = m_tileRowHeight[row]>maxTileHeight ? m_tileRowHeight[row]:maxTileHeight;
2979            accRowHeight += m_tileRowHeight[row];
2980          }
2981          maxTileHeight = (heightInCU-accRowHeight)>maxTileHeight ? m_uiMaxCUHeight*(heightInCU-accRowHeight):m_uiMaxCUHeight*maxTileHeight;
2982        }
2983      }
2984      Int maxSizeInSamplesY = maxTileWidth*maxTileHeight;
2985      m_minSpatialSegmentationIdc = 4*PicSizeInSamplesY/maxSizeInSamplesY-4;
2986    }
2987    else if(m_iWaveFrontSynchro)
2988    {
2989      m_minSpatialSegmentationIdc = 4*PicSizeInSamplesY/((2*m_iSourceHeight+m_iSourceWidth)*m_uiMaxCUHeight)-4;
2990    }
2991    else if(m_sliceMode == FIXED_NUMBER_OF_CTU)
2992    {
2993      m_minSpatialSegmentationIdc = 4*PicSizeInSamplesY/(m_sliceArgument*m_uiMaxCUWidth*m_uiMaxCUHeight)-4;
2994    }
2995    else
2996    {
2997      m_minSpatialSegmentationIdc = 0;
2998    }
2999  }
3000
3001  xConfirmPara( m_iWaveFrontSynchro < 0, "WaveFrontSynchro cannot be negative" );
3002
3003  xConfirmPara( m_decodedPictureHashSEIEnabled<0 || m_decodedPictureHashSEIEnabled>3, "this hash type is not correct!\n");
3004
3005  if (m_toneMappingInfoSEIEnabled)
3006  {
3007    xConfirmPara( m_toneMapCodedDataBitDepth < 8 || m_toneMapCodedDataBitDepth > 14 , "SEIToneMapCodedDataBitDepth must be in rage 8 to 14");
3008    xConfirmPara( m_toneMapTargetBitDepth < 1 || (m_toneMapTargetBitDepth > 16 && m_toneMapTargetBitDepth < 255) , "SEIToneMapTargetBitDepth must be in rage 1 to 16 or equal to 255");
3009    xConfirmPara( m_toneMapModelId < 0 || m_toneMapModelId > 4 , "SEIToneMapModelId must be in rage 0 to 4");
3010    xConfirmPara( m_cameraIsoSpeedValue == 0, "SEIToneMapCameraIsoSpeedValue shall not be equal to 0");
3011    xConfirmPara( m_exposureIndexValue  == 0, "SEIToneMapExposureIndexValue shall not be equal to 0");
3012    xConfirmPara( m_extendedRangeWhiteLevel < 100, "SEIToneMapExtendedRangeWhiteLevel should be greater than or equal to 100");
3013    xConfirmPara( m_nominalBlackLevelLumaCodeValue >= m_nominalWhiteLevelLumaCodeValue, "SEIToneMapNominalWhiteLevelLumaCodeValue shall be greater than SEIToneMapNominalBlackLevelLumaCodeValue");
3014    xConfirmPara( m_extendedWhiteLevelLumaCodeValue < m_nominalWhiteLevelLumaCodeValue, "SEIToneMapExtendedWhiteLevelLumaCodeValue shall be greater than or equal to SEIToneMapNominalWhiteLevelLumaCodeValue");
3015  }
3016
3017  if (m_kneeSEIEnabled && !m_kneeSEICancelFlag)
3018  {
3019    xConfirmPara( m_kneeSEINumKneePointsMinus1 < 0 || m_kneeSEINumKneePointsMinus1 > 998, "SEIKneeFunctionNumKneePointsMinus1 must be in the range of 0 to 998");
3020    for ( UInt i=0; i<=m_kneeSEINumKneePointsMinus1; i++ )
3021    {
3022      xConfirmPara( m_kneeSEIInputKneePoint[i] < 1 || m_kneeSEIInputKneePoint[i] > 999, "SEIKneeFunctionInputKneePointValue must be in the range of 1 to 999");
3023      xConfirmPara( m_kneeSEIOutputKneePoint[i] < 0 || m_kneeSEIOutputKneePoint[i] > 1000, "SEIKneeFunctionInputKneePointValue must be in the range of 0 to 1000");
3024      if ( i > 0 )
3025      {
3026        xConfirmPara( m_kneeSEIInputKneePoint[i-1] >= m_kneeSEIInputKneePoint[i],  "The i-th SEIKneeFunctionInputKneePointValue must be greater than the (i-1)-th value");
3027        xConfirmPara( m_kneeSEIOutputKneePoint[i-1] > m_kneeSEIOutputKneePoint[i],  "The i-th SEIKneeFunctionOutputKneePointValue must be greater than or equal to the (i-1)-th value");
3028      }
3029    }
3030  }
3031
3032  if ( m_RCEnableRateControl )
3033  {
3034    if ( m_RCForceIntraQP )
3035    {
3036      if ( m_RCInitialQP == 0 )
3037      {
3038        printf( "\nInitial QP for rate control is not specified. Reset not to use force intra QP!" );
3039        m_RCForceIntraQP = false;
3040      }
3041    }
3042    xConfirmPara( m_uiDeltaQpRD > 0, "Rate control cannot be used together with slice level multiple-QP optimization!\n" );
3043  }
3044#if NH_MV
3045  // VPS VUI
3046  for(Int i = 0; i < MAX_VPS_OP_SETS_PLUS1; i++ )
3047  { 
3048    for (Int j = 0; j < MAX_TLAYER; j++)
3049    {   
3050      if ( j < m_avgBitRate        [i].size() ) xConfirmPara( m_avgBitRate[i][j]         <  0 || m_avgBitRate[i][j]         > 65535, "avg_bit_rate            must be more than or equal to     0 and less than 65536" );
3051      if ( j < m_maxBitRate        [i].size() ) xConfirmPara( m_maxBitRate[i][j]         <  0 || m_maxBitRate[i][j]         > 65535, "max_bit_rate            must be more than or equal to     0 and less than 65536" );
3052      if ( j < m_constantPicRateIdc[i].size() ) xConfirmPara( m_constantPicRateIdc[i][j] <  0 || m_constantPicRateIdc[i][j] >     3, "constant_pic_rate_idc   must be more than or equal to     0 and less than     4" );
3053      if ( j < m_avgPicRate        [i].size() ) xConfirmPara( m_avgPicRate[i][j]         <  0 || m_avgPicRate[i][j]         > 65535, "avg_pic_rate            must be more than or equal to     0 and less than 65536" );
3054    }
3055  }
3056  // todo: replace value of 100 with requirement in spec
3057  for(Int i = 0; i < MAX_NUM_LAYERS; i++ )
3058  { 
3059    for (Int j = 0; j < MAX_NUM_LAYERS; j++)
3060    {   
3061      if ( j < m_minSpatialSegmentOffsetPlus1[i].size() ) xConfirmPara( m_minSpatialSegmentOffsetPlus1[i][j] < 0 || m_minSpatialSegmentOffsetPlus1[i][j] >   100, "min_spatial_segment_offset_plus1 must be more than or equal to     0 and less than   101" );
3062      if ( j < m_minHorizontalCtuOffsetPlus1[i] .size() ) xConfirmPara( m_minHorizontalCtuOffsetPlus1[i][j]  < 0 || m_minHorizontalCtuOffsetPlus1[i][j]  >   100, "min_horizontal_ctu_offset_plus1  must be more than or equal to     0 and less than   101" );
3063    }
3064  }
3065#endif
3066
3067  xConfirmPara(!m_TransquantBypassEnableFlag && m_CUTransquantBypassFlagForce, "CUTransquantBypassFlagForce cannot be 1 when TransquantBypassEnableFlag is 0");
3068
3069  xConfirmPara(m_log2ParallelMergeLevel < 2, "Log2ParallelMergeLevel should be larger than or equal to 2");
3070
3071  if (m_framePackingSEIEnabled)
3072  {
3073    xConfirmPara(m_framePackingSEIType < 3 || m_framePackingSEIType > 5 , "SEIFramePackingType must be in rage 3 to 5");
3074  }
3075#if NH_MV
3076  }
3077  }
3078  // Check input parameters for Sub-bitstream property SEI message
3079  if( m_subBistreamPropSEIEnabled )
3080  {
3081    xConfirmPara( 
3082      (this->m_sbPropNumAdditionalSubStreams != m_sbPropAvgBitRate.size() )
3083      || (this->m_sbPropNumAdditionalSubStreams != m_sbPropHighestSublayerId.size() )
3084      || (this->m_sbPropNumAdditionalSubStreams != m_sbPropMaxBitRate.size() )
3085      || (this->m_sbPropNumAdditionalSubStreams != m_sbPropOutputLayerSetIdxToVps.size() )
3086      || (this->m_sbPropNumAdditionalSubStreams != m_sbPropSubBitstreamMode.size()), "Some parameters of some sub-bitstream not defined");
3087
3088    for( Int i = 0; i < m_sbPropNumAdditionalSubStreams; i++ )
3089    {
3090      xConfirmPara( m_sbPropSubBitstreamMode[i] < 0 || m_sbPropSubBitstreamMode[i] > 1, "Mode value should be 0 or 1" );
3091      xConfirmPara( m_sbPropHighestSublayerId[i] < 0 || m_sbPropHighestSublayerId[i] > MAX_TLAYER-1, "Maximum sub-layer ID out of range" );
3092      xConfirmPara( m_sbPropOutputLayerSetIdxToVps[i] < 0 || m_sbPropOutputLayerSetIdxToVps[i] >= MAX_VPS_OUTPUTLAYER_SETS, "OutputLayerSetIdxToVps should be within allowed range" );
3093    }
3094  }
3095#endif
3096
3097  if (m_segmentedRectFramePackingSEIEnabled)
3098  {
3099    xConfirmPara(m_framePackingSEIEnabled > 0 , "SEISegmentedRectFramePacking must be 0 when SEIFramePacking is 1");
3100  }
3101
3102  if((m_numTileColumnsMinus1 <= 0) && (m_numTileRowsMinus1 <= 0) && m_tmctsSEIEnabled)
3103  {
3104    printf("Warning: SEITempMotionConstrainedTileSets is set to false to disable temporal motion-constrained tile sets SEI message because there are no tiles enabled.\n");
3105    m_tmctsSEIEnabled = false;
3106  }
3107
3108  if(m_timeCodeSEIEnabled)
3109  {
3110    xConfirmPara(m_timeCodeSEINumTs > MAX_TIMECODE_SEI_SETS, "Number of time sets cannot exceed 3");
3111  }
3112
3113#undef xConfirmPara
3114  if (check_failed)
3115  {
3116    exit(EXIT_FAILURE);
3117  }
3118}
3119
3120const Char *profileToString(const Profile::Name profile)
3121{
3122  static const UInt numberOfProfiles = sizeof(strToProfile)/sizeof(*strToProfile);
3123
3124  for (UInt profileIndex = 0; profileIndex < numberOfProfiles; profileIndex++)
3125  {
3126    if (strToProfile[profileIndex].value == profile)
3127    {
3128      return strToProfile[profileIndex].str;
3129    }
3130  }
3131
3132  //if we get here, we didn't find this profile in the list - so there is an error
3133  std::cerr << "ERROR: Unknown profile \"" << profile << "\" in profileToString" << std::endl;
3134  assert(false);
3135  exit(1);
3136  return "";
3137}
3138
3139Void TAppEncCfg::xPrintParameter()
3140{
3141  printf("\n");
3142#if NH_MV
3143  for( Int layer = 0; layer < m_numberOfLayers; layer++)
3144  {
3145    printf("Input File %i                     : %s\n", layer, m_pchInputFileList[layer]);
3146  }
3147#else
3148  printf("Input          File               : %s\n", m_pchInputFile          );
3149#endif
3150  printf("Bitstream      File               : %s\n", m_pchBitstreamFile      );
3151#if NH_MV
3152  for( Int layer = 0; layer < m_numberOfLayers; layer++)
3153  {
3154    printf("Reconstruction File %i            : %s\n", layer, m_pchReconFileList[layer]);
3155  }
3156#else
3157  printf("Reconstruction File               : %s\n", m_pchReconFile          );
3158#endif
3159#if NH_MV
3160  xPrintParaVector( "NuhLayerId"     , m_layerIdInNuh ); 
3161  if ( m_targetEncLayerIdList.size() > 0)
3162  {
3163    xPrintParaVector( "TargetEncLayerIdList"     , m_targetEncLayerIdList ); 
3164  }
3165  xPrintParaVector( "ViewIdVal"     , m_viewId ); 
3166  xPrintParaVector( "ViewOrderIdx"  , m_viewOrderIndex ); 
3167  xPrintParaVector( "AuxId", m_auxId );
3168#endif
3169#if NH_MV 
3170  xPrintParaVector( "QP"               , m_fQP                ); 
3171  xPrintParaVector( "LoopFilterDisable", m_bLoopFilterDisable ); 
3172  xPrintParaVector( "SAO"              , m_bUseSAO            ); 
3173#endif
3174
3175  printf("Real     Format                   : %dx%d %dHz\n", m_iSourceWidth - m_confWinLeft - m_confWinRight, m_iSourceHeight - m_confWinTop - m_confWinBottom, m_iFrameRate );
3176  printf("Internal Format                   : %dx%d %dHz\n", m_iSourceWidth, m_iSourceHeight, m_iFrameRate );
3177  printf("Sequence PSNR output              : %s\n", (m_printMSEBasedSequencePSNR ? "Linear average, MSE-based" : "Linear average only") );
3178  printf("Sequence MSE output               : %s\n", (m_printSequenceMSE ? "Enabled" : "Disabled") );
3179  printf("Frame MSE output                  : %s\n", (m_printFrameMSE    ? "Enabled" : "Disabled") );
3180  printf("Cabac-zero-word-padding           : %s\n", (m_cabacZeroWordPaddingEnabled? "Enabled" : "Disabled") );
3181  if (m_isField)
3182  {
3183    printf("Frame/Field                       : Field based coding\n");
3184    printf("Field index                       : %u - %d (%d fields)\n", m_FrameSkip, m_FrameSkip+m_framesToBeEncoded-1, m_framesToBeEncoded );
3185    printf("Field Order                       : %s field first\n", m_isTopFieldFirst?"Top":"Bottom");
3186
3187  }
3188  else
3189  {
3190    printf("Frame/Field                       : Frame based coding\n");
3191    printf("Frame index                       : %u - %d (%d frames)\n", m_FrameSkip, m_FrameSkip+m_framesToBeEncoded-1, m_framesToBeEncoded );
3192  }
3193#if NH_MV
3194  printf("Profile                           :");
3195  for (Int i = 0; i < m_profiles.size(); i++)
3196  {
3197    Profile::Name m_profile = m_profiles[i];
3198
3199#endif
3200    if (m_profile == Profile::MAINREXT)
3201    {
3202    ExtendedProfileName validProfileName;
3203    if (m_onePictureOnlyConstraintFlag)
3204    {
3205      validProfileName = m_bitDepthConstraint == 8 ? MAIN_444_STILL_PICTURE : (m_bitDepthConstraint == 16 ? MAIN_444_16_STILL_PICTURE : NONE);
3206    }
3207    else
3208    {
3209      const UInt intraIdx = m_intraConstraintFlag ? 1:0;
3210      const UInt bitDepthIdx = (m_bitDepthConstraint == 8 ? 0 : (m_bitDepthConstraint ==10 ? 1 : (m_bitDepthConstraint == 12 ? 2 : (m_bitDepthConstraint == 16 ? 3 : 4 ))));
3211      const UInt chromaFormatIdx = UInt(m_chromaFormatConstraint);
3212      validProfileName = (bitDepthIdx > 3 || chromaFormatIdx>3) ? NONE : validRExtProfileNames[intraIdx][bitDepthIdx][chromaFormatIdx];
3213    }
3214      std::string rextSubProfile;
3215      if (validProfileName!=NONE)
3216      {
3217        rextSubProfile=enumToString(strToExtendedProfile, sizeof(strToExtendedProfile)/sizeof(*strToExtendedProfile), validProfileName);
3218      }
3219      if (rextSubProfile == "main_444_16")
3220      {
3221        rextSubProfile="main_444_16 [NON STANDARD]";
3222      }
3223#if NH_MV
3224      printf(" %s (%s) ", profileToString(m_profile), (rextSubProfile.empty())?"INVALID REXT PROFILE":rextSubProfile.c_str() );
3225#else
3226      printf("Profile                           : %s (%s)\n", profileToString(m_profile), (rextSubProfile.empty())?"INVALID REXT PROFILE":rextSubProfile.c_str() );
3227#endif
3228    }
3229    else
3230    {
3231#if NH_MV
3232      printf(" %s ", profileToString(m_profile) );
3233#else
3234      printf("Profile                           : %s\n", profileToString(m_profile) );
3235#endif
3236    }
3237#if NH_MV   
3238  }
3239  printf("\n");
3240#endif
3241
3242  printf("CU size / depth / total-depth     : %d / %d / %d\n", m_uiMaxCUWidth, m_uiMaxCUDepth, m_uiMaxTotalCUDepth );
3243  printf("RQT trans. size (min / max)       : %d / %d\n", 1 << m_uiQuadtreeTULog2MinSize, 1 << m_uiQuadtreeTULog2MaxSize );
3244  printf("Max RQT depth inter               : %d\n", m_uiQuadtreeTUMaxDepthInter);
3245  printf("Max RQT depth intra               : %d\n", m_uiQuadtreeTUMaxDepthIntra);
3246  printf("Min PCM size                      : %d\n", 1 << m_uiPCMLog2MinSize);
3247  printf("Motion search range               : %d\n", m_iSearchRange );
3248#if NH_MV
3249  printf("Disp search range restriction     : %d\n", m_bUseDisparitySearchRangeRestriction );
3250  printf("Vertical disp search range        : %d\n", m_iVerticalDisparitySearchRange );
3251#endif
3252#if NH_MV
3253  xPrintParaVector( "Intra period", m_iIntraPeriod );
3254#else
3255  printf("Intra period                      : %d\n", m_iIntraPeriod );
3256#endif
3257  printf("Decoding refresh type             : %d\n", m_iDecodingRefreshType );
3258#if !NH_MV
3259  printf("QP                                : %5.2f\n", m_fQP );
3260#endif
3261  printf("Max dQP signaling depth           : %d\n", m_iMaxCuDQPDepth);
3262
3263  printf("Cb QP Offset                      : %d\n", m_cbQpOffset   );
3264  printf("Cr QP Offset                      : %d\n", m_crQpOffset);
3265  printf("QP adaptation                     : %d (range=%d)\n", m_bUseAdaptiveQP, (m_bUseAdaptiveQP ? m_iQPAdaptationRange : 0) );
3266  printf("GOP size                          : %d\n", m_iGOPSize );
3267  printf("Input bit depth                   : (Y:%d, C:%d)\n", m_inputBitDepth[CHANNEL_TYPE_LUMA], m_inputBitDepth[CHANNEL_TYPE_CHROMA] );
3268  printf("MSB-extended bit depth            : (Y:%d, C:%d)\n", m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA], m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] );
3269  printf("Internal bit depth                : (Y:%d, C:%d)\n", m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA] );
3270  printf("PCM sample bit depth              : (Y:%d, C:%d)\n", m_bPCMInputBitDepthFlag ? m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA] : m_internalBitDepth[CHANNEL_TYPE_LUMA],
3271                                                               m_bPCMInputBitDepthFlag ? m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] : m_internalBitDepth[CHANNEL_TYPE_CHROMA] );
3272  printf("Intra reference smoothing         : %s\n", (m_enableIntraReferenceSmoothing          ? "Enabled" : "Disabled") );
3273  printf("diff_cu_chroma_qp_offset_depth         : %d\n", m_diffCuChromaQpOffsetDepth);
3274  printf("extended_precision_processing_flag     : %s\n", (m_extendedPrecisionProcessingFlag         ? "Enabled" : "Disabled") );
3275  printf("implicit_rdpcm_enabled_flag            : %s\n", (m_rdpcmEnabledFlag[RDPCM_SIGNAL_IMPLICIT] ? "Enabled" : "Disabled") );
3276  printf("explicit_rdpcm_enabled_flag            : %s\n", (m_rdpcmEnabledFlag[RDPCM_SIGNAL_EXPLICIT] ? "Enabled" : "Disabled") );
3277  printf("transform_skip_rotation_enabled_flag   : %s\n", (m_transformSkipRotationEnabledFlag        ? "Enabled" : "Disabled") );
3278  printf("transform_skip_context_enabled_flag    : %s\n", (m_transformSkipContextEnabledFlag         ? "Enabled" : "Disabled") );
3279  printf("cross_component_prediction_enabled_flag: %s\n", (m_crossComponentPredictionEnabledFlag     ? (m_reconBasedCrossCPredictionEstimate ? "Enabled (reconstructed-residual-based estimate)" : "Enabled (encoder-side-residual-based estimate)") : "Disabled") );
3280  printf("high_precision_offsets_enabled_flag    : %s\n", (m_highPrecisionOffsetsEnabledFlag         ? "Enabled" : "Disabled") );
3281  printf("persistent_rice_adaptation_enabled_flag: %s\n", (m_persistentRiceAdaptationEnabledFlag     ? "Enabled" : "Disabled") );
3282  printf("cabac_bypass_alignment_enabled_flag    : %s\n", (m_cabacBypassAlignmentEnabledFlag         ? "Enabled" : "Disabled") );
3283#if NH_MV
3284  Bool anySAO = false; 
3285  IntAry1d saoOffBitShiftL;
3286  IntAry1d saoOffBitShiftC;
3287
3288  for (Int i = 0; i < m_numberOfLayers; i++)
3289  {
3290    if ( m_bUseSAO[i] )
3291    {
3292      anySAO = true; 
3293      saoOffBitShiftL.push_back( m_log2SaoOffsetScale[i][CHANNEL_TYPE_LUMA] );
3294      saoOffBitShiftC.push_back( m_log2SaoOffsetScale[i][CHANNEL_TYPE_CHROMA] );
3295    }
3296    else
3297    {
3298      saoOffBitShiftL.push_back( -1 );
3299      saoOffBitShiftC.push_back( -1 );
3300    }
3301  }
3302  if (anySAO)
3303  {
3304    xPrintParaVector( "Sao Luma Offset bit shifts"  , saoOffBitShiftL );
3305    xPrintParaVector( "Sao Chroma Offset bit shifts", saoOffBitShiftC );
3306  }
3307#else
3308  if (m_bUseSAO)
3309  {
3310    printf("log2_sao_offset_scale_luma             : %d\n", m_log2SaoOffsetScale[CHANNEL_TYPE_LUMA]);
3311    printf("log2_sao_offset_scale_chroma           : %d\n", m_log2SaoOffsetScale[CHANNEL_TYPE_CHROMA]);
3312  }
3313#endif
3314
3315  switch (m_costMode)
3316  {
3317    case COST_STANDARD_LOSSY:               printf("Cost function:                    : Lossy coding (default)\n"); break;
3318    case COST_SEQUENCE_LEVEL_LOSSLESS:      printf("Cost function:                    : Sequence_level_lossless coding\n"); break;
3319    case COST_LOSSLESS_CODING:              printf("Cost function:                    : Lossless coding with fixed QP of %d\n", LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP); break;
3320    case COST_MIXED_LOSSLESS_LOSSY_CODING:  printf("Cost function:                    : Mixed_lossless_lossy coding with QP'=%d for lossless evaluation\n", LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME); break;
3321    default:                                printf("Cost function:                    : Unknown\n"); break;
3322  }
3323
3324  printf("RateControl                       : %d\n", m_RCEnableRateControl );
3325
3326  if(m_RCEnableRateControl)
3327  {
3328    printf("TargetBitrate                     : %d\n", m_RCTargetBitrate );
3329    printf("KeepHierarchicalBit               : %d\n", m_RCKeepHierarchicalBit );
3330    printf("LCULevelRC                        : %d\n", m_RCLCULevelRC );
3331    printf("UseLCUSeparateModel               : %d\n", m_RCUseLCUSeparateModel );
3332    printf("InitialQP                         : %d\n", m_RCInitialQP );
3333    printf("ForceIntraQP                      : %d\n", m_RCForceIntraQP );
3334
3335
3336  }
3337
3338  printf("Max Num Merge Candidates          : %d\n", m_maxNumMergeCand);
3339  printf("\n");
3340#if NH_MV
3341  printf("TOOL CFG General: ");
3342#else
3343  printf("TOOL CFG: ");
3344#endif
3345  printf("IBD:%d ", ((m_internalBitDepth[CHANNEL_TYPE_LUMA] > m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA]) || (m_internalBitDepth[CHANNEL_TYPE_CHROMA] > m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA])));
3346  printf("HAD:%d ", m_bUseHADME           );
3347  printf("RDQ:%d ", m_useRDOQ            );
3348  printf("RDQTS:%d ", m_useRDOQTS        );
3349  printf("RDpenalty:%d ", m_rdPenalty  );
3350  printf("SQP:%d ", m_uiDeltaQpRD         );
3351  printf("ASR:%d ", m_bUseASR             );
3352  printf("FEN:%d ", m_bUseFastEnc         );
3353  printf("ECU:%d ", m_bUseEarlyCU         );
3354  printf("FDM:%d ", m_useFastDecisionForMerge );
3355  printf("CFM:%d ", m_bUseCbfFastMode         );
3356  printf("ESD:%d ", m_useEarlySkipDetection  );
3357  printf("RQT:%d ", 1     );
3358  printf("TransformSkip:%d ",     m_useTransformSkip              );
3359  printf("TransformSkipFast:%d ", m_useTransformSkipFast       );
3360  printf("TransformSkipLog2MaxSize:%d ", m_log2MaxTransformSkipBlockSize);
3361  printf("Slice: M=%d ", m_sliceMode);
3362  if (m_sliceMode!=NO_SLICES)
3363  {
3364    printf("A=%d ", m_sliceArgument);
3365  }
3366  printf("SliceSegment: M=%d ",m_sliceSegmentMode);
3367  if (m_sliceSegmentMode!=NO_SLICES)
3368  {
3369    printf("A=%d ", m_sliceSegmentArgument);
3370  }
3371  printf("CIP:%d ", m_bUseConstrainedIntraPred);
3372#if !NH_MV
3373  printf("SAO:%d ", (m_bUseSAO)?(1):(0));
3374#endif
3375  printf("PCM:%d ", (m_usePCM && (1<<m_uiPCMLog2MinSize) <= m_uiMaxCUWidth)? 1 : 0);
3376
3377  if (m_TransquantBypassEnableFlag && m_CUTransquantBypassFlagForce)
3378  {
3379    printf("TransQuantBypassEnabled: =1");
3380  }
3381  else
3382  {
3383    printf("TransQuantBypassEnabled:%d ", (m_TransquantBypassEnableFlag)? 1:0 );
3384  }
3385
3386  printf("WPP:%d ", (Int)m_useWeightedPred);
3387  printf("WPB:%d ", (Int)m_useWeightedBiPred);
3388  printf("PME:%d ", m_log2ParallelMergeLevel);
3389  const Int iWaveFrontSubstreams = m_iWaveFrontSynchro ? (m_iSourceHeight + m_uiMaxCUHeight - 1) / m_uiMaxCUHeight : 1;
3390  printf(" WaveFrontSynchro:%d WaveFrontSubstreams:%d",
3391          m_iWaveFrontSynchro, iWaveFrontSubstreams);
3392  printf(" ScalingList:%d ", m_useScalingListId );
3393  printf("TMVPMode:%d ", m_TMVPModeId     );
3394#if ADAPTIVE_QP_SELECTION
3395  printf("AQpS:%d", m_bUseAdaptQpSelect   );
3396#endif
3397
3398  printf(" SignBitHidingFlag:%d ", m_signHideFlag);
3399  printf("RecalQP:%d", m_recalculateQPAccordingToLambda ? 1 : 0 );
3400
3401  printf("\n\n");
3402
3403  fflush(stdout);
3404}
3405
3406Bool confirmPara(Bool bflag, const Char* message)
3407{
3408  if (!bflag)
3409  {
3410    return false;
3411  }
3412
3413  printf("Error: %s\n",message);
3414  return true;
3415}
3416
3417//! \}
Note: See TracBrowser for help on using the repository browser.