/* 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-2020, 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     EncApp.cpp
    \brief    Encoder application class
*/

#include <list>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <iomanip>

#include "EncApp.h"
#include "EncoderLib/AnnexBwrite.h"
#include "EncoderLib/EncLibCommon.h"

using namespace std;

//! \ingroup EncoderApp
//! \{

// ====================================================================================================================
// Constructor / destructor / initialization / destroy
// ====================================================================================================================

EncApp::EncApp( fstream& bitStream, EncLibCommon* encLibCommon )
  : m_cEncLib( encLibCommon )
  , m_bitstream( bitStream )
{
  m_iFrameRcvd = 0;
  m_totalBytes = 0;
  m_essentialBytes = 0;
#if JVET_O0756_CALCULATE_HDRMETRICS
  m_metricTime = std::chrono::milliseconds(0);
#endif
  m_numEncoded = 0;
  m_flush = false;
}

EncApp::~EncApp()
{
}

void EncApp::xInitLibCfg()
{
#if JVET_Q0814_DPB
  VPS& vps = *m_cEncLib.getVPS();
  vps.m_targetOlsIdx = m_targetOlsIdx;
#else
  VPS vps;
#endif

  vps.setMaxLayers( m_maxLayers );

  if (vps.getMaxLayers() > 1)
  {
    vps.setVPSId(1);  //JVET_P0205 vps_video_parameter_set_id shall be greater than 0 for multi-layer coding
  }
  else
  {
    vps.setVPSId(0);
    vps.setEachLayerIsAnOlsFlag(1); // If vps_max_layers_minus1 is equal to 0,
                                    // the value of each_layer_is_an_ols_flag is inferred to be equal to 1.
                                    // Otherwise, when vps_all_independent_layers_flag is equal to 0,
                                    // the value of each_layer_is_an_ols_flag is inferred to be equal to 0.
  }
  vps.setMaxSubLayers(m_maxSublayers);
  if (vps.getMaxLayers() > 1 && vps.getMaxSubLayers() > 1)
  {
    vps.setAllLayersSameNumSublayersFlag(m_allLayersSameNumSublayersFlag);
  }
  if (vps.getMaxLayers() > 1)
  {
    vps.setAllIndependentLayersFlag(m_allIndependentLayersFlag);
    if (!vps.getAllIndependentLayersFlag())
    {
      vps.setEachLayerIsAnOlsFlag(0);
    }
  }

  for (int i = 0; i < vps.getMaxLayers(); i++)
  {
    vps.setGeneralLayerIdx( m_layerId[i], i );
    vps.setLayerId(i, m_layerId[i]);

    if (i > 0 && !vps.getAllIndependentLayersFlag())
    {
      vps.setIndependentLayerFlag( i, m_numRefLayers[i] ? false : true );

      if (!vps.getIndependentLayerFlag(i))
      {
        for (int j = 0, k = 0; j < i; j++)
        {
          if (m_refLayerIdxStr[i].find(to_string(j)) != std::string::npos)
          {
            vps.setDirectRefLayerFlag(i, j, true);
            vps.setInterLayerRefIdc( i, j, k );
            vps.setDirectRefLayerIdx(i, k++, j);
          }
          else
          {
            vps.setDirectRefLayerFlag(i, j, false);
          }
        }
      }
    }
  }


  if (vps.getMaxLayers() > 1)
  {
    if (vps.getAllIndependentLayersFlag())
    {
      vps.setEachLayerIsAnOlsFlag(m_eachLayerIsAnOlsFlag);
      if (vps.getEachLayerIsAnOlsFlag() == 0)
      {
        vps.setOlsModeIdc(2); // When vps_all_independent_layers_flag is equal to 1 and each_layer_is_an_ols_flag is equal to 0, the value of ols_mode_idc is inferred to be equal to 2
      }
    }
    if (!vps.getEachLayerIsAnOlsFlag())
    {
      if (!vps.getAllIndependentLayersFlag())
      {
        vps.setOlsModeIdc(m_olsModeIdc);
      }
      if (vps.getOlsModeIdc() == 2)
      {
        vps.setNumOutputLayerSets(m_numOutputLayerSets);
        for (int i = 1; i < vps.getNumOutputLayerSets(); i++)
        {
          for (int j = 0; j < vps.getMaxLayers(); j++)
          {
            if (m_olsOutputLayerStr[i].find(to_string(j)) != std::string::npos)
            {
              vps.setOlsOutputLayerFlag(i, j, 1);
            }
            else
            {
              vps.setOlsOutputLayerFlag(i, j, 0);
            }
          }
        }
      }
    }
  }
#if JVET_Q0786_PTL_only
  CHECK( m_numPtlsInVps == 0, "There has to be at least one PTL structure in the VPS." );
  vps.setNumPtls                                                 ( m_numPtlsInVps );
  vps.setPtPresentFlag                                           (0, 1);
  for (int i = 0; i < vps.getNumPtls(); i++)
  {
    if( i > 0 )
      vps.setPtPresentFlag                                         (i, 0);
    vps.setPtlMaxTemporalId                                      (i, vps.getMaxSubLayers() - 1); 
  }
  for (int i = 0; i < vps.getNumOutputLayerSets(); i++)
  {
    vps.setOlsPtlIdx                                             (i, m_olsPtlIdx[i]);
  }
  std::vector<ProfileTierLevel> ptls;
  ptls.resize(vps.getNumPtls());
  // PTL0 shall be the same as the one signalled in the SPS
  ptls[0].setLevelIdc                                            ( m_level );
  ptls[0].setProfileIdc                                          ( m_profile);
  ptls[0].setTierFlag                                            ( m_levelTier );
  ptls[0].setNumSubProfile                                       ( m_numSubProfile );
  for (int i = 0; i < m_numSubProfile; i++)
  {
    ptls[0].setSubProfileIdc                                   (i, m_subProfile[i]);
  }
  for(int i = 1; i < vps.getNumPtls(); i++)
  {
    ptls[i].setLevelIdc                                          (m_levelPtl[i]);
  }
  vps.setProfileTierLevel(ptls);
#endif
  vps.setVPSExtensionFlag                                        ( false );
#if !JVET_Q0814_DPB
  m_cEncLib.setVPS(&vps);
#endif
  m_cEncLib.setProfile                                           ( m_profile);
  m_cEncLib.setLevel                                             ( m_levelTier, m_level);
  m_cEncLib.setNumSubProfile                                     ( m_numSubProfile );
  for (int i = 0; i < m_numSubProfile; i++)
  {
    m_cEncLib.setSubProfile(i, m_subProfile[i]);
  }
  m_cEncLib.setProgressiveSourceFlag                             ( m_progressiveSourceFlag);
  m_cEncLib.setInterlacedSourceFlag                              ( m_interlacedSourceFlag);
  m_cEncLib.setNonPackedConstraintFlag                           ( m_nonPackedConstraintFlag);
#if JVET_Q0114_CONSTRAINT_FLAGS
  m_cEncLib.setNonProjectedConstraintFlag                        ( m_nonProjectedConstraintFlag );
  m_cEncLib.setNoResChangeInClvsConstraintFlag                   ( m_noResChangeInClvsConstraintFlag );
  m_cEncLib.setOneTilePerPicConstraintFlag                       ( m_oneTilePerPicConstraintFlag );
  m_cEncLib.setOneSlicePerPicConstraintFlag                      ( m_oneSlicePerPicConstraintFlag );
  m_cEncLib.setOneSubpicPerPicConstraintFlag                     ( m_oneSubpicPerPicConstraintFlag );
#endif
  m_cEncLib.setFrameOnlyConstraintFlag                           ( m_frameOnlyConstraintFlag);
  m_cEncLib.setIntraConstraintFlag                               ( m_intraConstraintFlag );

  m_cEncLib.setPrintMSEBasedSequencePSNR                         ( m_printMSEBasedSequencePSNR);
  m_cEncLib.setPrintFrameMSE                                     ( m_printFrameMSE);
  m_cEncLib.setPrintHexPsnr(m_printHexPsnr);
  m_cEncLib.setPrintSequenceMSE                                  ( m_printSequenceMSE);
  m_cEncLib.setCabacZeroWordPaddingEnabled                       ( m_cabacZeroWordPaddingEnabled );

  m_cEncLib.setFrameRate                                         ( m_iFrameRate );
  m_cEncLib.setFrameSkip                                         ( m_FrameSkip );
  m_cEncLib.setTemporalSubsampleRatio                            ( m_temporalSubsampleRatio );
  m_cEncLib.setSourceWidth                                       ( m_iSourceWidth );
  m_cEncLib.setSourceHeight                                      ( m_iSourceHeight );
  m_cEncLib.setConformanceWindow                                 ( m_confWinLeft / SPS::getWinUnitX( m_InputChromaFormatIDC ), m_confWinRight / SPS::getWinUnitX( m_InputChromaFormatIDC ), m_confWinTop / SPS::getWinUnitY( m_InputChromaFormatIDC ), m_confWinBottom / SPS::getWinUnitY( m_InputChromaFormatIDC ) );
  m_cEncLib.setScalingRatio                                      ( m_scalingRatioHor, m_scalingRatioVer );
  m_cEncLib.setRPREnabled                                        ( m_rprEnabled );
  m_cEncLib.setSwitchPocPeriod                                   ( m_switchPocPeriod );
  m_cEncLib.setUpscaledOutput                                    ( m_upscaledOutput );
  m_cEncLib.setFramesToBeEncoded                                 ( m_framesToBeEncoded );

  //====== SPS constraint flags =======
  m_cEncLib.setIntraOnlyConstraintFlag                           ( m_intraConstraintFlag );
  m_cEncLib.setMaxBitDepthConstraintIdc                          ( m_bitDepthConstraint - 8 );
  m_cEncLib.setMaxChromaFormatConstraintIdc                      ( m_chromaFormatConstraint );
  m_cEncLib.setFrameConstraintFlag                               ( m_bFrameConstraintFlag );
  m_cEncLib.setNoQtbttDualTreeIntraConstraintFlag                ( !m_dualTree );
  m_cEncLib.setNoPartitionConstraintsOverrideConstraintFlag      ( !m_SplitConsOverrideEnabledFlag );
  m_cEncLib.setNoSaoConstraintFlag                               ( !m_bUseSAO );
  m_cEncLib.setNoAlfConstraintFlag                               ( !m_alf );
#if JVET_Q0795_CCALF
  m_cEncLib.setNoAlfConstraintFlag                               ( !m_ccalf );
#endif
  m_cEncLib.setNoRefWraparoundConstraintFlag                     ( m_bNoRefWraparoundConstraintFlag );
  m_cEncLib.setNoTemporalMvpConstraintFlag                       ( m_TMVPModeId ? false : true );
  m_cEncLib.setNoSbtmvpConstraintFlag                            ( m_SubPuMvpMode ? false : true );
  m_cEncLib.setNoAmvrConstraintFlag                              ( m_bNoAmvrConstraintFlag );
  m_cEncLib.setNoBdofConstraintFlag                              ( !m_BIO );
  m_cEncLib.setNoDmvrConstraintFlag                              ( !m_DMVR );
  m_cEncLib.setNoCclmConstraintFlag                              ( m_LMChroma ? false : true );
  m_cEncLib.setNoMtsConstraintFlag                               ( (m_MTS || m_MTSImplicit) ? false : true );
  m_cEncLib.setNoSbtConstraintFlag                               ( !m_SBT );
  m_cEncLib.setNoAffineMotionConstraintFlag                      ( !m_Affine );
  m_cEncLib.setNoBcwConstraintFlag                               ( !m_bcw );
  m_cEncLib.setNoIbcConstraintFlag                               ( m_IBCMode ? false : true );
  m_cEncLib.setNoCiipConstraintFlag                           ( !m_ciip );
  m_cEncLib.setNoFPelMmvdConstraintFlag                          ( !(m_MMVD && m_allowDisFracMMVD) );
#if !JVET_Q0806
  m_cEncLib.setNoTriangleConstraintFlag                          ( !m_Triangle );
#else
  m_cEncLib.setNoGeoConstraintFlag                               ( !m_Geo );
#endif
  m_cEncLib.setNoLadfConstraintFlag                              ( !m_LadfEnabed );
  m_cEncLib.setNoTransformSkipConstraintFlag                     ( !m_useTransformSkip );
#if JVET_Q0089_SLICE_LOSSLESS_CODING_CHROMA_BDPCM
  m_cEncLib.setNoBDPCMConstraintFlag                             ( !m_useBDPCM );
#else
  m_cEncLib.setNoBDPCMConstraintFlag                             ( m_useBDPCM == 0 );
#endif
  m_cEncLib.setNoJointCbCrConstraintFlag                         (!m_JointCbCrMode);
  m_cEncLib.setNoQpDeltaConstraintFlag                           ( m_bNoQpDeltaConstraintFlag );
  m_cEncLib.setNoDepQuantConstraintFlag                          ( !m_depQuantEnabledFlag);
  m_cEncLib.setNoSignDataHidingConstraintFlag                    ( !m_signDataHidingEnabledFlag );
  m_cEncLib.setNoTrailConstraintFlag                             ( m_iIntraPeriod == 1 );
  m_cEncLib.setNoStsaConstraintFlag                              ( m_iIntraPeriod == 1 || !xHasNonZeroTemporalID() );
  m_cEncLib.setNoRaslConstraintFlag                              ( m_iIntraPeriod == 1 || !xHasLeadingPicture() );
  m_cEncLib.setNoRadlConstraintFlag                              ( m_iIntraPeriod == 1 || !xHasLeadingPicture() );
  m_cEncLib.setNoIdrConstraintFlag                               ( false ); // Not yet possible to encode bitstream starting with a GDR picture
  m_cEncLib.setNoCraConstraintFlag                               ( m_iDecodingRefreshType != 1 );
  m_cEncLib.setNoGdrConstraintFlag                               ( false ); // Not yet possible to encode GDR using config parameters
  m_cEncLib.setNoApsConstraintFlag                               ( !m_alf && !m_lmcsEnabled && m_useScalingListId == SCALING_LIST_OFF);

  //====== Coding Structure ========
  m_cEncLib.setIntraPeriod                                       ( m_iIntraPeriod );
  m_cEncLib.setDecodingRefreshType                               ( m_iDecodingRefreshType );
  m_cEncLib.setGOPSize                                           ( m_iGOPSize );
  m_cEncLib.setDrapPeriod                                        ( m_drapPeriod );
  m_cEncLib.setReWriteParamSets                                  ( m_rewriteParamSets );
  m_cEncLib.setRPLList0                                          ( m_RPLList0);
  m_cEncLib.setRPLList1                                          ( m_RPLList1);
  m_cEncLib.setIDRRefParamListPresent                            ( m_idrRefParamList );
  m_cEncLib.setGopList                                           ( m_GOPList );

  for(int i = 0; i < MAX_TLAYER; i++)
  {
    m_cEncLib.setNumReorderPics                                  ( m_numReorderPics[i], i );
    m_cEncLib.setMaxDecPicBuffering                              ( m_maxDecPicBuffering[i], i );
  }
  for( uint32_t uiLoop = 0; uiLoop < MAX_TLAYER; ++uiLoop )
  {
    m_cEncLib.setLambdaModifier                                  ( uiLoop, m_adLambdaModifier[ uiLoop ] );
  }
  m_cEncLib.setIntraLambdaModifier                               ( m_adIntraLambdaModifier );
  m_cEncLib.setIntraQpFactor                                     ( m_dIntraQpFactor );

  m_cEncLib.setBaseQP                                            ( m_iQP );

#if X0038_LAMBDA_FROM_QP_CAPABILITY
  m_cEncLib.setIntraQPOffset                                     ( m_intraQPOffset );
  m_cEncLib.setLambdaFromQPEnable                                ( m_lambdaFromQPEnable );
#endif
  m_cEncLib.setChromaQpMappingTableParams                         (m_chromaQpMappingTableParams);

  m_cEncLib.setPad                                               ( m_aiPad );

  m_cEncLib.setAccessUnitDelimiter                               ( m_AccessUnitDelimiter );
#if JVET_Q0775_PH_IN_SH
  m_cEncLib.setEnablePictureHeaderInSliceHeader                  ( m_enablePictureHeaderInSliceHeader );
#endif

  m_cEncLib.setMaxTempLayer                                      ( m_maxTempLayer );

  //===== Slice ========

  //====== Loop/Deblock Filter ========
  m_cEncLib.setLoopFilterDisable                                 ( m_bLoopFilterDisable       );
  m_cEncLib.setLoopFilterOffsetInPPS                             ( m_loopFilterOffsetInPPS );
  m_cEncLib.setLoopFilterBetaOffset                              ( m_loopFilterBetaOffsetDiv2  );
  m_cEncLib.setLoopFilterTcOffset                                ( m_loopFilterTcOffsetDiv2    );
#if JVET_Q0121_DEBLOCKING_CONTROL_PARAMETERS
  m_cEncLib.setLoopFilterCbBetaOffset                            ( m_loopFilterCbBetaOffsetDiv2  );
  m_cEncLib.setLoopFilterCbTcOffset                              ( m_loopFilterCbTcOffsetDiv2    );
  m_cEncLib.setLoopFilterCrBetaOffset                            ( m_loopFilterCrBetaOffsetDiv2  );
  m_cEncLib.setLoopFilterCrTcOffset                              ( m_loopFilterCrTcOffsetDiv2    );
#endif
#if W0038_DB_OPT
  m_cEncLib.setDeblockingFilterMetric                            ( m_deblockingFilterMetric );
#else
  m_cEncLib.setDeblockingFilterMetric                            ( m_DeblockingFilterMetric );
#endif

  //====== Motion search ========
  m_cEncLib.setDisableIntraPUsInInterSlices                      ( m_bDisableIntraPUsInInterSlices );
  m_cEncLib.setMotionEstimationSearchMethod                      ( m_motionEstimationSearchMethod  );
  m_cEncLib.setSearchRange                                       ( m_iSearchRange );
  m_cEncLib.setBipredSearchRange                                 ( m_bipredSearchRange );
  m_cEncLib.setClipForBiPredMeEnabled                            ( m_bClipForBiPredMeEnabled );
  m_cEncLib.setFastMEAssumingSmootherMVEnabled                   ( m_bFastMEAssumingSmootherMVEnabled );
  m_cEncLib.setMinSearchWindow                                   ( m_minSearchWindow );
  m_cEncLib.setRestrictMESampling                                ( m_bRestrictMESampling );

  //====== Quality control ========
  m_cEncLib.setMaxDeltaQP                                        ( m_iMaxDeltaQP  );
  m_cEncLib.setCuQpDeltaSubdiv                                   ( m_cuQpDeltaSubdiv );
  m_cEncLib.setCuChromaQpOffsetSubdiv                            ( m_cuChromaQpOffsetSubdiv );
  m_cEncLib.setChromaCbQpOffset                                  ( m_cbQpOffset     );
  m_cEncLib.setChromaCrQpOffset                                  ( m_crQpOffset  );
  m_cEncLib.setChromaCbQpOffsetDualTree                          ( m_cbQpOffsetDualTree );
  m_cEncLib.setChromaCrQpOffsetDualTree                          ( m_crQpOffsetDualTree );
  m_cEncLib.setChromaCbCrQpOffset                                ( m_cbCrQpOffset         );
  m_cEncLib.setChromaCbCrQpOffsetDualTree                        ( m_cbCrQpOffsetDualTree );
#if ER_CHROMA_QP_WCG_PPS
  m_cEncLib.setWCGChromaQpControl                                ( m_wcgChromaQpControl );
#endif
#if W0038_CQP_ADJ
  m_cEncLib.setSliceChromaOffsetQpIntraOrPeriodic                ( m_sliceChromaQpOffsetPeriodicity, m_sliceChromaQpOffsetIntraOrPeriodic );
#endif
  m_cEncLib.setChromaFormatIdc                                   ( m_chromaFormatIDC  );
  m_cEncLib.setUseAdaptiveQP                                     ( m_bUseAdaptiveQP  );
  m_cEncLib.setQPAdaptationRange                                 ( m_iQPAdaptationRange );
#if ENABLE_QPA
  m_cEncLib.setUsePerceptQPA                                     ( m_bUsePerceptQPA && !m_bUseAdaptiveQP );
  m_cEncLib.setUseWPSNR                                          ( m_bUseWPSNR );
#endif
  m_cEncLib.setExtendedPrecisionProcessingFlag                   ( m_extendedPrecisionProcessingFlag );
  m_cEncLib.setHighPrecisionOffsetsEnabledFlag                   ( m_highPrecisionOffsetsEnabledFlag );

  m_cEncLib.setWeightedPredictionMethod( m_weightedPredictionMethod );

  //====== Tool list ========
#if SHARP_LUMA_DELTA_QP
  m_cEncLib.setLumaLevelToDeltaQPControls                        ( m_lumaLevelToDeltaQPMapping );
#endif
#if X0038_LAMBDA_FROM_QP_CAPABILITY
  m_cEncLib.setDeltaQpRD( (m_costMode==COST_LOSSLESS_CODING) ? 0 : m_uiDeltaQpRD );
#else
  m_cEncLib.setDeltaQpRD                                         ( m_uiDeltaQpRD  );
#endif
  m_cEncLib.setFastDeltaQp                                       ( m_bFastDeltaQP  );
  m_cEncLib.setUseASR                                            ( m_bUseASR      );
  m_cEncLib.setUseHADME                                          ( m_bUseHADME    );
  m_cEncLib.setdQPs                                              ( m_aidQP        );
  m_cEncLib.setUseRDOQ                                           ( m_useRDOQ     );
  m_cEncLib.setUseRDOQTS                                         ( m_useRDOQTS   );
#if T0196_SELECTIVE_RDOQ
  m_cEncLib.setUseSelectiveRDOQ                                  ( m_useSelectiveRDOQ );
#endif
  m_cEncLib.setRDpenalty                                         ( m_rdPenalty );
  m_cEncLib.setCTUSize                                           ( m_uiCTUSize );
#if JVET_Q0119_CLEANUPS
  m_cEncLib.setSubPicInfoPresentFlag                             ( m_subPicInfoPresentFlag );
  if(m_subPicInfoPresentFlag)
#else
  m_cEncLib.setSubPicPresentFlag                                 ( m_subPicPresentFlag );
  if(m_subPicPresentFlag)
#endif
  {
    m_cEncLib.setNumSubPics                                      ( m_numSubPics );
    for (int i = 0; i < m_numSubPics; i++)
    {
      m_cEncLib.setSubPicCtuTopLeftX                             ( m_subPicCtuTopLeftX[i], i );
      m_cEncLib.setSubPicCtuTopLeftY                             ( m_subPicCtuTopLeftY[i], i );
      m_cEncLib.setSubPicWidth                                   ( m_subPicWidth[i], i );
      m_cEncLib.setSubPicHeight                                  ( m_subPicHeight[i], i );
      m_cEncLib.setSubPicTreatedAsPicFlag                        ( m_subPicTreatedAsPicFlag[i], i );
      m_cEncLib.setLoopFilterAcrossSubpicEnabledFlag             ( m_loopFilterAcrossSubpicEnabledFlag[i], i );
    }
  }

#if JVET_Q0119_CLEANUPS
  m_cEncLib.setSubPicIdMappingExplicitlySignalledFlag            ( m_subPicIdMappingExplicitlySignalledFlag );
  if (m_subPicIdMappingExplicitlySignalledFlag)
  {
    m_cEncLib.setSubPicIdMappingInSpsFlag                        ( m_subPicIdMappingInSpsFlag );
    if(m_subPicIdMappingInSpsFlag)
#else
  m_cEncLib.setSubPicIdPresentFlag                               ( m_subPicIdPresentFlag );
  if (m_subPicIdPresentFlag) 
  {
    m_cEncLib.setSubPicIdSignallingPresentFlag                   ( m_subPicIdSignallingPresentFlag );
    if(m_subPicIdSignallingPresentFlag)
#endif
    {
      m_cEncLib.setSubPicIdLen                                   ( m_subPicIdLen );
      for (int i = 0; i < m_numSubPics; i++)
      {
        m_cEncLib.setSubPicId                                    ( m_subPicId[i], i );
      }
    }
  }
  m_cEncLib.setUseSplitConsOverride                              ( m_SplitConsOverrideEnabledFlag );
  m_cEncLib.setMinQTSizes                                        ( m_uiMinQT );
  m_cEncLib.setMaxMTTHierarchyDepth                              ( m_uiMaxMTTHierarchyDepth, m_uiMaxMTTHierarchyDepthI, m_uiMaxMTTHierarchyDepthIChroma );
#if JVET_Q0330_BLOCK_PARTITION
  m_cEncLib.setMaxBTSizes                                        ( m_uiMaxBT );
  m_cEncLib.setMaxTTSizes                                        ( m_uiMaxTT );
#endif 
  m_cEncLib.setDualITree                                         ( m_dualTree );
  m_cEncLib.setLFNST                                             ( m_LFNST );
  m_cEncLib.setUseFastLFNST                                      ( m_useFastLFNST );
  m_cEncLib.setSubPuMvpMode                                      ( m_SubPuMvpMode );
  m_cEncLib.setAffine                                            ( m_Affine );
  m_cEncLib.setAffineType                                        ( m_AffineType );
  m_cEncLib.setPROF                                              ( m_PROF );
  m_cEncLib.setBIO                                               (m_BIO);
  m_cEncLib.setUseLMChroma                                       ( m_LMChroma );
  m_cEncLib.setHorCollocatedChromaFlag                           ( m_horCollocatedChromaFlag );
  m_cEncLib.setVerCollocatedChromaFlag                           ( m_verCollocatedChromaFlag );
  m_cEncLib.setIntraMTS                                          ( m_MTS & 1 );
  m_cEncLib.setInterMTS                                          ( ( m_MTS >> 1 ) & 1 );
  m_cEncLib.setMTSIntraMaxCand                                   ( m_MTSIntraMaxCand );
  m_cEncLib.setMTSInterMaxCand                                   ( m_MTSInterMaxCand );
  m_cEncLib.setImplicitMTS                                       ( m_MTSImplicit );
  m_cEncLib.setUseSBT                                            ( m_SBT );
  m_cEncLib.setSBTFast64WidthTh                                  ( m_SBTFast64WidthTh );
  m_cEncLib.setUseCompositeRef                                   ( m_compositeRefEnabled );
  m_cEncLib.setUseSMVD                                           ( m_SMVD );
  m_cEncLib.setUseBcw                                            ( m_bcw );
  m_cEncLib.setUseBcwFast                                        ( m_BcwFast );
#if LUMA_ADAPTIVE_DEBLOCKING_FILTER_QP_OFFSET
  m_cEncLib.setUseLadf                                           ( m_LadfEnabed );
  if ( m_LadfEnabed )
  {
    m_cEncLib.setLadfNumIntervals                                ( m_LadfNumIntervals);
    for ( int k = 0; k < m_LadfNumIntervals; k++ )
    {
      m_cEncLib.setLadfQpOffset( m_LadfQpOffset[k], k );
      m_cEncLib.setLadfIntervalLowerBound(m_LadfIntervalLowerBound[k], k);
    }
  }
#endif
  m_cEncLib.setUseCiip                                        ( m_ciip );
#if !JVET_Q0806
  m_cEncLib.setUseTriangle                                       ( m_Triangle );
#else
  m_cEncLib.setUseGeo                                            ( m_Geo );
#endif
  m_cEncLib.setUseHashME                                         ( m_HashME );

  m_cEncLib.setAllowDisFracMMVD                                  ( m_allowDisFracMMVD );
  m_cEncLib.setUseAffineAmvr                                     ( m_AffineAmvr );
  m_cEncLib.setUseAffineAmvrEncOpt                               ( m_AffineAmvrEncOpt );
  m_cEncLib.setDMVR                                              ( m_DMVR );
  m_cEncLib.setMMVD                                              ( m_MMVD );
  m_cEncLib.setMmvdDisNum                                        (m_MmvdDisNum);
  m_cEncLib.setRGBFormatFlag(m_rgbFormat);
  m_cEncLib.setUseColorTrans(m_useColorTrans);
  m_cEncLib.setPLTMode                                           ( m_PLTMode );
  m_cEncLib.setJointCbCr                                         ( m_JointCbCrMode );
  m_cEncLib.setIBCMode                                           ( m_IBCMode );
  m_cEncLib.setIBCLocalSearchRangeX                              ( m_IBCLocalSearchRangeX );
  m_cEncLib.setIBCLocalSearchRangeY                              ( m_IBCLocalSearchRangeY );
  m_cEncLib.setIBCHashSearch                                     ( m_IBCHashSearch );
  m_cEncLib.setIBCHashSearchMaxCand                              ( m_IBCHashSearchMaxCand );
  m_cEncLib.setIBCHashSearchRange4SmallBlk                       ( m_IBCHashSearchRange4SmallBlk );
  m_cEncLib.setIBCFastMethod                                     ( m_IBCFastMethod );

  m_cEncLib.setUseWrapAround                                     ( m_wrapAround );
  m_cEncLib.setWrapAroundOffset                                  ( m_wrapAroundOffset );

  // ADD_NEW_TOOL : (encoder app) add setting of tool enabling flags and associated parameters here

  m_cEncLib.setLoopFilterAcrossVirtualBoundariesDisabledFlag     ( m_loopFilterAcrossVirtualBoundariesDisabledFlag );
  m_cEncLib.setNumVerVirtualBoundaries                           ( m_numVerVirtualBoundaries );
  m_cEncLib.setNumHorVirtualBoundaries                           ( m_numHorVirtualBoundaries );
  for( unsigned i = 0; i < m_numVerVirtualBoundaries; i++ )
  {
    m_cEncLib.setVirtualBoundariesPosX                           ( m_virtualBoundariesPosX[ i ], i );
  }
  for( unsigned i = 0; i < m_numHorVirtualBoundaries; i++ )
  {
    m_cEncLib.setVirtualBoundariesPosY                           ( m_virtualBoundariesPosY[ i ], i );
  }

  m_cEncLib.setMaxCUWidth                                        ( m_uiCTUSize );
  m_cEncLib.setMaxCUHeight                                       ( m_uiCTUSize );
#if JVET_Q0468_Q0469_MIN_LUMA_CB_AND_MIN_QT_FIX
  m_cEncLib.setLog2MinCodingBlockSize                            ( m_log2MinCuSize );
#else
  m_cEncLib.setMaxCodingDepth                                    ( m_uiMaxCodingDepth );
  m_cEncLib.setLog2DiffMaxMinCodingBlockSize                     ( m_uiLog2DiffMaxMinCodingBlockSize );
#endif
  m_cEncLib.setLog2MaxTbSize                                     ( m_log2MaxTbSize );
  m_cEncLib.setUseEncDbOpt(m_encDbOpt);
  m_cEncLib.setUseFastLCTU                                       ( m_useFastLCTU );
  m_cEncLib.setFastInterSearchMode                               ( m_fastInterSearchMode );
  m_cEncLib.setUseEarlyCU                                        ( m_bUseEarlyCU  );
  m_cEncLib.setUseFastDecisionForMerge                           ( m_useFastDecisionForMerge  );
  m_cEncLib.setUseCbfFastMode                                    ( m_bUseCbfFastMode  );
  m_cEncLib.setUseEarlySkipDetection                             ( m_useEarlySkipDetection );
  m_cEncLib.setUseFastMerge                                      ( m_useFastMrg );
  m_cEncLib.setUsePbIntraFast                                    ( m_usePbIntraFast );
  m_cEncLib.setUseAMaxBT                                         ( m_useAMaxBT );
  m_cEncLib.setUseE0023FastEnc                                   ( m_e0023FastEnc );
  m_cEncLib.setUseContentBasedFastQtbt                           ( m_contentBasedFastQtbt );
  m_cEncLib.setUseNonLinearAlfLuma                               ( m_useNonLinearAlfLuma );
  m_cEncLib.setUseNonLinearAlfChroma                             ( m_useNonLinearAlfChroma );
  m_cEncLib.setMaxNumAlfAlternativesChroma                       ( m_maxNumAlfAlternativesChroma );
  m_cEncLib.setUseMRL                                            ( m_MRL );
  m_cEncLib.setUseMIP                                            ( m_MIP );
  m_cEncLib.setUseFastMIP                                        ( m_useFastMIP );
  m_cEncLib.setFastLocalDualTreeMode                             ( m_fastLocalDualTreeMode );
  m_cEncLib.setCrossComponentPredictionEnabledFlag               ( m_crossComponentPredictionEnabledFlag );
  m_cEncLib.setUseReconBasedCrossCPredictionEstimate             ( m_reconBasedCrossCPredictionEstimate );
#if !JVET_Q0441_SAO_MOD_12_BIT
  m_cEncLib.setLog2SaoOffsetScale                                ( CHANNEL_TYPE_LUMA  , m_log2SaoOffsetScale[CHANNEL_TYPE_LUMA]   );
  m_cEncLib.setLog2SaoOffsetScale                                ( CHANNEL_TYPE_CHROMA, m_log2SaoOffsetScale[CHANNEL_TYPE_CHROMA] );
#endif
  m_cEncLib.setUseTransformSkip                                  ( m_useTransformSkip      );
  m_cEncLib.setUseTransformSkipFast                              ( m_useTransformSkipFast  );
  m_cEncLib.setUseChromaTS                                       ( m_useChromaTS && m_useTransformSkip);
  m_cEncLib.setUseBDPCM                                          ( m_useBDPCM );
  m_cEncLib.setTransformSkipRotationEnabledFlag                  ( m_transformSkipRotationEnabledFlag );
  m_cEncLib.setTransformSkipContextEnabledFlag                   ( m_transformSkipContextEnabledFlag   );
  m_cEncLib.setPersistentRiceAdaptationEnabledFlag               ( m_persistentRiceAdaptationEnabledFlag );
  m_cEncLib.setCabacBypassAlignmentEnabledFlag                   ( m_cabacBypassAlignmentEnabledFlag );
  m_cEncLib.setLog2MaxTransformSkipBlockSize                     ( m_log2MaxTransformSkipBlockSize  );
  for (uint32_t signallingModeIndex = 0; signallingModeIndex < NUMBER_OF_RDPCM_SIGNALLING_MODES; signallingModeIndex++)
  {
    m_cEncLib.setRdpcmEnabledFlag                                ( RDPCMSignallingMode(signallingModeIndex), m_rdpcmEnabledFlag[signallingModeIndex]);
  }
  m_cEncLib.setFastUDIUseMPMEnabled                              ( m_bFastUDIUseMPMEnabled );
  m_cEncLib.setFastMEForGenBLowDelayEnabled                      ( m_bFastMEForGenBLowDelayEnabled );
  m_cEncLib.setUseBLambdaForNonKeyLowDelayPictures               ( m_bUseBLambdaForNonKeyLowDelayPictures );
  m_cEncLib.setUseISP                                            ( m_ISP );
  m_cEncLib.setUseFastISP                                        ( m_useFastISP );

  // set internal bit-depth and constants
  for (uint32_t channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
  {
    m_cEncLib.setBitDepth((ChannelType)channelType, m_internalBitDepth[channelType]);
    m_cEncLib.setInputBitDepth((ChannelType)channelType, m_inputBitDepth[channelType]);
  }

  m_cEncLib.setMaxNumMergeCand                                   ( m_maxNumMergeCand );
  m_cEncLib.setMaxNumAffineMergeCand                             ( m_maxNumAffineMergeCand );
#if !JVET_Q0806
  m_cEncLib.setMaxNumTriangleCand                                ( m_maxNumTriangleCand );
#else
  m_cEncLib.setMaxNumGeoCand                                     ( m_maxNumGeoCand );
#endif
  m_cEncLib.setMaxNumIBCMergeCand                                ( m_maxNumIBCMergeCand );

  //====== Weighted Prediction ========
  m_cEncLib.setUseWP                                             ( m_useWeightedPred     );
  m_cEncLib.setWPBiPred                                          ( m_useWeightedBiPred   );

#if JVET_Q0297_MER
  //====== Parallel Merge Estimation ========
  m_cEncLib.setLog2ParallelMergeLevelMinus2(m_log2ParallelMergeLevel - 2);
#endif

  //====== Tiles and Slices ========
  m_cEncLib.setNoPicPartitionFlag( !m_picPartitionFlag );
  if( m_picPartitionFlag )
  {
    m_cEncLib.setTileColWidths( m_tileColumnWidth );
    m_cEncLib.setTileRowHeights( m_tileRowHeight );
    m_cEncLib.setRectSliceFlag( !m_rasterSliceFlag );
    m_cEncLib.setNumSlicesInPic( m_numSlicesInPic );
    m_cEncLib.setTileIdxDeltaPresentFlag( m_tileIdxDeltaPresentFlag );
    m_cEncLib.setRectSlices( m_rectSlices );
    m_cEncLib.setRasterSliceSizes( m_rasterSliceSize );
    m_cEncLib.setLFCrossTileBoundaryFlag( !m_disableLFCrossTileBoundaryFlag );
    m_cEncLib.setLFCrossSliceBoundaryFlag( !m_disableLFCrossSliceBoundaryFlag );
  }
  else
  {
    m_cEncLib.setRectSliceFlag( true );
    m_cEncLib.setNumSlicesInPic( 1 );
    m_cEncLib.setTileIdxDeltaPresentFlag( 0 );
    m_cEncLib.setLFCrossTileBoundaryFlag( true );
    m_cEncLib.setLFCrossSliceBoundaryFlag( true );
  }

  //====== Sub-picture and Slices ========
  m_cEncLib.setSingleSlicePerSubPicFlagFlag                      ( m_singleSlicePerSubPicFlag );
  m_cEncLib.setUseSAO                                            ( m_bUseSAO );
  m_cEncLib.setTestSAODisableAtPictureLevel                      ( m_bTestSAODisableAtPictureLevel );
  m_cEncLib.setSaoEncodingRate                                   ( m_saoEncodingRate );
  m_cEncLib.setSaoEncodingRateChroma                             ( m_saoEncodingRateChroma );
  m_cEncLib.setMaxNumOffsetsPerPic                               ( m_maxNumOffsetsPerPic);

  m_cEncLib.setSaoCtuBoundary                                    ( m_saoCtuBoundary);

  m_cEncLib.setSaoGreedyMergeEnc                                 ( m_saoGreedyMergeEnc);
  m_cEncLib.setIntraSmoothingDisabledFlag                        (!m_enableIntraReferenceSmoothing );
  m_cEncLib.setDecodedPictureHashSEIType                         ( m_decodedPictureHashSEIType );
#if HEVC_SEI
  m_cEncLib.setRecoveryPointSEIEnabled                           ( m_recoveryPointSEIEnabled );
#endif
  m_cEncLib.setDependentRAPIndicationSEIEnabled                  ( m_drapPeriod > 0 );
  m_cEncLib.setBufferingPeriodSEIEnabled                         ( m_bufferingPeriodSEIEnabled );
  m_cEncLib.setPictureTimingSEIEnabled                           ( m_pictureTimingSEIEnabled );
  m_cEncLib.setFrameFieldInfoSEIEnabled                          ( m_frameFieldInfoSEIEnabled );
   m_cEncLib.setBpDeltasGOPStructure                             ( m_bpDeltasGOPStructure );
  m_cEncLib.setDecodingUnitInfoSEIEnabled                        ( m_decodingUnitInfoSEIEnabled );
  m_cEncLib.setHrdParametersPresentFlag                          ( m_hrdParametersPresentFlag );
  m_cEncLib.setFramePackingArrangementSEIEnabled                 ( m_framePackingSEIEnabled );
  m_cEncLib.setFramePackingArrangementSEIType                    ( m_framePackingSEIType );
  m_cEncLib.setFramePackingArrangementSEIId                      ( m_framePackingSEIId );
  m_cEncLib.setFramePackingArrangementSEIQuincunx                ( m_framePackingSEIQuincunx );
  m_cEncLib.setFramePackingArrangementSEIInterpretation          ( m_framePackingSEIInterpretation );
  m_cEncLib.setErpSEIEnabled                                     ( m_erpSEIEnabled );           
  m_cEncLib.setErpSEICancelFlag                                  ( m_erpSEICancelFlag );        
  m_cEncLib.setErpSEIPersistenceFlag                             ( m_erpSEIPersistenceFlag );   
  m_cEncLib.setErpSEIGuardBandFlag                               ( m_erpSEIGuardBandFlag );     
  m_cEncLib.setErpSEIGuardBandType                               ( m_erpSEIGuardBandType );     
  m_cEncLib.setErpSEILeftGuardBandWidth                          ( m_erpSEILeftGuardBandWidth );
  m_cEncLib.setErpSEIRightGuardBandWidth                         ( m_erpSEIRightGuardBandWidth );
  m_cEncLib.setSphereRotationSEIEnabled                          ( m_sphereRotationSEIEnabled );
  m_cEncLib.setSphereRotationSEICancelFlag                       ( m_sphereRotationSEICancelFlag );
  m_cEncLib.setSphereRotationSEIPersistenceFlag                  ( m_sphereRotationSEIPersistenceFlag );
  m_cEncLib.setSphereRotationSEIYaw                              ( m_sphereRotationSEIYaw );
  m_cEncLib.setSphereRotationSEIPitch                            ( m_sphereRotationSEIPitch );
  m_cEncLib.setSphereRotationSEIRoll                             ( m_sphereRotationSEIRoll );
  m_cEncLib.setOmniViewportSEIEnabled                            ( m_omniViewportSEIEnabled );          
  m_cEncLib.setOmniViewportSEIId                                 ( m_omniViewportSEIId );               
  m_cEncLib.setOmniViewportSEICancelFlag                         ( m_omniViewportSEICancelFlag );       
  m_cEncLib.setOmniViewportSEIPersistenceFlag                    ( m_omniViewportSEIPersistenceFlag );  
  m_cEncLib.setOmniViewportSEICntMinus1                          ( m_omniViewportSEICntMinus1 );        
  m_cEncLib.setOmniViewportSEIAzimuthCentre                      ( m_omniViewportSEIAzimuthCentre );    
  m_cEncLib.setOmniViewportSEIElevationCentre                    ( m_omniViewportSEIElevationCentre );  
  m_cEncLib.setOmniViewportSEITiltCentre                         ( m_omniViewportSEITiltCentre );       
  m_cEncLib.setOmniViewportSEIHorRange                           ( m_omniViewportSEIHorRange );         
  m_cEncLib.setOmniViewportSEIVerRange                           ( m_omniViewportSEIVerRange );         
  m_cEncLib.setRwpSEIEnabled                                     (m_rwpSEIEnabled);
  m_cEncLib.setRwpSEIRwpCancelFlag                               (m_rwpSEIRwpCancelFlag);
  m_cEncLib.setRwpSEIRwpPersistenceFlag                          (m_rwpSEIRwpPersistenceFlag);
  m_cEncLib.setRwpSEIConstituentPictureMatchingFlag              (m_rwpSEIConstituentPictureMatchingFlag);
  m_cEncLib.setRwpSEINumPackedRegions                            (m_rwpSEINumPackedRegions);
  m_cEncLib.setRwpSEIProjPictureWidth                            (m_rwpSEIProjPictureWidth);
  m_cEncLib.setRwpSEIProjPictureHeight                           (m_rwpSEIProjPictureHeight);
  m_cEncLib.setRwpSEIPackedPictureWidth                          (m_rwpSEIPackedPictureWidth);
  m_cEncLib.setRwpSEIPackedPictureHeight                         (m_rwpSEIPackedPictureHeight);
  m_cEncLib.setRwpSEIRwpTransformType                            (m_rwpSEIRwpTransformType);
  m_cEncLib.setRwpSEIRwpGuardBandFlag                            (m_rwpSEIRwpGuardBandFlag);
  m_cEncLib.setRwpSEIProjRegionWidth                             (m_rwpSEIProjRegionWidth);
  m_cEncLib.setRwpSEIProjRegionHeight                            (m_rwpSEIProjRegionHeight);
  m_cEncLib.setRwpSEIRwpSEIProjRegionTop                         (m_rwpSEIRwpSEIProjRegionTop);
  m_cEncLib.setRwpSEIProjRegionLeft                              (m_rwpSEIProjRegionLeft);
  m_cEncLib.setRwpSEIPackedRegionWidth                           (m_rwpSEIPackedRegionWidth);
  m_cEncLib.setRwpSEIPackedRegionHeight                          (m_rwpSEIPackedRegionHeight);
  m_cEncLib.setRwpSEIPackedRegionTop                             (m_rwpSEIPackedRegionTop);
  m_cEncLib.setRwpSEIPackedRegionLeft                            (m_rwpSEIPackedRegionLeft);
  m_cEncLib.setRwpSEIRwpLeftGuardBandWidth                       (m_rwpSEIRwpLeftGuardBandWidth);
  m_cEncLib.setRwpSEIRwpRightGuardBandWidth                      (m_rwpSEIRwpRightGuardBandWidth);
  m_cEncLib.setRwpSEIRwpTopGuardBandHeight                       (m_rwpSEIRwpTopGuardBandHeight);
  m_cEncLib.setRwpSEIRwpBottomGuardBandHeight                    (m_rwpSEIRwpBottomGuardBandHeight);
  m_cEncLib.setRwpSEIRwpGuardBandNotUsedForPredFlag              (m_rwpSEIRwpGuardBandNotUsedForPredFlag);
  m_cEncLib.setRwpSEIRwpGuardBandType                            (m_rwpSEIRwpGuardBandType);
  m_cEncLib.setGcmpSEIEnabled                                    ( m_gcmpSEIEnabled );
  m_cEncLib.setGcmpSEICancelFlag                                 ( m_gcmpSEICancelFlag );
  m_cEncLib.setGcmpSEIPersistenceFlag                            ( m_gcmpSEIPersistenceFlag );                                                              
  m_cEncLib.setGcmpSEIPackingType                                ( (uint8_t)m_gcmpSEIPackingType );
  m_cEncLib.setGcmpSEIMappingFunctionType                        ( (uint8_t)m_gcmpSEIMappingFunctionType );                                                              
  m_cEncLib.setGcmpSEIFaceIndex                                  ( m_gcmpSEIFaceIndex );
  m_cEncLib.setGcmpSEIFaceRotation                               ( m_gcmpSEIFaceRotation );
  m_cEncLib.setGcmpSEIFunctionCoeffU                             ( m_gcmpSEIFunctionCoeffU );
  m_cEncLib.setGcmpSEIFunctionUAffectedByVFlag                   ( m_gcmpSEIFunctionUAffectedByVFlag );
  m_cEncLib.setGcmpSEIFunctionCoeffV                             ( m_gcmpSEIFunctionCoeffV );
  m_cEncLib.setGcmpSEIFunctionVAffectedByUFlag                   ( m_gcmpSEIFunctionVAffectedByUFlag );                                                              
  m_cEncLib.setGcmpSEIGuardBandFlag                              ( m_gcmpSEIGuardBandFlag );
  m_cEncLib.setGcmpSEIGuardBandBoundaryType                      ( m_gcmpSEIGuardBandBoundaryType );
  m_cEncLib.setGcmpSEIGuardBandSamplesMinus1                     ( (uint8_t)m_gcmpSEIGuardBandSamplesMinus1 );
  m_cEncLib.setSubpicureLevelInfoSEIEnabled                      (m_subpicureLevelInfoSEIEnabled);
  m_cEncLib.setSampleAspectRatioInfoSEIEnabled                   (m_sampleAspectRatioInfoSEIEnabled);
  m_cEncLib.setSariCancelFlag                                    (m_sariCancelFlag);
  m_cEncLib.setSariPersistenceFlag                               (m_sariPersistenceFlag);
  m_cEncLib.setSariAspectRatioIdc                                (m_sariAspectRatioIdc);
  m_cEncLib.setSariSarWidth                                      (m_sariSarWidth);
  m_cEncLib.setSariSarHeight                                     (m_sariSarHeight);
  m_cEncLib.setMCTSEncConstraint                                 ( m_MCTSEncConstraint);
  m_cEncLib.setMasteringDisplaySEI                               ( m_masteringDisplay );
#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
  m_cEncLib.setSEIAlternativeTransferCharacteristicsSEIEnable    ( m_preferredTransferCharacteristics>=0     );
  m_cEncLib.setSEIPreferredTransferCharacteristics               ( uint8_t(m_preferredTransferCharacteristics) );
#endif
  // film grain charcteristics
  m_cEncLib.setFilmGrainCharactersticsSEIEnabled                 (m_fgcSEIEnabled);
  m_cEncLib.setFilmGrainCharactersticsSEICancelFlag              (m_fgcSEICancelFlag);
  m_cEncLib.setFilmGrainCharactersticsSEIPersistenceFlag         (m_fgcSEIPersistenceFlag);
  m_cEncLib.setFilmGrainCharactersticsSEIModelID                 ((uint8_t)m_fgcSEIModelID);
  m_cEncLib.setFilmGrainCharactersticsSEISepColourDescPresent    (m_fgcSEISepColourDescPresentFlag);
  m_cEncLib.setFilmGrainCharactersticsSEIBlendingModeID          ((uint8_t)m_fgcSEIBlendingModeID);
  m_cEncLib.setFilmGrainCharactersticsSEILog2ScaleFactor         ((uint8_t)m_fgcSEILog2ScaleFactor);
  for (int i = 0; i < MAX_NUM_COMPONENT; i++) {
    m_cEncLib.setFGCSEICompModelPresent                          (m_fgcSEICompModelPresent[i], i);
  }
  // content light level
  m_cEncLib.setCLLSEIEnabled                                     (m_cllSEIEnabled);
  m_cEncLib.setCLLSEIMaxContentLightLevel                        ((uint16_t)m_cllSEIMaxContentLevel);
  m_cEncLib.setCLLSEIMaxPicAvgLightLevel                         ((uint16_t)m_cllSEIMaxPicAvgLevel);
  // ambient viewing enviornment
  m_cEncLib.setAmbientViewingEnvironmentSEIEnabled               (m_aveSEIEnabled);
  m_cEncLib.setAmbientViewingEnvironmentSEIIlluminance           (m_aveSEIAmbientIlluminance);
  m_cEncLib.setAmbientViewingEnvironmentSEIAmbientLightX         ((uint16_t)m_aveSEIAmbientLightX);
  m_cEncLib.setAmbientViewingEnvironmentSEIAmbientLightY         ((uint16_t)m_aveSEIAmbientLightY);
  // content colour volume SEI
  m_cEncLib.setCcvSEIEnabled                                     (m_ccvSEIEnabled);
  m_cEncLib.setCcvSEICancelFlag                                  (m_ccvSEICancelFlag);
  m_cEncLib.setCcvSEIPersistenceFlag                             (m_ccvSEIPersistenceFlag);
  m_cEncLib.setCcvSEIEnabled                                     (m_ccvSEIEnabled);
  m_cEncLib.setCcvSEICancelFlag                                  (m_ccvSEICancelFlag);
  m_cEncLib.setCcvSEIPersistenceFlag                             (m_ccvSEIPersistenceFlag);
  m_cEncLib.setCcvSEIPrimariesPresentFlag                        (m_ccvSEIPrimariesPresentFlag);
  m_cEncLib.setCcvSEIMinLuminanceValuePresentFlag                (m_ccvSEIMinLuminanceValuePresentFlag);
  m_cEncLib.setCcvSEIMaxLuminanceValuePresentFlag                (m_ccvSEIMaxLuminanceValuePresentFlag);
  m_cEncLib.setCcvSEIAvgLuminanceValuePresentFlag                (m_ccvSEIAvgLuminanceValuePresentFlag);
  for(int i = 0; i < MAX_NUM_COMPONENT; i++) {
    m_cEncLib.setCcvSEIPrimariesX                                (m_ccvSEIPrimariesX[i], i);
    m_cEncLib.setCcvSEIPrimariesY                                (m_ccvSEIPrimariesY[i], i);
  }
  m_cEncLib.setCcvSEIMinLuminanceValue                           (m_ccvSEIMinLuminanceValue);
  m_cEncLib.setCcvSEIMaxLuminanceValue                           (m_ccvSEIMaxLuminanceValue);
  m_cEncLib.setCcvSEIAvgLuminanceValue                           (m_ccvSEIAvgLuminanceValue);
  m_cEncLib.setEntropyCodingSyncEnabledFlag                      ( m_entropyCodingSyncEnabledFlag );
  m_cEncLib.setTMVPModeId                                        ( m_TMVPModeId );
  m_cEncLib.setSliceLevelRpl                                     ( m_sliceLevelRpl  );
  m_cEncLib.setSliceLevelDblk                                    ( m_sliceLevelDblk );
  m_cEncLib.setSliceLevelSao                                     ( m_sliceLevelSao  );
#if JVET_Q0819_PH_CHANGES 
  m_cEncLib.setSliceLevelWp                                      ( m_sliceLevelWp );
  m_cEncLib.setSliceLevelDeltaQp                                 ( m_sliceLevelDeltaQp );
#endif
  m_cEncLib.setSliceLevelAlf                                     ( m_sliceLevelAlf  );
#if !JVET_Q0482_REMOVE_CONSTANT_PARAMS
  m_cEncLib.setConstantSliceHeaderParamsEnabledFlag              ( m_constantSliceHeaderParamsEnabledFlag );
  m_cEncLib.setPPSDepQuantEnabledIdc                             ( m_PPSDepQuantEnabledIdc );
  m_cEncLib.setPPSRefPicListSPSIdc0                              ( m_PPSRefPicListSPSIdc0 );
  m_cEncLib.setPPSRefPicListSPSIdc1                              ( m_PPSRefPicListSPSIdc1 );
  m_cEncLib.setPPSMvdL1ZeroIdc                                   ( m_PPSMvdL1ZeroIdc );
  m_cEncLib.setPPSCollocatedFromL0Idc                            ( m_PPSCollocatedFromL0Idc );
  m_cEncLib.setPPSSixMinusMaxNumMergeCandPlus1                   ( m_PPSSixMinusMaxNumMergeCandPlus1 );
#endif
#if !JVET_Q0806
#if !JVET_Q0482_REMOVE_CONSTANT_PARAMS
  m_cEncLib.setPPSMaxNumMergeCandMinusMaxNumTriangleCandPlus1    ( m_PPSMaxNumMergeCandMinusMaxNumTriangleCandPlus1 );
#endif
#else
#if !JVET_Q0482_REMOVE_CONSTANT_PARAMS
  m_cEncLib.setPPSMaxNumMergeCandMinusMaxNumGeoCandPlus1    ( m_PPSMaxNumMergeCandMinusMaxNumGeoCandPlus1 );
#endif
#endif
  m_cEncLib.setUseScalingListId                                  ( m_useScalingListId  );
  m_cEncLib.setScalingListFileName                               ( m_scalingListFileName );
  m_cEncLib.setDisableScalingMatrixForLfnstBlks                  ( m_disableScalingMatrixForLfnstBlks);
  m_cEncLib.setDepQuantEnabledFlag                               ( m_depQuantEnabledFlag);
  m_cEncLib.setSignDataHidingEnabledFlag                         ( m_signDataHidingEnabledFlag);
  m_cEncLib.setUseRateCtrl                                       ( m_RCEnableRateControl );
  m_cEncLib.setTargetBitrate                                     ( m_RCTargetBitrate );
  m_cEncLib.setKeepHierBit                                       ( m_RCKeepHierarchicalBit );
  m_cEncLib.setLCULevelRC                                        ( m_RCLCULevelRC );
  m_cEncLib.setUseLCUSeparateModel                               ( m_RCUseLCUSeparateModel );
  m_cEncLib.setInitialQP                                         ( m_RCInitialQP );
  m_cEncLib.setForceIntraQP                                      ( m_RCForceIntraQP );
#if U0132_TARGET_BITS_SATURATION
  m_cEncLib.setCpbSaturationEnabled                              ( m_RCCpbSaturationEnabled );
  m_cEncLib.setCpbSize                                           ( m_RCCpbSize );
  m_cEncLib.setInitialCpbFullness                                ( m_RCInitialCpbFullness );
#endif
  m_cEncLib.setCostMode                                          ( m_costMode );
  m_cEncLib.setUseRecalculateQPAccordingToLambda                 ( m_recalculateQPAccordingToLambda );
  m_cEncLib.setDecodingParameterSetEnabled                       ( m_decodingParameterSetEnabled );
#if HEVC_SEI
  m_cEncLib.setActiveParameterSetsSEIEnabled                     ( m_activeParameterSetsSEIEnabled );
#endif
  m_cEncLib.setVuiParametersPresentFlag                          ( m_vuiParametersPresentFlag );
  m_cEncLib.setAspectRatioInfoPresentFlag                        ( m_aspectRatioInfoPresentFlag);
  m_cEncLib.setAspectRatioIdc                                    ( m_aspectRatioIdc );
  m_cEncLib.setSarWidth                                          ( m_sarWidth );
  m_cEncLib.setSarHeight                                         ( m_sarHeight );
  m_cEncLib.setColourDescriptionPresentFlag                      ( m_colourDescriptionPresentFlag );
  m_cEncLib.setColourPrimaries                                   ( m_colourPrimaries );
  m_cEncLib.setTransferCharacteristics                           ( m_transferCharacteristics );
  m_cEncLib.setMatrixCoefficients                                ( m_matrixCoefficients );
  m_cEncLib.setChromaLocInfoPresentFlag                          ( m_chromaLocInfoPresentFlag );
  m_cEncLib.setChromaSampleLocTypeTopField                       ( m_chromaSampleLocTypeTopField );
  m_cEncLib.setChromaSampleLocTypeBottomField                    ( m_chromaSampleLocTypeBottomField );
  m_cEncLib.setChromaSampleLocType                               ( m_chromaSampleLocType );
  m_cEncLib.setOverscanInfoPresentFlag                           ( m_overscanInfoPresentFlag );
  m_cEncLib.setOverscanAppropriateFlag                           ( m_overscanAppropriateFlag );
  m_cEncLib.setVideoFullRangeFlag                                ( m_videoFullRangeFlag );
  m_cEncLib.setEfficientFieldIRAPEnabled                         ( m_bEfficientFieldIRAPEnabled );
  m_cEncLib.setHarmonizeGopFirstFieldCoupleEnabled               ( m_bHarmonizeGopFirstFieldCoupleEnabled );
  m_cEncLib.setSummaryOutFilename                                ( m_summaryOutFilename );
  m_cEncLib.setSummaryPicFilenameBase                            ( m_summaryPicFilenameBase );
  m_cEncLib.setSummaryVerboseness                                ( m_summaryVerboseness );
  m_cEncLib.setIMV                                               ( m_ImvMode );
  m_cEncLib.setIMV4PelFast                                       ( m_Imv4PelFast );
  m_cEncLib.setDecodeBitstream                                   ( 0, m_decodeBitstreams[0] );
  m_cEncLib.setDecodeBitstream                                   ( 1, m_decodeBitstreams[1] );
  m_cEncLib.setSwitchPOC                                         ( m_switchPOC );
  m_cEncLib.setSwitchDQP                                         ( m_switchDQP );
  m_cEncLib.setFastForwardToPOC                                  ( m_fastForwardToPOC );
  m_cEncLib.setForceDecodeBitstream1                             ( m_forceDecodeBitstream1 );
  m_cEncLib.setStopAfterFFtoPOC                                  ( m_stopAfterFFtoPOC );
  m_cEncLib.setBs2ModPOCAndType                                  ( m_bs2ModPOCAndType );
  m_cEncLib.setDebugCTU                                          ( m_debugCTU );
#if ENABLE_SPLIT_PARALLELISM
  m_cEncLib.setNumSplitThreads                                   ( m_numSplitThreads );
  m_cEncLib.setForceSingleSplitThread                            ( m_forceSplitSequential );
#endif
  m_cEncLib.setUseALF                                            ( m_alf );
#if JVET_Q0795_CCALF
  m_cEncLib.setUseCCALF                                          ( m_ccalf );
  m_cEncLib.setCCALFQpThreshold                                  ( m_ccalfQpThreshold );
#endif
  m_cEncLib.setLmcs                                              ( m_lmcsEnabled );
  m_cEncLib.setReshapeSignalType                                 ( m_reshapeSignalType );
  m_cEncLib.setReshapeIntraCMD                                   ( m_intraCMD );
  m_cEncLib.setReshapeCW                                         ( m_reshapeCW );
  m_cEncLib.setReshapeCSoffset                                   ( m_CSoffset );

#if JVET_O0756_CALCULATE_HDRMETRICS
  for (int i=0; i<hdrtoolslib::NB_REF_WHITE; i++)
  {
    m_cEncLib.setWhitePointDeltaE                                (i, m_whitePointDeltaE[i] );
  }
  m_cEncLib.setMaxSampleValue                                    (m_maxSampleValue);
  m_cEncLib.setSampleRange                                       (m_sampleRange);
  m_cEncLib.setColorPrimaries                                    (m_colorPrimaries);
  m_cEncLib.setEnableTFunctionLUT                                (m_enableTFunctionLUT);
  for (int i=0; i<2; i++)
  {
    m_cEncLib.setChromaLocation                                    (i, m_chromaLocation);
    m_cEncLib.setChromaUPFilter                                    (m_chromaUPFilter);
  }
  m_cEncLib.setCropOffsetLeft                                    (m_cropOffsetLeft);
  m_cEncLib.setCropOffsetTop                                     (m_cropOffsetTop);
  m_cEncLib.setCropOffsetRight                                   (m_cropOffsetRight);
  m_cEncLib.setCropOffsetBottom                                  (m_cropOffsetBottom);
  m_cEncLib.setCalculateHdrMetrics                               (m_calculateHdrMetrics);
#endif
  m_cEncLib.setGopBasedTemporalFilterEnabled(m_gopBasedTemporalFilterEnabled);
  m_cEncLib.setNumRefLayers                                       ( m_numRefLayers );
}

void EncApp::xCreateLib( std::list<PelUnitBuf*>& recBufList, const int layerId )
{
  // Video I/O
  m_cVideoIOYuvInputFile.open( m_inputFileName,     false, m_inputBitDepth, m_MSBExtendedBitDepth, m_internalBitDepth );  // read  mode
#if EXTENSION_360_VIDEO
  m_cVideoIOYuvInputFile.skipFrames(m_FrameSkip, m_inputFileWidth, m_inputFileHeight, m_InputChromaFormatIDC);
#else
  const int sourceHeight = m_isField ? m_iSourceHeightOrg : m_iSourceHeight;
  m_cVideoIOYuvInputFile.skipFrames(m_FrameSkip, m_iSourceWidth - m_aiPad[0], sourceHeight - m_aiPad[1], m_InputChromaFormatIDC);
#endif
  if (!m_reconFileName.empty())
  {
    if (m_packedYUVMode && ((m_outputBitDepth[CH_L] != 10 && m_outputBitDepth[CH_L] != 12)
        || ((m_iSourceWidth & (1 + (m_outputBitDepth[CH_L] & 3))) != 0)))
    {
      EXIT ("Invalid output bit-depth or image width for packed YUV output, aborting\n");
    }
    if (m_packedYUVMode && (m_chromaFormatIDC != CHROMA_400) && ((m_outputBitDepth[CH_C] != 10 && m_outputBitDepth[CH_C] != 12)
        || (((m_iSourceWidth / SPS::getWinUnitX (m_chromaFormatIDC)) & (1 + (m_outputBitDepth[CH_C] & 3))) != 0)))
    {
      EXIT ("Invalid chroma output bit-depth or image width for packed YUV output, aborting\n");
    }

    std::string reconFileName = m_reconFileName;
    if( m_reconFileName.compare( "/dev/null" ) &&  (m_maxLayers > 1) )
    {
      size_t pos = reconFileName.find_last_of('.');
      if (pos != string::npos)
      {
        reconFileName.insert( pos, std::to_string( layerId ) );
      }
      else
      {
        reconFileName.append( std::to_string( layerId ) );
      }
    }
    m_cVideoIOYuvReconFile.open( reconFileName, true, m_outputBitDepth, m_outputBitDepth, m_internalBitDepth );  // write mode
  }

  // create the encoder
  m_cEncLib.create( layerId );

  // create the output buffer
  for( int i = 0; i < (m_iGOPSize + 1 + (m_isField ? 1 : 0)); i++ )
  {
    recBufList.push_back( new PelUnitBuf );
  }
}

void EncApp::xDestroyLib()
{
  // Video I/O
  m_cVideoIOYuvInputFile.close();
  m_cVideoIOYuvReconFile.close();

  // Neo Decoder
  m_cEncLib.destroy();
}

void EncApp::xInitLib(bool isFieldCoding)
{
  m_cEncLib.init(isFieldCoding, this );
}

// ====================================================================================================================
// Public member functions
// ====================================================================================================================

void EncApp::createLib( const int layerIdx )
{
  const int sourceHeight = m_isField ? m_iSourceHeightOrg : m_iSourceHeight;
  UnitArea unitArea( m_chromaFormatIDC, Area( 0, 0, m_iSourceWidth, sourceHeight ) );

  m_orgPic = new PelStorage;
  m_trueOrgPic = new PelStorage;
  m_orgPic->create( unitArea );
  m_trueOrgPic->create( unitArea );

  if( !m_bitstream.is_open() )
  {
    m_bitstream.open( m_bitstreamFileName.c_str(), fstream::binary | fstream::out );
    if( !m_bitstream )
    {
      EXIT( "Failed to open bitstream file " << m_bitstreamFileName.c_str() << " for writing\n" );
    }
  }

  // initialize internal class & member variables and VPS
  xInitLibCfg();
  const int layerId = m_cEncLib.getVPS() == nullptr ? 0 : m_cEncLib.getVPS()->getLayerId( layerIdx );
  xCreateLib( m_recBufList, layerId );
  xInitLib( m_isField );

  printChromaFormat();

#if EXTENSION_360_VIDEO
  m_ext360 = new TExt360AppEncTop( *this, m_cEncLib.getGOPEncoder()->getExt360Data(), *( m_cEncLib.getGOPEncoder() ), *m_orgPic );
#endif

  if( m_gopBasedTemporalFilterEnabled )
  {
    m_temporalFilter.init( m_FrameSkip, m_inputBitDepth, m_MSBExtendedBitDepth, m_internalBitDepth, m_iSourceWidth, m_iSourceHeight,
      m_aiPad, m_bClipInputVideoToRec709Range, m_inputFileName, m_chromaFormatIDC,
      m_inputColourSpaceConvert, m_iQP, m_gopBasedTemporalFilterStrengths,
      m_gopBasedTemporalFilterFutureReference );
  }
}

void EncApp::destroyLib()
{
  printf( "\nLayerId %2d", m_cEncLib.getLayerId() );

  m_cEncLib.printSummary( m_isField );

  // delete used buffers in encoder class
  m_cEncLib.deletePicBuffer();

  for( auto &p : m_recBufList )
  {
    delete p;
  }
  m_recBufList.clear();

  xDestroyLib();

  if( m_bitstream.is_open() )
  {
    m_bitstream.close();
  }

  m_orgPic->destroy();
  m_trueOrgPic->destroy();
  delete m_trueOrgPic;
  delete m_orgPic;
#if EXTENSION_360_VIDEO
  delete m_ext360;
#endif

  printRateSummary();
}

bool EncApp::encodePrep( bool& eos )
{
  // main encoder loop
  const InputColourSpaceConversion ipCSC = m_inputColourSpaceConvert;
  const InputColourSpaceConversion snrCSC = ( !m_snrInternalColourSpace ) ? m_inputColourSpaceConvert : IPCOLOURSPACE_UNCHANGED;

  // read input YUV file
#if EXTENSION_360_VIDEO
  if( m_ext360->isEnabled() )
  {
    m_ext360->read( m_cVideoIOYuvInputFile, *m_orgPic, *m_trueOrgPic, ipCSC );
  }
  else
  {
    m_cVideoIOYuvInputFile.read( *m_orgPic, *m_trueOrgPic, ipCSC, m_aiPad, m_InputChromaFormatIDC, m_bClipInputVideoToRec709Range );
  }
#else
  m_cVideoIOYuvInputFile.read( *m_orgPic, *m_trueOrgPic, ipCSC, m_aiPad, m_InputChromaFormatIDC, m_bClipInputVideoToRec709Range );
#endif

  if( m_gopBasedTemporalFilterEnabled )
  {
    m_temporalFilter.filter( m_orgPic, m_iFrameRcvd );
  }

  // increase number of received frames
  m_iFrameRcvd++;

  eos = ( m_isField && ( m_iFrameRcvd == ( m_framesToBeEncoded >> 1 ) ) ) || ( !m_isField && ( m_iFrameRcvd == m_framesToBeEncoded ) );

  // if end of file (which is only detected on a read failure) flush the encoder of any queued pictures
  if( m_cVideoIOYuvInputFile.isEof() )
  {
    m_flush = true;
    eos = true;
    m_iFrameRcvd--;
    m_cEncLib.setFramesToBeEncoded( m_iFrameRcvd );
  }

  bool keepDoing = false;

  // call encoding function for one frame
  if( m_isField )
  {
    keepDoing = m_cEncLib.encodePrep( eos, m_flush ? 0 : m_orgPic, m_flush ? 0 : m_trueOrgPic, snrCSC, m_recBufList, m_numEncoded, m_isTopFieldFirst );
  }
  else
  {
    keepDoing = m_cEncLib.encodePrep( eos, m_flush ? 0 : m_orgPic, m_flush ? 0 : m_trueOrgPic, snrCSC, m_recBufList, m_numEncoded );
  }

  return keepDoing;
}

bool EncApp::encode()
{
  const InputColourSpaceConversion snrCSC = ( !m_snrInternalColourSpace ) ? m_inputColourSpaceConvert : IPCOLOURSPACE_UNCHANGED;
  bool keepDoing = false;

  // call encoding function for one frame
  if( m_isField )
  {
    keepDoing = m_cEncLib.encode( snrCSC, m_recBufList, m_numEncoded, m_isTopFieldFirst );
  }
  else
  {
    keepDoing = m_cEncLib.encode( snrCSC, m_recBufList, m_numEncoded );
  }

#if JVET_O0756_CALCULATE_HDRMETRICS
    m_metricTime = m_cEncLib.getMetricTime();
#endif

  // output when the entire GOP was proccessed
  if( !keepDoing )
  {
    // write bistream to file if necessary
    if( m_numEncoded > 0 )
    {
      xWriteOutput( m_numEncoded, m_recBufList );
    }
    // temporally skip frames
    if( m_temporalSubsampleRatio > 1 )
    {
#if EXTENSION_360_VIDEO
      m_cVideoIOYuvInputFile.skipFrames( m_temporalSubsampleRatio - 1, m_inputFileWidth, m_inputFileHeight, m_InputChromaFormatIDC );
#else
    const int sourceHeight = m_isField ? m_iSourceHeightOrg : m_iSourceHeight;
    m_cVideoIOYuvInputFile.skipFrames( m_temporalSubsampleRatio - 1, m_iSourceWidth - m_aiPad[0], sourceHeight - m_aiPad[1], m_InputChromaFormatIDC );
#endif
    }
  }

  return keepDoing;
}

// ====================================================================================================================
// Protected member functions
// ====================================================================================================================

/**
  Write access units to output file.
  \param bitstreamFile  target bitstream file
  \param iNumEncoded    number of encoded frames
  \param accessUnits    list of access units to be written
 */
void EncApp::xWriteOutput( int iNumEncoded, std::list<PelUnitBuf*>& recBufList )
{
  const InputColourSpaceConversion ipCSC = (!m_outputInternalColourSpace) ? m_inputColourSpaceConvert : IPCOLOURSPACE_UNCHANGED;
  std::list<PelUnitBuf*>::iterator iterPicYuvRec = recBufList.end();
  int i;

  for ( i = 0; i < iNumEncoded; i++ )
  {
    --iterPicYuvRec;
  }

  if (m_isField)
  {
    //Reinterlace fields
    for ( i = 0; i < iNumEncoded/2; i++ )
    {
      const PelUnitBuf*  pcPicYuvRecTop     = *(iterPicYuvRec++);
      const PelUnitBuf*  pcPicYuvRecBottom  = *(iterPicYuvRec++);

      if (!m_reconFileName.empty())
      {
        m_cVideoIOYuvReconFile.write( *pcPicYuvRecTop, *pcPicYuvRecBottom,
                                      ipCSC,
                                      false, // TODO: m_packedYUVMode,
                                      m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, NUM_CHROMA_FORMAT, m_isTopFieldFirst );
      }
    }
  }
  else
  {
    for ( i = 0; i < iNumEncoded; i++ )
    {
      const PelUnitBuf* pcPicYuvRec = *(iterPicYuvRec++);
      if (!m_reconFileName.empty())
      {
        if( m_cEncLib.isRPREnabled() && m_cEncLib.getUpscaledOutput() )
        {
          const SPS& sps = *m_cEncLib.getSPS( 0 );
          const PPS& pps = *m_cEncLib.getPPS( ( sps.getMaxPicWidthInLumaSamples() != pcPicYuvRec->get( COMPONENT_Y ).width || sps.getMaxPicHeightInLumaSamples() != pcPicYuvRec->get( COMPONENT_Y ).height ) ? ENC_PPS_ID_RPR : 0 );

          m_cVideoIOYuvReconFile.writeUpscaledPicture( sps, pps, *pcPicYuvRec, ipCSC, m_packedYUVMode, m_cEncLib.getUpscaledOutput(), NUM_CHROMA_FORMAT, m_bClipOutputVideoToRec709Range );
        }
        else
        {
          m_cVideoIOYuvReconFile.write( pcPicYuvRec->get( COMPONENT_Y ).width, pcPicYuvRec->get( COMPONENT_Y ).height, *pcPicYuvRec, ipCSC, m_packedYUVMode,
            m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, NUM_CHROMA_FORMAT, m_bClipOutputVideoToRec709Range );
        }
      }
    }
  }
}


void EncApp::outputAU( const AccessUnit& au )
{
  const vector<uint32_t>& stats = writeAnnexB(m_bitstream, au);
  rateStatsAccum(au, stats);
  m_bitstream.flush();
}


/**
 *
 */
void EncApp::rateStatsAccum(const AccessUnit& au, const std::vector<uint32_t>& annexBsizes)
{
  AccessUnit::const_iterator it_au = au.begin();
  vector<uint32_t>::const_iterator it_stats = annexBsizes.begin();

  for (; it_au != au.end(); it_au++, it_stats++)
  {
    switch ((*it_au)->m_nalUnitType)
    {
    case NAL_UNIT_CODED_SLICE_TRAIL:
    case NAL_UNIT_CODED_SLICE_STSA:
    case NAL_UNIT_CODED_SLICE_IDR_W_RADL:
    case NAL_UNIT_CODED_SLICE_IDR_N_LP:
    case NAL_UNIT_CODED_SLICE_CRA:
    case NAL_UNIT_CODED_SLICE_GDR:
    case NAL_UNIT_CODED_SLICE_RADL:
    case NAL_UNIT_CODED_SLICE_RASL:
    case NAL_UNIT_DPS:
    case NAL_UNIT_VPS:
    case NAL_UNIT_SPS:
    case NAL_UNIT_PPS:
    case NAL_UNIT_PH:
    case NAL_UNIT_PREFIX_APS:
    case NAL_UNIT_SUFFIX_APS:
      m_essentialBytes += *it_stats;
      break;
    default:
      break;
    }

    m_totalBytes += *it_stats;
  }
}

void EncApp::printRateSummary()
{
  double time = (double) m_iFrameRcvd / m_iFrameRate * m_temporalSubsampleRatio;
  msg( DETAILS,"Bytes written to file: %u (%.3f kbps)\n", m_totalBytes, 0.008 * m_totalBytes / time );
  if (m_summaryVerboseness > 0)
  {
    msg(DETAILS, "Bytes for SPS/PPS/APS/Slice (Incl. Annex B): %u (%.3f kbps)\n", m_essentialBytes, 0.008 * m_essentialBytes / time);
  }
}

void EncApp::printChromaFormat()
{
  if( g_verbosity >= DETAILS )
  {
    std::cout << std::setw(43) << "Input ChromaFormatIDC = ";
    switch (m_InputChromaFormatIDC)
    {
    case CHROMA_400:  std::cout << "  4:0:0"; break;
    case CHROMA_420:  std::cout << "  4:2:0"; break;
    case CHROMA_422:  std::cout << "  4:2:2"; break;
    case CHROMA_444:  std::cout << "  4:4:4"; break;
    default:
      THROW( "invalid chroma fomat");
    }
    std::cout << std::endl;

    std::cout << std::setw(43) << "Output (internal) ChromaFormatIDC = ";
    switch (m_cEncLib.getChromaFormatIdc())
    {
    case CHROMA_400:  std::cout << "  4:0:0"; break;
    case CHROMA_420:  std::cout << "  4:2:0"; break;
    case CHROMA_422:  std::cout << "  4:2:2"; break;
    case CHROMA_444:  std::cout << "  4:4:4"; break;
    default:
      THROW( "invalid chroma fomat");
    }
    std::cout << "\n" << std::endl;
  }
}

//! \}
