Skip to content
Snippets Groups Projects
EncAppCfg.cpp 194 KiB
Newer Older
  • Learn to ignore specific revisions
  • 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
    /* The copyright in this software is being made available under the BSD
     * License, included below. This software may be subject to other third party
     * and contributor rights, including patent rights, and no such rights are
     * granted under this license.
     *
     * Copyright (c) 2010-2018, ITU/ISO/IEC
     * All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions are met:
     *
     *  * Redistributions of source code must retain the above copyright notice,
     *    this list of conditions and the following disclaimer.
     *  * Redistributions in binary form must reproduce the above copyright notice,
     *    this list of conditions and the following disclaimer in the documentation
     *    and/or other materials provided with the distribution.
     *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
     *    be used to endorse or promote products derived from this software without
     *    specific prior written permission.
     *
     * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
     * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
     * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
     * THE POSSIBILITY OF SUCH DAMAGE.
     */
    
    /** \file     EncAppCfg.cpp
        \brief    Handle encoder configuration parameters
    */
    
    #include "EncAppCfg.h"
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <cstring>
    #include <string>
    #include <fstream>
    #include <limits>
    
    #include "Utilities/program_options_lite.h"
    #include "CommonLib/Rom.h"
    #include "EncoderLib/RateCtrl.h"
    
    #include "CommonLib/dtrace_next.h"
    
    #define MACRO_TO_STRING_HELPER(val) #val
    #define MACRO_TO_STRING(val) MACRO_TO_STRING_HELPER(val)
    
    using namespace std;
    namespace po = df::program_options_lite;
    
    
    
    enum ExtendedProfileName // this is used for determining profile strings, where multiple profiles map to a single profile idc with various constraint flag combinations
    {
      NONE = 0,
      MAIN = 1,
      MAIN10 = 2,
      MAINSTILLPICTURE = 3,
      MAINREXT = 4,
      HIGHTHROUGHPUTREXT = 5, // Placeholder profile for development
      // The following are RExt profiles, which would map to the MAINREXT profile idc.
      // The enumeration indicates the bit-depth constraint in the bottom 2 digits
      //                           the chroma format in the next digit
      //                           the intra constraint in the next digit
      //                           If it is a RExt still picture, there is a '1' for the top digit.
      MONOCHROME_8      = 1008,
      MONOCHROME_12     = 1012,
      MONOCHROME_16     = 1016,
      MAIN_12           = 1112,
      MAIN_422_10       = 1210,
      MAIN_422_12       = 1212,
      MAIN_444          = 1308,
      MAIN_444_10       = 1310,
      MAIN_444_12       = 1312,
      MAIN_444_16       = 1316, // non-standard profile definition, used for development purposes
      MAIN_INTRA        = 2108,
      MAIN_10_INTRA     = 2110,
      MAIN_12_INTRA     = 2112,
      MAIN_422_10_INTRA = 2210,
      MAIN_422_12_INTRA = 2212,
      MAIN_444_INTRA    = 2308,
      MAIN_444_10_INTRA = 2310,
      MAIN_444_12_INTRA = 2312,
      MAIN_444_16_INTRA = 2316,
      MAIN_444_STILL_PICTURE = 11308,
      MAIN_444_16_STILL_PICTURE = 12316,
      NEXT          = 6
    };
    
    
    //! \ingroup EncoderApp
    //! \{
    
    // ====================================================================================================================
    // Constructor / destructor / initialization / destroy
    // ====================================================================================================================
    
    EncAppCfg::EncAppCfg()
    : m_inputColourSpaceConvert(IPCOLOURSPACE_UNCHANGED)
    , m_snrInternalColourSpace(false)
    , m_outputInternalColourSpace(false)
    #if EXTENSION_360_VIDEO
    , m_ext360(*this)
    #endif
    {
      m_aidQP = NULL;
      m_startOfCodedInterval = NULL;
      m_codedPivotValue = NULL;
      m_targetPivotValue = NULL;
    }
    
    EncAppCfg::~EncAppCfg()
    {
      if ( m_aidQP )
      {
        delete[] m_aidQP;
      }
      if ( m_startOfCodedInterval )
      {
        delete[] m_startOfCodedInterval;
        m_startOfCodedInterval = NULL;
      }
       if ( m_codedPivotValue )
      {
        delete[] m_codedPivotValue;
        m_codedPivotValue = NULL;
      }
      if ( m_targetPivotValue )
      {
        delete[] m_targetPivotValue;
        m_targetPivotValue = NULL;
      }
    
    #if ENABLE_TRACING
      tracing_uninit(g_trace_ctx);
    #endif
    }
    
    void EncAppCfg::create()
    {
    }
    
    void EncAppCfg::destroy()
    {
    }
    
    std::istringstream &operator>>(std::istringstream &in, GOPEntry &entry)     //input
    {
      in>>entry.m_sliceType;
      in>>entry.m_POC;
      in>>entry.m_QPOffset;
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
      in>>entry.m_QPOffsetModelOffset;
      in>>entry.m_QPOffsetModelScale;
    #endif
    #if W0038_CQP_ADJ
      in>>entry.m_CbQPoffset;
      in>>entry.m_CrQPoffset;
    #endif
      in>>entry.m_QPFactor;
      in>>entry.m_tcOffsetDiv2;
      in>>entry.m_betaOffsetDiv2;
      in>>entry.m_temporalId;
      in>>entry.m_numRefPicsActive;
      in>>entry.m_numRefPics;
      for ( int i = 0; i < entry.m_numRefPics; i++ )
      {
        in>>entry.m_referencePics[i];
      }
      in>>entry.m_interRPSPrediction;
      if (entry.m_interRPSPrediction==1)
      {
        in>>entry.m_deltaRPS;
        in>>entry.m_numRefIdc;
        for ( int i = 0; i < entry.m_numRefIdc; i++ )
        {
          in>>entry.m_refIdc[i];
        }
      }
      else if (entry.m_interRPSPrediction==2)
      {
        in>>entry.m_deltaRPS;
      }
      return in;
    }
    
    bool confirmPara(bool bflag, const char* message);
    
    static inline ChromaFormat numberToChromaFormat(const int val)
    {
      switch (val)
      {
        case 400: return CHROMA_400; break;
        case 420: return CHROMA_420; break;
        case 422: return CHROMA_422; break;
        case 444: return CHROMA_444; break;
        default:  return NUM_CHROMA_FORMAT;
      }
    }
    
    static const struct MapStrToProfile
    {
      const char* str;
      Profile::Name value;
    }
    strToProfile[] =
    {
      {"none",                 Profile::NONE               },
      {"main",                 Profile::MAIN               },
      {"main10",               Profile::MAIN10             },
      {"main-still-picture",   Profile::MAINSTILLPICTURE   },
      {"main-RExt",            Profile::MAINREXT           },
      {"high-throughput-RExt", Profile::HIGHTHROUGHPUTREXT },
      {"next",                 Profile::NEXT           }
    };
    
    static const struct MapStrToExtendedProfile
    {
      const char* str;
      ExtendedProfileName value;
    }
    strToExtendedProfile[] =
    {
        {"none",                      NONE             },
        {"main",                      MAIN             },
        {"main10",                    MAIN10           },
        {"main_still_picture",        MAINSTILLPICTURE },
        {"main-still-picture",        MAINSTILLPICTURE },
        {"main_RExt",                 MAINREXT         },
        {"main-RExt",                 MAINREXT         },
        {"main_rext",                 MAINREXT         },
        {"main-rext",                 MAINREXT         },
        {"high_throughput_RExt",      HIGHTHROUGHPUTREXT },
        {"high-throughput-RExt",      HIGHTHROUGHPUTREXT },
        {"high_throughput_rext",      HIGHTHROUGHPUTREXT },
        {"high-throughput-rext",      HIGHTHROUGHPUTREXT },
        {"monochrome",                MONOCHROME_8     },
        {"monochrome12",              MONOCHROME_12    },
        {"monochrome16",              MONOCHROME_16    },
        {"main12",                    MAIN_12          },
        {"main_422_10",               MAIN_422_10      },
        {"main_422_12",               MAIN_422_12      },
        {"main_444",                  MAIN_444         },
        {"main_444_10",               MAIN_444_10      },
        {"main_444_12",               MAIN_444_12      },
        {"main_444_16",               MAIN_444_16      },
        {"main_intra",                MAIN_INTRA       },
        {"main_10_intra",             MAIN_10_INTRA    },
        {"main_12_intra",             MAIN_12_INTRA    },
        {"main_422_10_intra",         MAIN_422_10_INTRA},
        {"main_422_12_intra",         MAIN_422_12_INTRA},
        {"main_444_intra",            MAIN_444_INTRA   },
        {"main_444_still_picture",    MAIN_444_STILL_PICTURE },
        {"main_444_10_intra",         MAIN_444_10_INTRA},
        {"main_444_12_intra",         MAIN_444_12_INTRA},
        {"main_444_16_intra",         MAIN_444_16_INTRA},
        {"main_444_16_still_picture", MAIN_444_16_STILL_PICTURE },
        {"next",                      NEXT }
    };
    
    static const ExtendedProfileName validRExtProfileNames[2/* intraConstraintFlag*/][4/* bit depth constraint 8=0, 10=1, 12=2, 16=3*/][4/*chroma format*/]=
    {
        {
            { MONOCHROME_8,  NONE,          NONE,              MAIN_444          }, // 8-bit  inter for 400, 420, 422 and 444
            { NONE,          NONE,          MAIN_422_10,       MAIN_444_10       }, // 10-bit inter for 400, 420, 422 and 444
            { MONOCHROME_12, MAIN_12,       MAIN_422_12,       MAIN_444_12       }, // 12-bit inter for 400, 420, 422 and 444
            { MONOCHROME_16, NONE,          NONE,              MAIN_444_16       }  // 16-bit inter for 400, 420, 422 and 444 (the latter is non standard used for development)
        },
        {
            { NONE,          MAIN_INTRA,    NONE,              MAIN_444_INTRA    }, // 8-bit  intra for 400, 420, 422 and 444
            { NONE,          MAIN_10_INTRA, MAIN_422_10_INTRA, MAIN_444_10_INTRA }, // 10-bit intra for 400, 420, 422 and 444
            { NONE,          MAIN_12_INTRA, MAIN_422_12_INTRA, MAIN_444_12_INTRA }, // 12-bit intra for 400, 420, 422 and 444
            { NONE,          NONE,          NONE,              MAIN_444_16_INTRA }  // 16-bit intra for 400, 420, 422 and 444
        }
    };
    
    static const struct MapStrToTier
    {
      const char* str;
      Level::Tier value;
    }
    strToTier[] =
    {
      {"main", Level::MAIN},
      {"high", Level::HIGH},
    };
    
    static const struct MapStrToLevel
    {
      const char* str;
      Level::Name value;
    }
    strToLevel[] =
    {
      {"none",Level::NONE},
      {"1",   Level::LEVEL1},
      {"2",   Level::LEVEL2},
      {"2.1", Level::LEVEL2_1},
      {"3",   Level::LEVEL3},
      {"3.1", Level::LEVEL3_1},
      {"4",   Level::LEVEL4},
      {"4.1", Level::LEVEL4_1},
      {"5",   Level::LEVEL5},
      {"5.1", Level::LEVEL5_1},
      {"5.2", Level::LEVEL5_2},
      {"6",   Level::LEVEL6},
      {"6.1", Level::LEVEL6_1},
      {"6.2", Level::LEVEL6_2},
      {"8.5", Level::LEVEL8_5},
    };
    
    #if U0132_TARGET_BITS_SATURATION
    uint32_t g_uiMaxCpbSize[2][21] =
    {
      //         LEVEL1,        LEVEL2,LEVEL2_1,     LEVEL3, LEVEL3_1,      LEVEL4, LEVEL4_1,       LEVEL5,  LEVEL5_1,  LEVEL5_2,    LEVEL6,  LEVEL6_1,  LEVEL6_2
      { 0, 0, 0, 350000, 0, 0, 1500000, 3000000, 0, 6000000, 10000000, 0, 12000000, 20000000, 0,  25000000,  40000000,  60000000,  60000000, 120000000, 240000000 },
      { 0, 0, 0,      0, 0, 0,       0,       0, 0,       0,        0, 0, 30000000, 50000000, 0, 100000000, 160000000, 240000000, 240000000, 480000000, 800000000 }
    };
    #endif
    
    static const struct MapStrToCostMode
    {
      const char* str;
      CostMode    value;
    }
    strToCostMode[] =
    {
      {"lossy",                     COST_STANDARD_LOSSY},
      {"sequence_level_lossless",   COST_SEQUENCE_LEVEL_LOSSLESS},
      {"lossless",                  COST_LOSSLESS_CODING},
      {"mixed_lossless_lossy",      COST_MIXED_LOSSLESS_LOSSY_CODING}
    };
    
    #if HEVC_USE_SCALING_LISTS
    static const struct MapStrToScalingListMode
    {
      const char* str;
      ScalingListMode value;
    }
    strToScalingListMode[] =
    {
      {"0",       SCALING_LIST_OFF},
      {"1",       SCALING_LIST_DEFAULT},
      {"2",       SCALING_LIST_FILE_READ},
      {"off",     SCALING_LIST_OFF},
      {"default", SCALING_LIST_DEFAULT},
      {"file",    SCALING_LIST_FILE_READ}
    };
    #endif
    
    template<typename T, typename P>
    static std::string enumToString(P map[], uint32_t mapLen, const T val)
    {
      for (uint32_t i = 0; i < mapLen; i++)
      {
        if (val == map[i].value)
        {
          return map[i].str;
        }
      }
      return std::string();
    }
    
    template<typename T, typename P>
    static istream& readStrToEnum(P map[], uint32_t mapLen, istream &in, T &val)
    {
      string str;
      in >> str;
    
      for (uint32_t i = 0; i < mapLen; i++)
      {
        if (str == map[i].str)
        {
          val = map[i].value;
          goto found;
        }
      }
      /* not found */
      in.setstate(ios::failbit);
    found:
      return in;
    }
    
    //inline to prevent compiler warnings for "unused static function"
    
    static inline istream& operator >> (istream &in, ExtendedProfileName &profile)
    {
      return readStrToEnum(strToExtendedProfile, sizeof(strToExtendedProfile)/sizeof(*strToExtendedProfile), in, profile);
    }
    
    namespace Level
    {
      static inline istream& operator >> (istream &in, Tier &tier)
      {
        return readStrToEnum(strToTier, sizeof(strToTier)/sizeof(*strToTier), in, tier);
      }
    
      static inline istream& operator >> (istream &in, Name &level)
      {
        return readStrToEnum(strToLevel, sizeof(strToLevel)/sizeof(*strToLevel), in, level);
      }
    }
    
    static inline istream& operator >> (istream &in, CostMode &mode)
    {
      return readStrToEnum(strToCostMode, sizeof(strToCostMode)/sizeof(*strToCostMode), in, mode);
    }
    
    #if HEVC_USE_SCALING_LISTS
    static inline istream& operator >> (istream &in, ScalingListMode &mode)
    {
      return readStrToEnum(strToScalingListMode, sizeof(strToScalingListMode)/sizeof(*strToScalingListMode), in, mode);
    }
    #endif
    
    template <class T>
    struct SMultiValueInput
    {
      const T              minValIncl;
      const T              maxValIncl;
      const std::size_t    minNumValuesIncl;
      const std::size_t    maxNumValuesIncl; // Use 0 for unlimited
            std::vector<T> values;
      SMultiValueInput() : minValIncl(0), maxValIncl(0), minNumValuesIncl(0), maxNumValuesIncl(0), values() { }
      SMultiValueInput(std::vector<T> &defaults) : minValIncl(0), maxValIncl(0), minNumValuesIncl(0), maxNumValuesIncl(0), values(defaults) { }
      SMultiValueInput(const T &minValue, const T &maxValue, std::size_t minNumberValues=0, std::size_t maxNumberValues=0)
        : minValIncl(minValue), maxValIncl(maxValue), minNumValuesIncl(minNumberValues), maxNumValuesIncl(maxNumberValues), values()  { }
      SMultiValueInput(const T &minValue, const T &maxValue, std::size_t minNumberValues, std::size_t maxNumberValues, const T* defValues, const uint32_t numDefValues)
        : minValIncl(minValue), maxValIncl(maxValue), minNumValuesIncl(minNumberValues), maxNumValuesIncl(maxNumberValues), values(defValues, defValues+numDefValues)  { }
      SMultiValueInput<T> &operator=(const std::vector<T> &userValues) { values=userValues; return *this; }
      SMultiValueInput<T> &operator=(const SMultiValueInput<T> &userValues) { values=userValues.values; return *this; }
    
      T readValue(const char *&pStr, bool &bSuccess);
    
      istream& readValues(std::istream &in);
    };
    
    template <class T>
    static inline istream& operator >> (std::istream &in, SMultiValueInput<T> &values)
    {
      return values.readValues(in);
    }
    
    template<>
    uint32_t SMultiValueInput<uint32_t>::readValue(const char *&pStr, bool &bSuccess)
    {
      char *eptr;
      uint32_t val=strtoul(pStr, &eptr, 0);
      pStr=eptr;
      bSuccess=!(*eptr!=0 && !isspace(*eptr) && *eptr!=',') && !(val<minValIncl || val>maxValIncl);
      return val;
    }
    
    template<>
    int SMultiValueInput<int>::readValue(const char *&pStr, bool &bSuccess)
    {
      char *eptr;
      int val=strtol(pStr, &eptr, 0);
      pStr=eptr;
      bSuccess=!(*eptr!=0 && !isspace(*eptr) && *eptr!=',') && !(val<minValIncl || val>maxValIncl);
      return val;
    }
    
    template<>
    double SMultiValueInput<double>::readValue(const char *&pStr, bool &bSuccess)
    {
      char *eptr;
      double val=strtod(pStr, &eptr);
      pStr=eptr;
      bSuccess=!(*eptr!=0 && !isspace(*eptr) && *eptr!=',') && !(val<minValIncl || val>maxValIncl);
      return val;
    }
    
    template<>
    bool SMultiValueInput<bool>::readValue(const char *&pStr, bool &bSuccess)
    {
      char *eptr;
      int val=strtol(pStr, &eptr, 0);
      pStr=eptr;
      bSuccess=!(*eptr!=0 && !isspace(*eptr) && *eptr!=',') && !(val<int(minValIncl) || val>int(maxValIncl));
      return val!=0;
    }
    
    template <class T>
    istream& SMultiValueInput<T>::readValues(std::istream &in)
    {
      values.clear();
      string str;
      while (!in.eof())
      {
        string tmp; in >> tmp; str+=" " + tmp;
      }
      if (!str.empty())
      {
        const char *pStr=str.c_str();
        // soak up any whitespace
        for(;isspace(*pStr);pStr++);
    
        while (*pStr != 0)
        {
          bool bSuccess=true;
          T val=readValue(pStr, bSuccess);
          if (!bSuccess)
          {
            in.setstate(ios::failbit);
            break;
          }
    
          if (maxNumValuesIncl != 0 && values.size() >= maxNumValuesIncl)
          {
            in.setstate(ios::failbit);
            break;
          }
          values.push_back(val);
          // soak up any whitespace and up to 1 comma.
          for(;isspace(*pStr);pStr++);
          if (*pStr == ',')
          {
            pStr++;
          }
          for(;isspace(*pStr);pStr++);
        }
      }
      if (values.size() < minNumValuesIncl)
      {
        in.setstate(ios::failbit);
      }
      return in;
    }
    
    #if QP_SWITCHING_FOR_PARALLEL
    template <class T>
    static inline istream& operator >> (std::istream &in, EncAppCfg::OptionalValue<T> &value)
    {
      in >> std::ws;
      if (in.eof())
      {
        value.bPresent = false;
      }
      else
      {
        in >> value.value;
        value.bPresent = true;
      }
      return in;
    }
    #endif
    
    static void
    automaticallySelectRExtProfile(const bool bUsingGeneralRExtTools,
                                   const bool bUsingChromaQPAdjustment,
                                   const bool bUsingExtendedPrecision,
                                   const bool bIntraConstraintFlag,
                                   uint32_t &bitDepthConstraint,
                                   ChromaFormat &chromaFormatConstraint,
                                   const int  maxBitDepth,
                                   const ChromaFormat chromaFormat)
    {
      // Try to choose profile, according to table in Q1013.
      uint32_t trialBitDepthConstraint=maxBitDepth;
      if (trialBitDepthConstraint<8)
      {
        trialBitDepthConstraint=8;
      }
      else if (trialBitDepthConstraint==9 || trialBitDepthConstraint==11)
      {
        trialBitDepthConstraint++;
      }
      else if (trialBitDepthConstraint>12)
      {
        trialBitDepthConstraint=16;
      }
    
      // both format and bit depth constraints are unspecified
      if (bUsingExtendedPrecision || trialBitDepthConstraint==16)
      {
        bitDepthConstraint = 16;
        chromaFormatConstraint = (!bIntraConstraintFlag && chromaFormat==CHROMA_400) ? CHROMA_400 : CHROMA_444;
      }
      else if (bUsingGeneralRExtTools)
      {
        if (chromaFormat == CHROMA_400 && !bIntraConstraintFlag)
        {
          bitDepthConstraint = 16;
          chromaFormatConstraint = CHROMA_400;
        }
        else
        {
          bitDepthConstraint = trialBitDepthConstraint;
          chromaFormatConstraint = CHROMA_444;
        }
      }
      else if (chromaFormat == CHROMA_400)
      {
        if (bIntraConstraintFlag)
        {
          chromaFormatConstraint = CHROMA_420; // there is no intra 4:0:0 profile.
          bitDepthConstraint     = trialBitDepthConstraint;
        }
        else
        {
          chromaFormatConstraint = CHROMA_400;
          bitDepthConstraint     = trialBitDepthConstraint == 8 ? 8 : 12;
        }
      }
      else
      {
        bitDepthConstraint = trialBitDepthConstraint;
        chromaFormatConstraint = chromaFormat;
        if (bUsingChromaQPAdjustment && chromaFormat == CHROMA_420)
        {
          chromaFormatConstraint = CHROMA_422; // 4:2:0 cannot use the chroma qp tool.
        }
        if (chromaFormatConstraint == CHROMA_422 && bitDepthConstraint == 8)
        {
          bitDepthConstraint = 10; // there is no 8-bit 4:2:2 profile.
        }
        if (chromaFormatConstraint == CHROMA_420 && !bIntraConstraintFlag)
        {
          bitDepthConstraint = 12; // there is no 8 or 10-bit 4:2:0 inter RExt profile.
        }
      }
    }
    // ====================================================================================================================
    // Public member functions
    // ====================================================================================================================
    
    /** \param  argc        number of arguments
        \param  argv        array of arguments
        \retval             true when success
     */
    bool EncAppCfg::parseCfg( int argc, char* argv[] )
    {
      bool do_help = false;
    
      int tmpChromaFormat;
      int tmpInputChromaFormat;
      int tmpConstraintChromaFormat;
      int tmpWeightedPredictionMethod;
      int tmpFastInterSearchMode;
      int tmpMotionEstimationSearchMethod;
      int tmpSliceMode;
    #if HEVC_DEPENDENT_SLICES
      int tmpSliceSegmentMode;
    #endif
      int tmpDecodedPictureHashSEIMappedType;
      string inputColourSpaceConvert;
      string inputPathPrefix;
      ExtendedProfileName extendedProfile;
      int saoOffsetBitShift[MAX_NUM_CHANNEL_TYPE];
    
      // Multi-value input fields:                                // minval, maxval (incl), min_entries, max_entries (incl) [, default values, number of default values]
      SMultiValueInput<uint32_t> cfg_ColumnWidth                     (0, std::numeric_limits<uint32_t>::max(), 0, std::numeric_limits<uint32_t>::max());
      SMultiValueInput<uint32_t> cfg_RowHeight                       (0, std::numeric_limits<uint32_t>::max(), 0, std::numeric_limits<uint32_t>::max());
      SMultiValueInput<int>  cfg_startOfCodedInterval            (std::numeric_limits<int>::min(), std::numeric_limits<int>::max(), 0, 1<<16);
      SMultiValueInput<int>  cfg_codedPivotValue                 (std::numeric_limits<int>::min(), std::numeric_limits<int>::max(), 0, 1<<16);
      SMultiValueInput<int>  cfg_targetPivotValue                (std::numeric_limits<int>::min(), std::numeric_limits<int>::max(), 0, 1<<16);
    
      SMultiValueInput<double> cfg_adIntraLambdaModifier         (0, std::numeric_limits<double>::max(), 0, MAX_TLAYER); ///< Lambda modifier for Intra pictures, one for each temporal layer. If size>temporalLayer, then use [temporalLayer], else if size>0, use [size()-1], else use m_adLambdaModifier.
    
    #if SHARP_LUMA_DELTA_QP
      const int defaultLumaLevelTodQp_QpChangePoints[]   =  {-3,  -2,  -1,   0,   1,   2,   3,   4,   5,   6};
      const int defaultLumaLevelTodQp_LumaChangePoints[] =  { 0, 301, 367, 434, 501, 567, 634, 701, 767, 834};
      SMultiValueInput<int>  cfg_lumaLeveltoDQPMappingQP         (-MAX_QP, MAX_QP,                    0, LUMA_LEVEL_TO_DQP_LUT_MAXSIZE, defaultLumaLevelTodQp_QpChangePoints,   sizeof(defaultLumaLevelTodQp_QpChangePoints  )/sizeof(int));
      SMultiValueInput<int>  cfg_lumaLeveltoDQPMappingLuma       (0, std::numeric_limits<int>::max(), 0, LUMA_LEVEL_TO_DQP_LUT_MAXSIZE, defaultLumaLevelTodQp_LumaChangePoints, sizeof(defaultLumaLevelTodQp_LumaChangePoints)/sizeof(int));
      uint32_t lumaLevelToDeltaQPMode;
    #endif
    
      const uint32_t defaultInputKneeCodes[3]  = { 600, 800, 900 };
      const uint32_t defaultOutputKneeCodes[3] = { 100, 250, 450 };
      SMultiValueInput<uint32_t> cfg_kneeSEIInputKneePointValue      (1,  999, 0, 999, defaultInputKneeCodes,  sizeof(defaultInputKneeCodes )/sizeof(uint32_t));
      SMultiValueInput<uint32_t> cfg_kneeSEIOutputKneePointValue     (0, 1000, 0, 999, defaultOutputKneeCodes, sizeof(defaultOutputKneeCodes)/sizeof(uint32_t));
      const int defaultPrimaryCodes[6]     = { 0,50000, 0,0, 50000,0 };
      const int defaultWhitePointCode[2]   = { 16667, 16667 };
      SMultiValueInput<int>  cfg_DisplayPrimariesCode            (0, 50000, 6, 6, defaultPrimaryCodes,   sizeof(defaultPrimaryCodes  )/sizeof(int));
      SMultiValueInput<int>  cfg_DisplayWhitePointCode           (0, 50000, 2, 2, defaultWhitePointCode, sizeof(defaultWhitePointCode)/sizeof(int));
    
      SMultiValueInput<bool> cfg_timeCodeSeiTimeStampFlag        (0,  1, 0, MAX_TIMECODE_SEI_SETS);
      SMultiValueInput<bool> cfg_timeCodeSeiNumUnitFieldBasedFlag(0,  1, 0, MAX_TIMECODE_SEI_SETS);
      SMultiValueInput<int>  cfg_timeCodeSeiCountingType         (0,  6, 0, MAX_TIMECODE_SEI_SETS);
      SMultiValueInput<bool> cfg_timeCodeSeiFullTimeStampFlag    (0,  1, 0, MAX_TIMECODE_SEI_SETS);
      SMultiValueInput<bool> cfg_timeCodeSeiDiscontinuityFlag    (0,  1, 0, MAX_TIMECODE_SEI_SETS);
      SMultiValueInput<bool> cfg_timeCodeSeiCntDroppedFlag       (0,  1, 0, MAX_TIMECODE_SEI_SETS);
      SMultiValueInput<int>  cfg_timeCodeSeiNumberOfFrames       (0,511, 0, MAX_TIMECODE_SEI_SETS);
      SMultiValueInput<int>  cfg_timeCodeSeiSecondsValue         (0, 59, 0, MAX_TIMECODE_SEI_SETS);
      SMultiValueInput<int>  cfg_timeCodeSeiMinutesValue         (0, 59, 0, MAX_TIMECODE_SEI_SETS);
      SMultiValueInput<int>  cfg_timeCodeSeiHoursValue           (0, 23, 0, MAX_TIMECODE_SEI_SETS);
      SMultiValueInput<bool> cfg_timeCodeSeiSecondsFlag          (0,  1, 0, MAX_TIMECODE_SEI_SETS);
      SMultiValueInput<bool> cfg_timeCodeSeiMinutesFlag          (0,  1, 0, MAX_TIMECODE_SEI_SETS);
      SMultiValueInput<bool> cfg_timeCodeSeiHoursFlag            (0,  1, 0, MAX_TIMECODE_SEI_SETS);
      SMultiValueInput<int>  cfg_timeCodeSeiTimeOffsetLength     (0, 31, 0, MAX_TIMECODE_SEI_SETS);
      SMultiValueInput<int>  cfg_timeCodeSeiTimeOffsetValue      (std::numeric_limits<int>::min(), std::numeric_limits<int>::max(), 0, MAX_TIMECODE_SEI_SETS);
      int warnUnknowParameter = 0;
    
    #if ENABLE_TRACING
      string sTracingRule;
      string sTracingFile;
      bool   bTracingChannelsList = false;
    #endif
    #if ENABLE_SIMD_OPT
      std::string ignore;
    #endif
    
      bool sdr = false;
    
      po::Options opts;
      opts.addOptions()
      ("help",                                            do_help,                                          false, "this help text")
      ("c",    po::parseConfigFile, "configuration file name")
      ("WarnUnknowParameter,w",                           warnUnknowParameter,                                  0, "warn for unknown configuration parameters instead of failing")
      ("isSDR",                                           sdr,                                              false, "compatibility")
    #if ENABLE_SIMD_OPT
      ("SIMD",                                            ignore,                                      string(""), "SIMD extension to use (SCALAR, SSE41, SSE42, AVX, AVX2, AVX512), default: the highest supported extension\n")
    #endif
      // File, I/O and source parameters
      ("InputFile,i",                                     m_inputFileName,                             string(""), "Original YUV input file name")
      ("InputPathPrefix,-ipp",                            inputPathPrefix,                             string(""), "pathname to prepend to input filename")
      ("BitstreamFile,b",                                 m_bitstreamFileName,                         string(""), "Bitstream output file name")
      ("ReconFile,o",                                     m_reconFileName,                             string(""), "Reconstructed YUV output file name")
      ("SourceWidth,-wdt",                                m_iSourceWidth,                                       0, "Source picture width")
      ("SourceHeight,-hgt",                               m_iSourceHeight,                                      0, "Source picture height")
      ("InputBitDepth",                                   m_inputBitDepth[CHANNEL_TYPE_LUMA],                   8, "Bit-depth of input file")
      ("OutputBitDepth",                                  m_outputBitDepth[CHANNEL_TYPE_LUMA],                  0, "Bit-depth of output file (default:InternalBitDepth)")
      ("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)")
      ("InternalBitDepth",                                m_internalBitDepth[CHANNEL_TYPE_LUMA],                0, "Bit-depth the codec operates at. (default: MSBExtendedBitDepth). If different to MSBExtendedBitDepth, source data will be converted")
      ("InputBitDepthC",                                  m_inputBitDepth[CHANNEL_TYPE_CHROMA],                 0, "As per InputBitDepth but for chroma component. (default:InputBitDepth)")
      ("OutputBitDepthC",                                 m_outputBitDepth[CHANNEL_TYPE_CHROMA],                0, "As per OutputBitDepth but for chroma component. (default: use luma output bit-depth)")
      ("MSBExtendedBitDepthC",                            m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA],           0, "As per MSBExtendedBitDepth but for chroma component. (default:MSBExtendedBitDepth)")
      ("InternalBitDepthC",                               m_internalBitDepth[CHANNEL_TYPE_CHROMA],              0, "As per InternalBitDepth but for chroma component. (default:InternalBitDepth)")
      ("ExtendedPrecision",                               m_extendedPrecisionProcessingFlag,                false, "Increased internal accuracies to support high bit depths (not valid in V1 profiles)")
      ("HighPrecisionPredictionWeighting",                m_highPrecisionOffsetsEnabledFlag,                false, "Use high precision option for weighted prediction (not valid in V1 profiles)")
      ("InputColourSpaceConvert",                         inputColourSpaceConvert,                     string(""), "Colour space conversion to apply to input video. Permitted values are (empty string=UNCHANGED) " + getListOfColourSpaceConverts(true))
      ("SNRInternalColourSpace",                          m_snrInternalColourSpace,                         false, "If true, then no colour space conversion is applied prior to SNR, otherwise inverse of input is applied.")
      ("OutputInternalColourSpace",                       m_outputInternalColourSpace,                      false, "If true, then no colour space conversion is applied for reconstructed video, otherwise inverse of input is applied.")
      ("InputChromaFormat",                               tmpInputChromaFormat,                               420, "InputChromaFormatIDC")
      ("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")
      ("PrintHexPSNR",                                    m_printHexPsnr,                                   false, "0 (default) don't emit hexadecimal PSNR for each frame, 1 = also emit hexadecimal PSNR values")
      ("PrintFrameMSE",                                   m_printFrameMSE,                                  false, "0 (default) emit only bit count and PSNRs for each frame, 1 = also emit MSE values")
      ("PrintSequenceMSE",                                m_printSequenceMSE,                               false, "0 (default) emit only bit rate and PSNRs for the whole sequence, 1 = also emit MSE values")
      ("CabacZeroWordPaddingEnabled",                     m_cabacZeroWordPaddingEnabled,                     true, "0 do not add conforming cabac-zero-words to bit streams, 1 (default) = add cabac-zero-words as required")
      ("ChromaFormatIDC,-cf",                             tmpChromaFormat,                                      0, "ChromaFormatIDC (400|420|422|444 or set 0 (default) for same as InputChromaFormat)")
      ("ConformanceMode",                                 m_conformanceWindowMode,                              0, "Deprecated alias of ConformanceWindowMode")
      ("ConformanceWindowMode",                           m_conformanceWindowMode,                              0, "Window conformance mode (0: no window, 1:automatic padding, 2:padding, 3:conformance")
      ("HorizontalPadding,-pdx",                          m_aiPad[0],                                           0, "Horizontal source padding for conformance window mode 2")
      ("VerticalPadding,-pdy",                            m_aiPad[1],                                           0, "Vertical source padding for conformance window mode 2")
      ("ConfLeft",                                        m_confWinLeft,                                        0, "Deprecated alias of ConfWinLeft")
      ("ConfRight",                                       m_confWinRight,                                       0, "Deprecated alias of ConfWinRight")
      ("ConfTop",                                         m_confWinTop,                                         0, "Deprecated alias of ConfWinTop")
      ("ConfBottom",                                      m_confWinBottom,                                      0, "Deprecated alias of ConfWinBottom")
      ("ConfWinLeft",                                     m_confWinLeft,                                        0, "Left offset for window conformance mode 3")
      ("ConfWinRight",                                    m_confWinRight,                                       0, "Right offset for window conformance mode 3")
      ("ConfWinTop",                                      m_confWinTop,                                         0, "Top offset for window conformance mode 3")
      ("ConfWinBottom",                                   m_confWinBottom,                                      0, "Bottom offset for window conformance mode 3")
      ("AccessUnitDelimiter",                             m_AccessUnitDelimiter,                            false, "Enable Access Unit Delimiter NALUs")
      ("FrameRate,-fr",                                   m_iFrameRate,                                         0, "Frame rate")
      ("FrameSkip,-fs",                                   m_FrameSkip,                                         0u, "Number of frames to skip at start of input YUV")
      ("TemporalSubsampleRatio,-ts",                      m_temporalSubsampleRatio,                            1u, "Temporal sub-sample ratio when reading input YUV")
      ("FramesToBeEncoded,f",                             m_framesToBeEncoded,                                  0, "Number of frames to be encoded (default=all)")
      ("ClipInputVideoToRec709Range",                     m_bClipInputVideoToRec709Range,                   false, "If true then clip input video to the Rec. 709 Range on loading when InternalBitDepth is less than MSBExtendedBitDepth")
      ("ClipOutputVideoToRec709Range",                    m_bClipOutputVideoToRec709Range,                  false, "If true then clip output video to the Rec. 709 Range on saving when OutputBitDepth is less than InternalBitDepth")
      ("SummaryOutFilename",                              m_summaryOutFilename,                          string(), "Filename to use for producing summary output file. If empty, do not produce a file.")
      ("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.")
      ("SummaryVerboseness",                              m_summaryVerboseness,                                0u, "Specifies the level of the verboseness of the text output")
      ("Verbosity,v",                                     m_verbosity,                               (int)VERBOSE, "Specifies the level of the verboseness")
    
      //Field coding parameters
      ("FieldCoding",                                     m_isField,                                        false, "Signals if it's a field based coding")
      ("TopFieldFirst, Tff",                              m_isTopFieldFirst,                                false, "In case of field based coding, signals whether if it's a top field first or not")
      ("EfficientFieldIRAPEnabled",                       m_bEfficientFieldIRAPEnabled,                      true, "Enable to code fields in a specific, potentially more efficient, order.")
      ("HarmonizeGopFirstFieldCoupleEnabled",             m_bHarmonizeGopFirstFieldCoupleEnabled,            true, "Enables harmonization of Gop first field couple")
    
      // Profile and level
      ("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")
      ("Level",                                           m_level,                                    Level::NONE, "Level limit to be used, eg 5.1, or none")
      ("Tier",                                            m_levelTier,                                Level::MAIN, "Tier to use for interpretation of --Level (main or high only)")
      ("MaxBitDepthConstraint",                           m_bitDepthConstraint,                                0u, "Bit depth to use for profile-constraint for RExt profiles. 0=automatically choose based upon other parameters")
      ("MaxChromaFormatConstraint",                       tmpConstraintChromaFormat,                            0, "Chroma-format to use for the profile-constraint for RExt profiles. 0=automatically choose based upon other parameters")
      ("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)")
      ("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)")
      ("LowerBitRateConstraintFlag",                      m_lowerBitRateConstraintFlag,                      true, "Value of general_lower_bit_rate_constraint_flag to use for RExt profiles")
    
      ("ProgressiveSource",                               m_progressiveSourceFlag,                          false, "Indicate that source is progressive")
      ("InterlacedSource",                                m_interlacedSourceFlag,                           false, "Indicate that source is interlaced")
      ("NonPackedSource",                                 m_nonPackedConstraintFlag,                        false, "Indicate that source does not contain frame packing")
      ("FrameOnly",                                       m_frameOnlyConstraintFlag,                        false, "Indicate that the bitstream contains only frames")
      ("QTBT",                                            m_QTBT,                                           false, "Enable QTBT (0:off, 1:on)  [default: off]")
      ("MTT",                                             m_MTT,                                               0u, "Multi type tree type (0: off, 1:QTBT + triple split) [default: 0]")
      ("CTUSize",                                         m_uiCTUSize,                                       128u, "CTUSize (specifies the CTU size if QTBT is on) [default: 128]")
      ("MinQTISlice",                                     m_uiMinQT[0],                                        8u, "MinQTISlice")
      ("MinQTLumaISlice",                                 m_uiMinQT[0],                                        8u, "MinQTLumaISlice")
      ("MinQTChromaISlice",                               m_uiMinQT[2],                                        4u, "MinQTChromaISlice")
      ("MinQTNonISlice",                                  m_uiMinQT[1],                                        8u, "MinQTNonISlice")
      ("MaxBTDepth",                                      m_uiMaxBTDepth,                                      3u, "MaxBTDepth")
      ("MaxBTDepthI",                                     m_uiMaxBTDepthI,                                     3u, "MaxBTDepthI")
      ("MaxBTDepthISliceL",                               m_uiMaxBTDepthI,                                     3u, "MaxBTDepthISliceL")
      ("MaxBTDepthISliceC",                               m_uiMaxBTDepthIChroma,                               3u, "MaxBTDepthISliceC")
      ("DualITree",                                       m_dualTree,                                       false, "Use separate QTBT trees for intra slice luma and chroma channel types")
      ("LargeCTU",                                        m_LargeCTU,                                       false, "Enable large CTU (0:off, 1:on)  [default: off]")
    #if JVET_K0346
    #if ENABLE_BMS
      ("SubPuMvp",                                       m_SubPuMvpMode,                                       0, "Enable Sub-PU temporal motion vector prediction (0:off, 1:ATMVP, 2:STMVP, 3:ATMVP+STMVP)  [default: off]")
    #else
      ("SubPuMvp",                                       m_SubPuMvpMode,                                       0, "Enable Sub-PU temporal motion vector prediction (0:off, 1:on)  [default: off]")
    #endif
      ("SubPuMvpLog2Size",                               m_SubPuMvpLog2Size,                                   2u, "Sub-PU TMVP size index: 2^n")
      ("HighPrecMv",                                     m_highPrecisionMv,                                 false, "High precision motion vectors for temporal merging (0:off, 1:on)  [default: off]")
    #endif
    #if JVET_K_AFFINE
      ("HighPrecMv",                                      m_highPrecisionMv,                               false, "High precision motion vectors for temporal merging (0:off, 1:on)  [default: off]")
      ("Affine",                                          m_Affine,                                        false, "Enable affine prediction (0:off, 1:on)  [default: off]")
    #if JVET_K0337_AFFINE_6PARA
      ( "AffineType",                                     m_AffineType,                                     true,  "Enable affine type prediction (0:off, 1:on)  [default: on]" )
    #endif
    #endif
      ("DisableMotCompression",                           m_DisableMotionCompression,                       false, "Disable motion data compression for all modes")
    #if JVET_K0357_AMVR
      ("IMV",                                             m_ImvMode,                                            2, "Adaptive MV precision Mode (IMV)\n"
                                                                                                                   "\t0: disabled IMV\n"
                                                                                                                   "\t1: IMV default (Full-Pel)\n"
                                                                                                                   "\t2: IMV Full-Pel and 4-PEL\n")
      ("IMV4PelFast",                                     m_Imv4PelFast,                                        1, "Fast 4-Pel Adaptive MV precision Mode 0:disabled, 1:enabled)  [default: 1]")
      ("IMVMaxCand",                                      m_ImvMaxCand,                                         4, "max IMV cand (QTBF off only)")
    #endif
    #if ENABLE_WPP_PARALLELISM
      ("AltDQPCoding",                                    m_AltDQPCoding,                                   false, "Improved predictive delta-QP coding (0:off, 1:on)  [default: off]")
    #endif
    #if JVET_K0190
      ("LMChroma",                                        m_LMChroma,                                           1, " LMChroma prediction "
                                                                                                                   "\t0:  Disable LMChroma\n"
                                                                                                                   "\t1:  Enable LMChroma\n")
    #else
    #endif
    #if JVET_K1000_SIMPLIFIED_EMT
      ("EMT,-emt",                                        m_EMT,                                                0, "Enhanced Multiple Transform (EMT)\n"
        "\t0:  Disable EMT\n"
        "\t1:  Enable only Intra EMT\n"
        "\t2:  Enable only Inter EMT\n"
        "\t3:  Enable both Intra & Inter EMT\n")
      ("EMTFast,-femt",                                   m_FastEMT,                                            0, "Fast methods for Enhanced Multiple Transform (EMT)\n"
        "\t0:  Disable fast methods for EMT\n"
        "\t1:  Enable fast methods only for Intra EMT\n"
        "\t2:  Enable fast methods only for Inter EMT\n"
        "\t3:  Enable fast methods for both Intra & Inter EMT\n")
    #endif
      // ADD_NEW_TOOL : (encoder app) add parsing parameters here
    
      ("LCTUFast",                                        m_useFastLCTU,                                    false, "Fast methods for large CTU")
      ("FastMrg",                                         m_useFastMrg,                                     false, "Fast methods for inter merge")
      ("PBIntraFast",                                     m_usePbIntraFast,                                 false, "Fast assertion if the intra mode is probable")
      ("AMaxBT",                                          m_useAMaxBT,                                      false, "Adaptive maximal BT-size")
    #if !JVET_K0220_ENC_CTRL
      ("SaveLoadEncInfo",                                 m_useSaveLoadEncInfo,                             false, "Reuse of previous encoder decision for same block generated by different partition methods")
      ("SaveLoadSplitDecision",                           m_useSaveLoadSplitDecision,                       false, "Reuse of previous split decision for same block generated by different partition methods")
    #endif
      ("E0023FastEnc",                                    m_e0023FastEnc,                                    true, "Fast encoding setting for QTBT (proposal E0023)")
      ("ContentBasedFastQtbt",                            m_contentBasedFastQtbt,                           false, "Signal based QTBT speed-up")
      // Unit definition parameters
      ("MaxCUWidth",                                      m_uiMaxCUWidth,                                     64u)
      ("MaxCUHeight",                                     m_uiMaxCUHeight,                                    64u)
      // todo: remove defaults from MaxCUSize
      ("MaxCUSize,s",                                     m_uiMaxCUWidth,                                     64u, "Maximum CU size")
      ("MaxCUSize,s",                                     m_uiMaxCUHeight,                                    64u, "Maximum CU size")
      ("MaxPartitionDepth,h",                             m_uiMaxCUDepth,                                      4u, "CU depth")
    
      ("QuadtreeTULog2MaxSize",                           m_quadtreeTULog2MaxSize,                             -1, "Maximum TU size in logarithm base 2")
      ("QuadtreeTULog2MinSize",                           m_quadtreeTULog2MinSize,                              2, "Minimum TU size in logarithm base 2")
    
      ("QuadtreeTUMaxDepthIntra",                         m_uiQuadtreeTUMaxDepthIntra,                         1u, "Depth of TU tree for intra CUs")
      ("QuadtreeTUMaxDepthInter",                         m_uiQuadtreeTUMaxDepthInter,                         2u, "Depth of TU tree for inter CUs")
    
    
      ("TULog2MaxSize",                                   m_tuLog2MaxSize,                                     -1, "Maximum TU size in logarithm base 2 (for use with NEXT-Profile)")
    
      // Coding structure paramters
      ("IntraPeriod,-ip",                                 m_iIntraPeriod,                                      -1, "Intra period in frames, (-1: only first frame)")
      ("DecodingRefreshType,-dr",                         m_iDecodingRefreshType,                               0, "Intra refresh type (0:none 1:CRA 2:IDR 3:RecPointSEI)")
      ("GOPSize,g",                                       m_iGOPSize,                                           1, "GOP size of temporal structure")
    
      // motion search options
      ("DisableIntraInInter",                             m_bDisableIntraPUsInInterSlices,                  false, "Flag to disable intra PUs in inter slices")
      ("FastSearch",                                      tmpMotionEstimationSearchMethod,  int(MESEARCH_DIAMOND), "0:Full search 1:Diamond 2:Selective 3:Enhanced Diamond")
      ("SearchRange,-sr",                                 m_iSearchRange,                                      96, "Motion search range")
      ("BipredSearchRange",                               m_bipredSearchRange,                                  4, "Motion search range for bipred refinement")
      ("MinSearchWindow",                                 m_minSearchWindow,                                    8, "Minimum motion search window size for the adaptive window ME")
      ("RestrictMESampling",                              m_bRestrictMESampling,                            false, "Restrict ME Sampling for selective inter motion search")
      ("ClipForBiPredMEEnabled",                          m_bClipForBiPredMeEnabled,                        false, "Enables clipping in the Bi-Pred ME. It is disabled to reduce encoder run-time")
      ("FastMEAssumingSmootherMVEnabled",                 m_bFastMEAssumingSmootherMVEnabled,                true, "Enables fast ME assuming a smoother MV.")
    
      ("HadamardME",                                      m_bUseHADME,                                       true, "Hadamard ME for fractional-pel")
      ("ASR",                                             m_bUseASR,                                        false, "Adaptive motion search range");
      opts.addOptions()
    
      // Mode decision parameters
      ("LambdaModifier0,-LM0",                            m_adLambdaModifier[ 0 ],                  ( double )1.0, "Lambda modifier for temporal layer 0. If LambdaModifierI is used, this will not affect intra pictures")
      ("LambdaModifier1,-LM1",                            m_adLambdaModifier[ 1 ],                  ( double )1.0, "Lambda modifier for temporal layer 1. If LambdaModifierI is used, this will not affect intra pictures")
      ("LambdaModifier2,-LM2",                            m_adLambdaModifier[ 2 ],                  ( double )1.0, "Lambda modifier for temporal layer 2. If LambdaModifierI is used, this will not affect intra pictures")
      ("LambdaModifier3,-LM3",                            m_adLambdaModifier[ 3 ],                  ( double )1.0, "Lambda modifier for temporal layer 3. If LambdaModifierI is used, this will not affect intra pictures")
      ("LambdaModifier4,-LM4",                            m_adLambdaModifier[ 4 ],                  ( double )1.0, "Lambda modifier for temporal layer 4. If LambdaModifierI is used, this will not affect intra pictures")
      ("LambdaModifier5,-LM5",                            m_adLambdaModifier[ 5 ],                  ( double )1.0, "Lambda modifier for temporal layer 5. If LambdaModifierI is used, this will not affect intra pictures")
      ("LambdaModifier6,-LM6",                            m_adLambdaModifier[ 6 ],                  ( double )1.0, "Lambda modifier for temporal layer 6. If LambdaModifierI is used, this will not affect intra pictures")
      ("LambdaModifierI,-LMI",                            cfg_adIntraLambdaModifier,    cfg_adIntraLambdaModifier, "Lambda modifiers for Intra pictures, comma separated, up to one the number of temporal layer. If entry for temporalLayer exists, then use it, else if some are specified, use the last, else use the standard LambdaModifiers.")
      ("IQPFactor,-IQF",                                  m_dIntraQpFactor,                                  -1.0, "Intra QP Factor for Lambda Computation. If negative, the default will scale lambda based on GOP size (unless LambdaFromQpEnable then IntraQPOffset is used instead)")
    
      /* Quantization parameters */
    #if QP_SWITCHING_FOR_PARALLEL
      ("QP,q",                                            m_iQP,                                               30, "Qp value")
      ("QPIncrementFrame,-qpif",                          m_qpIncrementAtSourceFrame,       OptionalValue<uint32_t>(), "If a source file frame number is specified, the internal QP will be incremented for all POCs associated with source frames >= frame number. If empty, do not increment.")
    #else
      ("QP,q",                                            m_fQP,                                             30.0, "Qp value, if value is float, QP is switched once during encoding")
    #endif
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
      ("IntraQPOffset",                                   m_intraQPOffset,                                      0, "Qp offset value for intra slice, typically determined based on GOP size")
      ("LambdaFromQpEnable",                              m_lambdaFromQPEnable,                             false, "Enable flag for derivation of lambda from QP")
    #endif
      ("DeltaQpRD,-dqr",                                  m_uiDeltaQpRD,                                       0u, "max dQp offset for slice")
      ("MaxDeltaQP,d",                                    m_iMaxDeltaQP,                                        0, "max dQp offset for block")
      ("MaxCuDQPDepth,-dqd",                              m_iMaxCuDQPDepth,                                     0, "max depth for a minimum CuDQP")
      ("MaxCUChromaQpAdjustmentDepth",                    m_diffCuChromaQpOffsetDepth,                         -1, "Maximum depth for CU chroma Qp adjustment - set less than 0 to disable")
      ("FastDeltaQP",                                     m_bFastDeltaQP,                                   false, "Fast Delta QP Algorithm")
    #if SHARP_LUMA_DELTA_QP
      ("LumaLevelToDeltaQPMode",                          lumaLevelToDeltaQPMode,                              0u, "Luma based Delta QP 0(default): not used. 1: Based on CTU average, 2: Based on Max luma in CTU")
    #if !WCG_EXT
      ("LumaLevelToDeltaQPMaxValWeight",                  m_lumaLevelToDeltaQPMapping.maxMethodWeight,        1.0, "Weight of block max luma val when LumaLevelToDeltaQPMode = 2")
    #endif
      ("LumaLevelToDeltaQPMappingLuma",                   cfg_lumaLeveltoDQPMappingLuma,  cfg_lumaLeveltoDQPMappingLuma, "Luma to Delta QP Mapping - luma thresholds")
      ("LumaLevelToDeltaQPMappingDQP",                    cfg_lumaLeveltoDQPMappingQP,  cfg_lumaLeveltoDQPMappingQP, "Luma to Delta QP Mapping - DQP values")
    #endif
    
      ("CbQpOffset,-cbqpofs",                             m_cbQpOffset,                                         0, "Chroma Cb QP Offset")
      ("CrQpOffset,-crqpofs",                             m_crQpOffset,                                         0, "Chroma Cr QP Offset")
      ("CbQpOffsetDualTree",                              m_cbQpOffsetDualTree,                                 1, "Chroma Cb QP Offset for dual tree")
      ("CrQpOffsetDualTree",                              m_crQpOffsetDualTree,                                 1, "Chroma Cr QP Offset for dual tree")
    #if ER_CHROMA_QP_WCG_PPS
      ("WCGPPSEnable",                                    m_wcgChromaQpControl.enabled,                     false, "1: Enable the WCG PPS chroma modulation scheme. 0 (default) disabled")
      ("WCGPPSCbQpScale",                                 m_wcgChromaQpControl.chromaCbQpScale,               1.0, "WCG PPS Chroma Cb QP Scale")
      ("WCGPPSCrQpScale",                                 m_wcgChromaQpControl.chromaCrQpScale,               1.0, "WCG PPS Chroma Cr QP Scale")
      ("WCGPPSChromaQpScale",                             m_wcgChromaQpControl.chromaQpScale,                 0.0, "WCG PPS Chroma QP Scale")
      ("WCGPPSChromaQpOffset",                            m_wcgChromaQpControl.chromaQpOffset,                0.0, "WCG PPS Chroma QP Offset")
    #endif
    #if W0038_CQP_ADJ
      ("SliceChromaQPOffsetPeriodicity",                  m_sliceChromaQpOffsetPeriodicity,                    0u, "Used in conjunction with Slice Cb/Cr QpOffsetIntraOrPeriodic. Use 0 (default) to disable periodic nature.")
      ("SliceCbQpOffsetIntraOrPeriodic",                  m_sliceChromaQpOffsetIntraOrPeriodic[0],              0, "Chroma Cb QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.")
      ("SliceCrQpOffsetIntraOrPeriodic",                  m_sliceChromaQpOffsetIntraOrPeriodic[1],              0, "Chroma Cr QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.")
    #endif
    
      ("AdaptiveQP,-aq",                                  m_bUseAdaptiveQP,                                 false, "QP adaptation based on a psycho-visual model")
      ("MaxQPAdaptationRange,-aqr",                       m_iQPAdaptationRange,                                 6, "QP adaptation range")
    #if ENABLE_QPA
      ("PerceptQPA,-qpa",                                 m_bUsePerceptQPA,                                 false, "perceptually motivated input-adaptive QP modification (default: 0 = off, ignored if -aq is set)")
      ("WPSNR,-wpsnr",                                    m_bUseWPSNR,                                      false, "output perceptually weighted peak SNR (WPSNR) instead of PSNR")
    #endif
      ("dQPFile,m",                                       m_dQPFileName,                               string(""), "dQP file name")
      ("RDOQ",                                            m_useRDOQ,                                         true)
      ("RDOQTS",                                          m_useRDOQTS,                                       true)
    #if T0196_SELECTIVE_RDOQ
      ("SelectiveRDOQ",                                   m_useSelectiveRDOQ,                               false, "Enable selective RDOQ")
    #endif
      ("RDpenalty",                                       m_rdPenalty,                                          0, "RD-penalty for 32x32 TU for intra in non-intra slices. 0:disabled  1:RD-penalty  2:maximum RD-penalty")
    
      // Deblocking filter parameters
      ("LoopFilterDisable",                               m_bLoopFilterDisable,                             false)
      ("LoopFilterOffsetInPPS",                           m_loopFilterOffsetInPPS,                           true)
      ("LoopFilterBetaOffset_div2",                       m_loopFilterBetaOffsetDiv2,                           0)
      ("LoopFilterTcOffset_div2",                         m_loopFilterTcOffsetDiv2,                             0)
    #if W0038_DB_OPT
      ("DeblockingFilterMetric",                          m_deblockingFilterMetric,                             0)
    #else
      ("DeblockingFilterMetric",                          m_DeblockingFilterMetric,                         false)
    #endif
      // Coding tools
      ("AMP",                                             m_enableAMP,                                       true, "Enable asymmetric motion partitions")
      ("CrossComponentPrediction",                        m_crossComponentPredictionEnabledFlag,            false, "Enable the use of cross-component prediction (not valid in V1 profiles)")
      ("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")
      ("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")
      ("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")
      ("TransformSkip",                                   m_useTransformSkip,                               false, "Intra transform skipping")
      ("TransformSkipFast",                               m_useTransformSkipFast,                           false, "Fast intra transform skipping")
      ("TransformSkipLog2MaxSize",                        m_log2MaxTransformSkipBlockSize,                     2U, "Specify transform-skip maximum size. Minimum 2. (not valid in V1 profiles)")
      ("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)")
      ("ExplicitResidualDPCM",                            m_rdpcmEnabledFlag[RDPCM_SIGNAL_EXPLICIT],        false, "Enable explicitly signalled residual DPCM for inter (not valid in V1 profiles)")
      ("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)")
      ("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)")
      ("GolombRiceParameterAdaptation",                   m_persistentRiceAdaptationEnabledFlag,            false, "Enable the adaptation of the Golomb-Rice parameter over the course of each slice")
      ("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")
      ("SAO",                                             m_bUseSAO,                                         true, "Enable Sample Adaptive Offset")
      ("TestSAODisableAtPictureLevel",                    m_bTestSAODisableAtPictureLevel,                  false, "Enables the testing of disabling SAO at the picture level after having analysed all blocks")
      ("SaoEncodingRate",                                 m_saoEncodingRate,                                 0.75, "When >0 SAO early picture termination is enabled for luma and chroma")
      ("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")
      ("MaxNumOffsetsPerPic",                             m_maxNumOffsetsPerPic,                             2048, "Max number of SAO offset per picture (Default: 2048)")
      ("SAOLcuBoundary",                                  m_saoCtuBoundary,                                 false, "0: right/bottom CTU boundary areas skipped from SAO parameter estimation, 1: non-deblocked pixels are used for those areas")
    #if K0238_SAO_GREEDY_MERGE_ENCODING
      ("SAOGreedyEnc",                                    m_saoGreedyMergeEnc,                              false, "SAO greedy merge encoding algorithm")