EncCu.h 15.9 KB
Newer Older
Alberto Gonzalez's avatar
Alberto Gonzalez committed
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
/* 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-2023, 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     EncCu.h
    \brief    Coding Unit (CU) encoder class (header)
*/

#ifndef __ENCCU__
#define __ENCCU__

// Include files
#include "CommonLib/CommonDef.h"
#include "CommonLib/IntraPrediction.h"
#include "CommonLib/InterPrediction.h"
#include "CommonLib/TrQuant.h"
#include "CommonLib/Unit.h"
#include "CommonLib/UnitPartitioner.h"
#include "CommonLib/IbcHashMap.h"
#include "CommonLib/DeblockingFilter.h"

#include "DecoderLib/DecCu.h"

#include "CABACWriter.h"
#include "IntraSearch.h"
#include "InterSearch.h"
#include "RateCtrl.h"
#include "EncModeCtrl.h"
//! \ingroup EncoderLib
//! \{

class EncLib;
class HLSWriter;
class EncSlice;

// ====================================================================================================================
// Class definition
// ====================================================================================================================

/// CU encoder class
struct GeoMergeCombo
{
  int splitDir;
  MergeIdxPair mergeIdx;
  double cost;
  GeoMergeCombo() : splitDir(0), mergeIdx{ 0, 0 }, cost(0.0){};
  GeoMergeCombo(int _splitDir, const MergeIdxPair &idx, double _cost)
    : splitDir(_splitDir), mergeIdx(idx), cost(_cost){};
};

class GeoComboCostList
{
public:
  GeoComboCostList() {};
  ~GeoComboCostList() {};
  std::vector<GeoMergeCombo> list;

  void sortByCost()
  {
    std::stable_sort(list.begin(), list.end(),
                     [](const GeoMergeCombo &a, const GeoMergeCombo &b) { return a.cost < b.cost; });
  };
};

class FastGeoCostList
{
  int m_maxNumGeoCand{ 0 };

  using CostArray = double[GEO_NUM_PARTITION_MODE][2];

  CostArray *m_singleDistList{ nullptr };

public:
  FastGeoCostList() {}
  ~FastGeoCostList()
  {
    delete[] m_singleDistList;
    m_singleDistList = nullptr;
  }

  void init(int maxNumGeoCand)
  {
    if (m_maxNumGeoCand != maxNumGeoCand)
    {
      delete[] m_singleDistList;
      m_singleDistList = nullptr;

      CHECK(maxNumGeoCand > MRG_MAX_NUM_CANDS, "Too many candidates");
      m_singleDistList = new CostArray[maxNumGeoCand];
      m_maxNumGeoCand  = maxNumGeoCand;
    }
  }

  void insert(int geoIdx, int partIdx, int mergeIdx, double cost)
  {
    CHECKD(geoIdx >= GEO_NUM_PARTITION_MODE, "geoIdx is too large");
    CHECKD(mergeIdx >= m_maxNumGeoCand, "mergeIdx is too large");
    CHECKD(partIdx >= 2, "partIdx is too large");

    m_singleDistList[mergeIdx][geoIdx][partIdx] = cost;
  }

  double getCost(const int splitDir, const MergeIdxPair &mergeCand)
  {
    return m_singleDistList[mergeCand[0]][splitDir][0] + m_singleDistList[mergeCand[1]][splitDir][1];
  }
};

#if JVET_AC0139_UNIFIED_MERGE
class MergeItem
{
private:
  PelStorage m_pelStorage;
  std::vector<MotionInfo> m_mvStorage;

public:
  enum class MergeItemType
  {
    REGULAR,
    SBTMVP,
    AFFINE,
    MMVD,
    CIIP,
    GPM,
    IBC,
    NUM,
  };

  double        cost;
  std::array<MvField[2], AFFINE_MAX_NUM_CP> mvField;
  int           mergeIdx;
  uint8_t       bcwIdx;
  uint8_t       interDir;
  bool          useAltHpelIf;
  AffineModel   affineType;

  bool          noResidual;
  bool          noBdofRefine;

  bool          lumaPredReady;
  bool          chromaPredReady;

  MergeItemType mergeItemType;
  MotionBuf     mvBuf;

#if GDR_ENABLED
  bool          mvSolid[2];
  bool          mvValid[2];
#endif

  MergeItem();
  ~MergeItem();

  void          create(ChromaFormat chromaFormat, const Area& area);
  void          importMergeInfo(const MergeCtx& mergeCtx, int _mergeIdx, MergeItemType _mergeItemType, PredictionUnit& pu);
  void          importMergeInfo(const AffineMergeCtx& mergeCtx, int _mergeIdx, MergeItemType _mergeItemType, const UnitArea& unitArea);
  bool          exportMergeInfo(PredictionUnit& pu, bool forceNoResidual);
  PelUnitBuf    getPredBuf(const UnitArea& unitArea) { return m_pelStorage.getBuf(unitArea); }
  MotionBuf     getMvBuf(const UnitArea& unitArea) { return MotionBuf(m_mvStorage.data(), g_miScaling.scale(unitArea.lumaSize())); }

  static int getGpmUnfiedIndex(int splitDir, const MergeIdxPair& geoMergeIdx)
  {
    return (splitDir << 8) | (geoMergeIdx[0] << 4) | geoMergeIdx[1];
  }
  static void updateGpmIdx(int mergeIdx, uint8_t& splitDir, MergeIdxPair& geoMergeIdx)
  {
    splitDir = (mergeIdx >> 8) & 0xFF;
    geoMergeIdx[0] = (mergeIdx >> 4) & 0xF;
    geoMergeIdx[1] = mergeIdx & 0xF;
  }
};

class MergeItemList
{
private:
  Pool<MergeItem> m_mergeItemPool;
  std::vector<MergeItem *> m_list;
  size_t m_maxTrackingNum = 0;
  ChromaFormat  m_chromaFormat;
  Area m_ctuArea;

public:
  MergeItemList();
  ~MergeItemList();

  void          init(size_t maxSize, ChromaFormat chromaFormat, int ctuWidth, int ctuHeight);
  MergeItem*    allocateNewMergeItem();
  void          insertMergeItemToList(MergeItem* p);
  void          resetList(size_t maxTrackingNum);
  MergeItem*    getMergeItemInList(size_t index);
  size_t        size() { return m_list.size(); }

};
#endif

class EncCu
  : DecCu
{
public:
  bool m_bestModeUpdated; //copy checked
  struct CtxPair
  {
    Ctx start;
    Ctx best;
  };

Alberto Gonzalez's avatar
Alberto Gonzalez committed
236 237
  std::vector<CtxPair>  m_ctxBuffer; //copy 
  CtxPair*              m_CurrCtx; //copy 
Alberto Gonzalez's avatar
Alberto Gonzalez committed
238
  CtxPool*              m_ctxPool; //copy 
Alberto Gonzalez's avatar
Alberto Gonzalez committed
239 240

  //  Data : encoder control
Alberto Gonzalez's avatar
Alberto Gonzalez committed
241
  int                   m_cuChromaQpOffsetIdxPlus1; // if 0, then cu_chroma_qp_offset_flag will be 0, otherwise cu_chroma_qp_offset_flag will be 1.  copy checked
Alberto Gonzalez's avatar
Alberto Gonzalez committed
242

Alberto Gonzalez's avatar
Alberto Gonzalez committed
243 244
  XuPool m_unitPool; //copy 
  PelUnitBufPool m_pelUnitBufPool;//copy
Alberto Gonzalez's avatar
Alberto Gonzalez committed
245

Alberto Gonzalez's avatar
Alberto Gonzalez committed
246
  CodingStructure    ***m_pTempCS; //copy
Alberto Gonzalez's avatar
Alberto Gonzalez committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
  CodingStructure    ***m_pBestCS;
  CodingStructure    ***m_pTempCS2;
  CodingStructure    ***m_pBestCS2;
  //  Access channel
  EncCfg*               m_pcEncCfg;
  IntraSearch*          m_pcIntraSearch;
  InterSearch*          m_pcInterSearch;
  TrQuant*              m_pcTrQuant;
  RdCost*               m_pcRdCost;
  EncSlice*             m_pcSliceEncoder;
  DeblockingFilter*     m_deblockingFilter;

  CABACWriter*          m_CABACEstimator;
  RateCtrl*             m_pcRateCtrl;
  IbcHashMap            m_ibcHashMap;
Alberto Gonzalez's avatar
Alberto Gonzalez committed
262
  EncModeCtrl*          m_modeCtrl;
Alberto Gonzalez's avatar
Alberto Gonzalez committed
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
#if !JVET_AC0139_UNIFIED_MERGE
  std::array<PelStorage, GEO_MAX_TRY_WEIGHTED_SAD> m_geoWeightedBuffers;   // weighted prediction pixels
#endif

  FastGeoCostList       m_geoCostList;
  double                m_AFFBestSATDCost;
  double                m_mergeBestSATDCost;
  MotionInfo            m_SubPuMiBuf      [( MAX_CU_SIZE * MAX_CU_SIZE ) >> ( MIN_CU_LOG2 << 1 )];

  int                   m_ctuIbcSearchRangeX;
  int                   m_ctuIbcSearchRangeY;

  std::array<int, 2>    m_bestBcwIdx;
  std::array<double, 2> m_bestBcwCost;

  static const MergeIdxPair m_geoModeTest[GEO_MAX_NUM_CANDS];

#if SHARP_LUMA_DELTA_QP || ENABLE_QPA_SUB_CTU
  void    updateLambda      ( Slice* slice, const int dQP,
 #if WCG_EXT && ER_CHROMA_QP_WCG_PPS
                              const bool useWCGChromaControl,
 #endif
                              const bool updateRdCostLambda );
#endif
  double                m_sbtCostSave[2];

  GeoComboCostList m_comboList;
#if JVET_AC0139_UNIFIED_MERGE
  MergeItemList         m_mergeItemList;
#endif

public:
  //ALBERTO
  EncCu copy(EncCu& original);
  //END ALBERTO

  /// copy parameters from encoder class
  void  init                ( EncLib* pcEncLib, const SPS& sps );

  void setDecCuReshaperInEncCU(EncReshape* pcReshape, ChromaFormat chromaFormatIDC) { initDecCuReshaper((Reshape*) pcReshape, chromaFormatIDC); }
  /// create internal buffers
  void  create              ( EncCfg* encCfg );

  /// destroy internal buffers
  void  destroy             ();

  /// CTU analysis function
  void compressCtu(CodingStructure &cs, const UnitArea &area, const unsigned ctuRsAddr,
                   const EnumArray<int, ChannelType> &prevQP, const EnumArray<int, ChannelType> &currQP);
  /// CTU encoding function
  int   updateCtuDataISlice ( const CPelBuf buf );

  EncModeCtrl* getModeCtrl  () { return m_modeCtrl; }


  void   setMergeBestSATDCost(double cost) { m_mergeBestSATDCost = cost; }
  double getMergeBestSATDCost()            { return m_mergeBestSATDCost; }
  void   setAFFBestSATDCost(double cost)   { m_AFFBestSATDCost = cost; }
  double getAFFBestSATDCost()              { return m_AFFBestSATDCost; }
  IbcHashMap& getIbcHashMap()              { return m_ibcHashMap;        }
  EncCfg*     getEncCfg()            const { return m_pcEncCfg;          }

  EncCu();
  ~EncCu();

protected:

  void xCalDebCost            ( CodingStructure &cs, Partitioner &partitioner, bool calDist = false );
  Distortion getDistortionDb  ( CodingStructure &cs, CPelBuf org, CPelBuf reco, ComponentID compID, const CompArea& compArea, bool afterDb );

  void xCompressCU            ( CodingStructure*& tempCS, CodingStructure*& bestCS, Partitioner& pm, double maxCostAllowed = MAX_DOUBLE );

  bool
    xCheckBestMode         ( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &pm, const EncTestMode& encTestmode );

  void xCheckModeSplit        ( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &pm, const EncTestMode& encTestMode, const ModeType modeTypeParent, bool &skipInterPass, double *splitRdCostBest);

  bool xCheckRDCostIntra(CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &pm, const EncTestMode& encTestMode, bool adaptiveColorTrans);

  void xCheckDQP              ( CodingStructure& cs, Partitioner& partitioner, bool bKeepCtx = false);
  void xCheckChromaQPOffset   ( CodingStructure& cs, Partitioner& partitioner);

  void xCheckRDCostHashInter  ( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &pm, const EncTestMode& encTestMode );
#if !JVET_AC0139_UNIFIED_MERGE
  void xCheckRDCostAffineMerge2Nx2N
                              ( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode );
#endif
  void xCheckRDCostInter      ( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &pm, const EncTestMode& encTestMode );
  bool xCheckRDCostInterAmvr(CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &pm,
                             const EncTestMode &encTestMode, double &bestIntPelCost);
  void xEncodeDontSplit       ( CodingStructure &cs, Partitioner &partitioner);

#if !JVET_AC0139_UNIFIED_MERGE
  void xCheckRDCostMerge2Nx2N ( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &pm, const EncTestMode& encTestMode );
#endif

#if JVET_AC0139_UNIFIED_MERGE
  void xCheckRDCostUnifiedMerge ( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &pm, const EncTestMode& encTestMode );
#endif

#if !JVET_AC0139_UNIFIED_MERGE
  void xCheckRDCostMergeGeo2Nx2N(CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &pm, const EncTestMode& encTestMode);
#endif
  void xEncodeInterResidual(CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner,
                            const EncTestMode &encTestMode, int residualPass = 0, bool *bestHasNonResi = nullptr,
                            double *equBcwCost = nullptr);
#if REUSE_CU_RESULTS
  void xReuseCachedResult     ( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &Partitioner );
#endif
  bool xIsBcwSkip(const CodingUnit& cu)
  {
    if (cu.slice->getSliceType() != B_SLICE)
    {
      return true;
    }
    return((m_pcEncCfg->getBaseQP() > 32) && ((cu.slice->getTLayer() >= 4)
       || ((cu.refIdxBi[0] >= 0 && cu.refIdxBi[1] >= 0)
       && (abs(cu.slice->getPOC() - cu.slice->getRefPOC(REF_PIC_LIST_0, cu.refIdxBi[0])) == 1
       ||  abs(cu.slice->getPOC() - cu.slice->getRefPOC(REF_PIC_LIST_1, cu.refIdxBi[1])) == 1))));
  }
  void xCheckRDCostIBCMode    ( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &pm, const EncTestMode& encTestMode );
  void xCheckRDCostIBCModeMerge2Nx2N( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode );

  void xCheckPLT              ( CodingStructure *&tempCS, CodingStructure *&bestCS, Partitioner &partitioner, const EncTestMode& encTestMode );

  PredictionUnit* getPuForInterPrediction(CodingStructure* cs);
#if JVET_AC0139_UNIFIED_MERGE
  unsigned int updateRdCheckingNum(double threshold, unsigned int numMergeSatdCand);

  void generateMergePrediction(const UnitArea& unitArea, MergeItem* mergeItem, PredictionUnit& pu, bool luma, bool chroma,
    PelUnitBuf& dstBuf, bool finalRd, bool forceNoResidual, PelUnitBuf* predBuf1, PelUnitBuf* predBuf2);
  double calcLumaCost4MergePrediction(const TempCtx& ctxStart, const PelUnitBuf& predBuf, double lambda, PredictionUnit& pu, DistParam& distParam);

  template <size_t N>
  void addRegularCandsToPruningList(const MergeCtx& mergeCtx, const UnitArea& localUnitArea, double sqrtLambdaForFirstPassIntra,
    const TempCtx& ctxStart, int numDmvrMvd, Mv dmvrL0Mvd[MRG_MAX_NUM_CANDS][MAX_NUM_SUBCU_DMVR],
    PelUnitBufVector<N>& mrgPredBufNoCiip, PelUnitBufVector<N>& mrgPredBufNoMvRefine, DistParam& distParam, PredictionUnit* pu);
  template <size_t N>
  void addCiipCandsToPruningList(const MergeCtx& mergeCtx, const UnitArea& localUnitArea, double sqrtLambdaForFirstPassIntra,
    const TempCtx& ctxStart, PelUnitBufVector<N>& mrgPredBufNoCiip, PelUnitBufVector<N>& mrgPredBufNoMvRefine, DistParam& distParam, PredictionUnit* pu);
  void addMmvdCandsToPruningList(const MergeCtx& mergeCtx, const UnitArea& localUnitArea, double sqrtLambdaForFirstPassIntra,
    const TempCtx& ctxStart, DistParam& distParam, PredictionUnit* pu);
  void addAffineCandsToPruningList(AffineMergeCtx& affineMergeCtx, const UnitArea& localUnitArea, double sqrtLambdaForFirstPass,
    const TempCtx& ctxStart, DistParam& distParam, PredictionUnit* pu);
  template <size_t N>
  void addGpmCandsToPruningList(const MergeCtx& mergeCtx, const UnitArea& localUnitArea, double sqrtLambdaForFirstPass,
    const TempCtx& ctxStart, const GeoComboCostList& comboList, PelUnitBufVector<N>& geoBuffer, DistParam& distParamSAD2, PredictionUnit* pu);

  template<size_t N>
  bool prepareGpmComboList(const MergeCtx& mergeCtx, const UnitArea& localUnitArea, double sqrtLambdaForFirstPass,
    GeoComboCostList& comboList, PelUnitBufVector<N>& geoBuffer, PredictionUnit* pu);
#else
  template<size_t N>
  unsigned int updateRdCheckingNum(double threshold, unsigned int numMergeSatdCand, static_vector<double, N>& costList);
#endif
  void checkEarlySkip(const CodingStructure* bestCS, const Partitioner &partitioner);

};

//! \}

#endif // __ENCMB__