Skip to content
Snippets Groups Projects
EncModeCtrl.cpp 63.4 KiB
Newer Older
  • Learn to ignore specific revisions
  • /* 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-2019, ITU/ISO/IEC
    
    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
     * 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     EncModeCtrl.cpp
        \brief    Encoder controller for trying out specific modes
    */
    
    #include "EncModeCtrl.h"
    
    #include "AQp.h"
    #include "RateCtrl.h"
    
    #include "CommonLib/RdCost.h"
    #include "CommonLib/CodingStructure.h"
    #include "CommonLib/Picture.h"
    #include "CommonLib/UnitTools.h"
    
    #include "CommonLib/dtrace_next.h"
    
    #include <cmath>
    
    void EncModeCtrl::init( EncCfg *pCfg, RateCtrl *pRateCtrl, RdCost* pRdCost )
    {
      m_pcEncCfg      = pCfg;
      m_pcRateCtrl    = pRateCtrl;
      m_pcRdCost      = pRdCost;
      m_fastDeltaQP   = false;
    #if SHARP_LUMA_DELTA_QP
      m_lumaQPOffset  = 0;
    
      initLumaDeltaQpLUT();
    #endif
    }
    
    bool EncModeCtrl::tryModeMaster( const EncTestMode& encTestmode, const CodingStructure &cs, Partitioner& partitioner )
    {
    #if ENABLE_SPLIT_PARALLELISM
      if( m_ComprCUCtxList.back().isLevelSplitParallel )
      {
        if( !parallelJobSelector( encTestmode, cs, partitioner ) )
        {
          return false;
        }
      }
    #endif
      return tryMode( encTestmode, cs, partitioner );
    }
    
    void EncModeCtrl::setEarlySkipDetected()
    {
      m_ComprCUCtxList.back().earlySkip = true;
    }
    
    void EncModeCtrl::xExtractFeatures( const EncTestMode encTestmode, CodingStructure& cs )
    {
      CHECK( cs.features.size() < NUM_ENC_FEATURES, "Features vector is not initialized" );
    
      cs.features[ENC_FT_DISTORTION     ] = double( cs.dist              );
      cs.features[ENC_FT_FRAC_BITS      ] = double( cs.fracBits          );
      cs.features[ENC_FT_RD_COST        ] = double( cs.cost              );
      cs.features[ENC_FT_ENC_MODE_TYPE  ] = double( encTestmode.type     );
      cs.features[ENC_FT_ENC_MODE_OPTS  ] = double( encTestmode.opts     );
    }
    
    bool EncModeCtrl::nextMode( const CodingStructure &cs, Partitioner &partitioner )
    {
      m_ComprCUCtxList.back().lastTestMode = m_ComprCUCtxList.back().testModes.back();
    
      m_ComprCUCtxList.back().testModes.pop_back();
    
      while( !m_ComprCUCtxList.back().testModes.empty() && !tryModeMaster( currTestMode(), cs, partitioner ) )
      {
        m_ComprCUCtxList.back().testModes.pop_back();
      }
    
      return !m_ComprCUCtxList.back().testModes.empty();
    }
    
    EncTestMode EncModeCtrl::currTestMode() const
    {
      return m_ComprCUCtxList.back().testModes.back();
    }
    
    EncTestMode EncModeCtrl::lastTestMode() const
    {
      return m_ComprCUCtxList.back().lastTestMode;
    }
    
    bool EncModeCtrl::anyMode() const
    {
      return !m_ComprCUCtxList.back().testModes.empty();
    }
    
    void EncModeCtrl::setBest( CodingStructure& cs )
    {
      if( cs.cost != MAX_DOUBLE && !cs.cus.empty() )
      {
        m_ComprCUCtxList.back().bestCS = &cs;
        m_ComprCUCtxList.back().bestCU = cs.cus[0];
        m_ComprCUCtxList.back().bestTU = cs.cus[0]->firstTU;
        m_ComprCUCtxList.back().lastTestMode = getCSEncMode( cs );
      }
    }
    
    void EncModeCtrl::xGetMinMaxQP( int& minQP, int& maxQP, const CodingStructure& cs, const Partitioner &partitioner, const int baseQP, const SPS& sps, const PPS& pps, const bool splitMode )
    {
      if( m_pcEncCfg->getUseRateCtrl() )
      {
        minQP = m_pcRateCtrl->getRCQP();
        maxQP = m_pcRateCtrl->getRCQP();
        return;
      }
    
      const uint32_t currDepth = partitioner.currDepth;
    
      if( !splitMode )
      {
        if( currDepth <= pps.getMaxCuDQPDepth() )
        {
          int deltaQP = m_pcEncCfg->getMaxDeltaQP();
          minQP = Clip3( -sps.getQpBDOffset( CHANNEL_TYPE_LUMA ), MAX_QP, baseQP - deltaQP );
          maxQP = Clip3( -sps.getQpBDOffset( CHANNEL_TYPE_LUMA ), MAX_QP, baseQP + deltaQP );
        }
        else
        {
          minQP = cs.currQP[partitioner.chType];
          maxQP = cs.currQP[partitioner.chType];
        }
    
    #if SHARP_LUMA_DELTA_QP
        if( m_pcEncCfg->getLumaLevelToDeltaQPMapping().isEnabled() )
        {
          minQP = Clip3( -sps.getQpBDOffset( CHANNEL_TYPE_LUMA ), MAX_QP, baseQP - m_lumaQPOffset );
          maxQP = minQP; // force encode choose the modified QO
        }
    #endif
      }
      else
      {
        if( currDepth == pps.getMaxCuDQPDepth() )
        {
          int deltaQP = m_pcEncCfg->getMaxDeltaQP();
          minQP = Clip3( -sps.getQpBDOffset( CHANNEL_TYPE_LUMA ), MAX_QP, baseQP - deltaQP );
          maxQP = Clip3( -sps.getQpBDOffset( CHANNEL_TYPE_LUMA ), MAX_QP, baseQP + deltaQP );
        }
        else if( currDepth < pps.getMaxCuDQPDepth() )
        {
          minQP = baseQP;
          maxQP = baseQP;
        }
        else
        {
          minQP = cs.currQP[partitioner.chType];
          maxQP = cs.currQP[partitioner.chType];
        }
    
    #if SHARP_LUMA_DELTA_QP
        if( m_pcEncCfg->getLumaLevelToDeltaQPMapping().isEnabled() )
        {
          minQP = Clip3( -sps.getQpBDOffset( CHANNEL_TYPE_LUMA ), MAX_QP, baseQP - m_lumaQPOffset );
          maxQP = minQP;
        }
    #endif
      }
    }
    
    
    int EncModeCtrl::xComputeDQP( const CodingStructure &cs, const Partitioner &partitioner )
    {
      Picture* picture    = cs.picture;
      unsigned uiAQDepth  = std::min( partitioner.currDepth, ( uint32_t ) picture->aqlayer.size() - 1 );
      AQpLayer* pcAQLayer = picture->aqlayer[uiAQDepth];
    
      double dMaxQScale   = pow( 2.0, m_pcEncCfg->getQPAdaptationRange() / 6.0 );
      double dAvgAct      = pcAQLayer->getAvgActivity();
      double dCUAct       = pcAQLayer->getActivity( cs.area.Y().topLeft() );
      double dNormAct     = ( dMaxQScale*dCUAct + dAvgAct ) / ( dCUAct + dMaxQScale*dAvgAct );
      double dQpOffset    = log( dNormAct ) / log( 2.0 ) * 6.0;
      int    iQpOffset    = int( floor( dQpOffset + 0.49999 ) );
      return iQpOffset;
    }
    
    
    #if SHARP_LUMA_DELTA_QP
    void EncModeCtrl::initLumaDeltaQpLUT()
    {
      const LumaLevelToDeltaQPMapping &mapping = m_pcEncCfg->getLumaLevelToDeltaQPMapping();
    
      if( !mapping.isEnabled() )
      {
        return;
      }
    
      // map the sparse LumaLevelToDeltaQPMapping.mapping to a fully populated linear table.
    
      int         lastDeltaQPValue = 0;
      std::size_t nextSparseIndex = 0;
      for( int index = 0; index < LUMA_LEVEL_TO_DQP_LUT_MAXSIZE; index++ )
      {
        while( nextSparseIndex < mapping.mapping.size() && index >= mapping.mapping[nextSparseIndex].first )
        {
          lastDeltaQPValue = mapping.mapping[nextSparseIndex].second;
          nextSparseIndex++;
        }
        m_lumaLevelToDeltaQPLUT[index] = lastDeltaQPValue;
      }
    }
    
    int EncModeCtrl::calculateLumaDQP( const CPelBuf& rcOrg )
    {
      double avg = 0;
    
      // Get QP offset derived from Luma level
    #if !WCG_EXT
      if( m_pcEncCfg->getLumaLevelToDeltaQPMapping().mode == LUMALVL_TO_DQP_AVG_METHOD )
    #else
      CHECK( m_pcEncCfg->getLumaLevelToDeltaQPMapping().mode != LUMALVL_TO_DQP_AVG_METHOD, "invalid delta qp mode" );
    #endif
      {
        // Use avg method
        int sum = 0;
        for( uint32_t y = 0; y < rcOrg.height; y++ )
        {
          for( uint32_t x = 0; x < rcOrg.width; x++ )
          {
            sum += rcOrg.at( x, y );
          }
        }
        avg = ( double ) sum / rcOrg.area();
      }
    #if !WCG_EXT
      else
      {
        // Use maximum luma value
        int maxVal = 0;
        for( uint32_t y = 0; y < rcOrg.height; y++ )
        {
          for( uint32_t x = 0; x < rcOrg.width; x++ )
          {
            const Pel& v = rcOrg.at( x, y );
            if( v > maxVal )
            {
              maxVal = v;
            }
          }
        }
        // use a percentage of the maxVal
        avg = ( double ) maxVal * m_pcEncCfg->getLumaLevelToDeltaQPMapping().maxMethodWeight;
      }
    #endif
      int lumaIdx = Clip3<int>( 0, int( LUMA_LEVEL_TO_DQP_LUT_MAXSIZE ) - 1, int( avg + 0.5 ) );
      int QP = m_lumaLevelToDeltaQPLUT[lumaIdx];
      return QP;
    }
    #endif
    
    #if ENABLE_SPLIT_PARALLELISM
    void EncModeCtrl::copyState( const EncModeCtrl& other, const UnitArea& area )
    {
      m_slice          = other.m_slice;
      m_fastDeltaQP    = other.m_fastDeltaQP;
      m_lumaQPOffset   = other.m_lumaQPOffset;
      m_runNextInParallel
                       = other.m_runNextInParallel;
      m_ComprCUCtxList = other.m_ComprCUCtxList;
    }
    
    #endif
    void CacheBlkInfoCtrl::create()
    {
      const unsigned numPos = MAX_CU_SIZE >> MIN_CU_LOG2;
    
      m_numWidths  = gp_sizeIdxInfo->numWidths();
      m_numHeights = gp_sizeIdxInfo->numHeights();
    
      for( unsigned x = 0; x < numPos; x++ )
      {
        for( unsigned y = 0; y < numPos; y++ )
        {
          m_codedCUInfo[x][y] = new CodedCUInfo**[m_numWidths];
    
          for( int wIdx = 0; wIdx < gp_sizeIdxInfo->numWidths(); wIdx++ )
          {
            if( gp_sizeIdxInfo->isCuSize( gp_sizeIdxInfo->sizeFrom( wIdx ) ) && x + ( gp_sizeIdxInfo->sizeFrom( wIdx ) >> MIN_CU_LOG2 ) <= ( MAX_CU_SIZE >> MIN_CU_LOG2 ) )
            {
              m_codedCUInfo[x][y][wIdx] = new CodedCUInfo*[gp_sizeIdxInfo->numHeights()];
    
              for( int hIdx = 0; hIdx < gp_sizeIdxInfo->numHeights(); hIdx++ )
              {
                if( gp_sizeIdxInfo->isCuSize( gp_sizeIdxInfo->sizeFrom( hIdx ) ) && y + ( gp_sizeIdxInfo->sizeFrom( hIdx ) >> MIN_CU_LOG2 ) <= ( MAX_CU_SIZE >> MIN_CU_LOG2 ) )
                {
                  m_codedCUInfo[x][y][wIdx][hIdx] = new CodedCUInfo;
                }
                else
                {
                  m_codedCUInfo[x][y][wIdx][hIdx] = nullptr;
                }
              }
            }
            else
            {
              m_codedCUInfo[x][y][wIdx] = nullptr;
            }
          }
        }
      }
    }
    
    void CacheBlkInfoCtrl::destroy()
    {
      const unsigned numPos = MAX_CU_SIZE >> MIN_CU_LOG2;
    
      for( unsigned x = 0; x < numPos; x++ )
      {
        for( unsigned y = 0; y < numPos; y++ )
        {
          for( int wIdx = 0; wIdx < gp_sizeIdxInfo->numWidths(); wIdx++ )
          {
            if( m_codedCUInfo[x][y][wIdx] )
            {
              for( int hIdx = 0; hIdx < gp_sizeIdxInfo->numHeights(); hIdx++ )
              {
                if( m_codedCUInfo[x][y][wIdx][hIdx] )
                {
                  delete m_codedCUInfo[x][y][wIdx][hIdx];
                }
              }
    
              delete[] m_codedCUInfo[x][y][wIdx];
            }
          }
    
          delete[] m_codedCUInfo[x][y];
        }
      }
    }
    
    void CacheBlkInfoCtrl::init( const Slice &slice )
    {
      const unsigned numPos = MAX_CU_SIZE >> MIN_CU_LOG2;
    
      for( unsigned x = 0; x < numPos; x++ )
      {
        for( unsigned y = 0; y < numPos; y++ )
        {
          for( int wIdx = 0; wIdx < gp_sizeIdxInfo->numWidths(); wIdx++ )
          {
            if( m_codedCUInfo[x][y][wIdx] )
            {
              for( int hIdx = 0; hIdx < gp_sizeIdxInfo->numHeights(); hIdx++ )
              {
                if( m_codedCUInfo[x][y][wIdx][hIdx] )
                {
                  memset( m_codedCUInfo[x][y][wIdx][hIdx], 0, sizeof( CodedCUInfo ) );
                }
              }
            }
          }
        }
      }
    
      m_slice_chblk = &slice;
    #if ENABLE_SPLIT_PARALLELISM
    
      m_currTemporalId = 0;
    #endif
    }
    #if ENABLE_SPLIT_PARALLELISM
    
    void CacheBlkInfoCtrl::touch( const UnitArea& area )
    {
      CodedCUInfo& cuInfo = getBlkInfo( area );
      cuInfo.temporalId = m_currTemporalId;
    }
    
    void CacheBlkInfoCtrl::copyState( const CacheBlkInfoCtrl &other, const UnitArea& area )
    {
      m_slice_chblk = other.m_slice_chblk;
    
      m_currTemporalId = other.m_currTemporalId;
    
      if( m_slice_chblk->isIntra() ) return;
    
      const int cuSizeMask = m_slice_chblk->getSPS()->getMaxCUWidth() - 1;
    
      const int minPosX = ( area.lx() & cuSizeMask ) >> MIN_CU_LOG2;
      const int minPosY = ( area.ly() & cuSizeMask ) >> MIN_CU_LOG2;
      const int maxPosX = ( area.Y().bottomRight().x & cuSizeMask ) >> MIN_CU_LOG2;
      const int maxPosY = ( area.Y().bottomRight().y & cuSizeMask ) >> MIN_CU_LOG2;
    
      for( unsigned x = minPosX; x <= maxPosX; x++ )
      {
        for( unsigned y = minPosY; y <= maxPosY; y++ )
        {
          for( int wIdx = 0; wIdx < gp_sizeIdxInfo->numWidths(); wIdx++ )
          {
            const int width = gp_sizeIdxInfo->sizeFrom( wIdx );
    
            if( m_codedCUInfo[x][y][wIdx] && width <= area.lwidth() && x + ( width >> MIN_CU_LOG2 ) <= ( maxPosX + 1 ) )
            {
              for( int hIdx = 0; hIdx < gp_sizeIdxInfo->numHeights(); hIdx++ )
              {
                const int height = gp_sizeIdxInfo->sizeFrom( hIdx );
    
                if( gp_sizeIdxInfo->isCuSize( height ) && height <= area.lheight() && y + ( height >> MIN_CU_LOG2 ) <= ( maxPosY + 1 ) )
                {
                  if( other.m_codedCUInfo[x][y][wIdx][hIdx]->temporalId > m_codedCUInfo[x][y][wIdx][hIdx]->temporalId )
                  {
                    *m_codedCUInfo[x][y][wIdx][hIdx] = *other.m_codedCUInfo[x][y][wIdx][hIdx];
                    m_codedCUInfo[x][y][wIdx][hIdx]->temporalId = m_currTemporalId;
                  }
                }
                else if( y + ( height >> MIN_CU_LOG2 ) > maxPosY + 1 )
                {
                  break;;
                }
              }
            }
            else if( x + ( width >> MIN_CU_LOG2 ) > maxPosX + 1 )
            {
              break;
            }
          }
        }
      }
    }
    #endif
    
    CodedCUInfo& CacheBlkInfoCtrl::getBlkInfo( const UnitArea& area )
    {
      unsigned idx1, idx2, idx3, idx4;
      getAreaIdx( area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4 );
    
      return *m_codedCUInfo[idx1][idx2][idx3][idx4];
    }
    
    bool CacheBlkInfoCtrl::isSkip( const UnitArea& area )
    {
      unsigned idx1, idx2, idx3, idx4;
      getAreaIdx( area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4 );
    
      return m_codedCUInfo[idx1][idx2][idx3][idx4]->isSkip;
    }
    
    
    bool CacheBlkInfoCtrl::isMMVDSkip(const UnitArea& area)
    {
      unsigned idx1, idx2, idx3, idx4;
      getAreaIdx(area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4);
    
      return m_codedCUInfo[idx1][idx2][idx3][idx4]->isMMVDSkip;
    }
    
    
    void CacheBlkInfoCtrl::setMv( const UnitArea& area, const RefPicList refPicList, const int iRefIdx, const Mv& rMv )
    {
      if( iRefIdx >= MAX_STORED_CU_INFO_REFS ) return;
    
      unsigned idx1, idx2, idx3, idx4;
      getAreaIdx( area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4 );
    
      m_codedCUInfo[idx1][idx2][idx3][idx4]->saveMv [refPicList][iRefIdx] = rMv;
      m_codedCUInfo[idx1][idx2][idx3][idx4]->validMv[refPicList][iRefIdx] = true;
    #if ENABLE_SPLIT_PARALLELISM
    
      touch( area );
    #endif
    }
    
    bool CacheBlkInfoCtrl::getMv( const UnitArea& area, const RefPicList refPicList, const int iRefIdx, Mv& rMv ) const
    {
      unsigned idx1, idx2, idx3, idx4;
      getAreaIdx( area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4 );
    
      if( iRefIdx >= MAX_STORED_CU_INFO_REFS )
      {
        rMv = m_codedCUInfo[idx1][idx2][idx3][idx4]->saveMv[refPicList][0];
        return false;
      }
    
      rMv = m_codedCUInfo[idx1][idx2][idx3][idx4]->saveMv[refPicList][iRefIdx];
      return m_codedCUInfo[idx1][idx2][idx3][idx4]->validMv[refPicList][iRefIdx];
    }
    
    
    #if JVET_M0140_SBT
    void SaveLoadEncInfoSbt::init( const Slice &slice )
    {
      m_sliceSbt = &slice;
    }
    
    void SaveLoadEncInfoSbt::create()
    {
      int numSizeIdx = gp_sizeIdxInfo->idxFrom( SBT_MAX_SIZE ) - MIN_CU_LOG2 + 1;
      int numPosIdx = MAX_CU_SIZE >> MIN_CU_LOG2;
    
      m_saveLoadSbt = new SaveLoadStructSbt***[numPosIdx];
    
      for( int xIdx = 0; xIdx < numPosIdx; xIdx++ )
      {
        m_saveLoadSbt[xIdx] = new SaveLoadStructSbt**[numPosIdx];
        for( int yIdx = 0; yIdx < numPosIdx; yIdx++ )
        {
          m_saveLoadSbt[xIdx][yIdx] = new SaveLoadStructSbt*[numSizeIdx];
          for( int wIdx = 0; wIdx < numSizeIdx; wIdx++ )
          {
            m_saveLoadSbt[xIdx][yIdx][wIdx] = new SaveLoadStructSbt[numSizeIdx];
          }
        }
      }
    }
    
    void SaveLoadEncInfoSbt::destroy()
    {
      int numSizeIdx = gp_sizeIdxInfo->idxFrom( SBT_MAX_SIZE ) - MIN_CU_LOG2 + 1;
      int numPosIdx = MAX_CU_SIZE >> MIN_CU_LOG2;
    
      for( int xIdx = 0; xIdx < numPosIdx; xIdx++ )
      {
        for( int yIdx = 0; yIdx < numPosIdx; yIdx++ )
        {
          for( int wIdx = 0; wIdx < numSizeIdx; wIdx++ )
          {
            delete[] m_saveLoadSbt[xIdx][yIdx][wIdx];
          }
          delete[] m_saveLoadSbt[xIdx][yIdx];
        }
        delete[] m_saveLoadSbt[xIdx];
      }
      delete[] m_saveLoadSbt;
    }
    
    uint16_t SaveLoadEncInfoSbt::findBestSbt( const UnitArea& area, const uint32_t curPuSse )
    {
      unsigned idx1, idx2, idx3, idx4;
      getAreaIdx( area.Y(), *m_sliceSbt->getPPS()->pcv, idx1, idx2, idx3, idx4 );
      SaveLoadStructSbt* pSbtSave = &m_saveLoadSbt[idx1][idx2][idx3 - MIN_CU_LOG2][idx4 - MIN_CU_LOG2];
    
      for( int i = 0; i < pSbtSave->numPuInfoStored; i++ )
      {
        if( curPuSse == pSbtSave->puSse[i] )
        {
          return pSbtSave->puSbt[i] + ( pSbtSave->puTrs[i] << 8 );
        }
      }
    
      return MAX_UCHAR + ( MAX_UCHAR << 8 );
    }
    
    bool SaveLoadEncInfoSbt::saveBestSbt( const UnitArea& area, const uint32_t curPuSse, const uint8_t curPuSbt, const uint8_t curPuTrs )
    {
      unsigned idx1, idx2, idx3, idx4;
      getAreaIdx( area.Y(), *m_sliceSbt->getPPS()->pcv, idx1, idx2, idx3, idx4 );
      SaveLoadStructSbt* pSbtSave = &m_saveLoadSbt[idx1][idx2][idx3 - MIN_CU_LOG2][idx4 - MIN_CU_LOG2];
    
      if( pSbtSave->numPuInfoStored == SBT_NUM_SL )
      {
        return false;
      }
    
      pSbtSave->puSse[pSbtSave->numPuInfoStored] = curPuSse;
      pSbtSave->puSbt[pSbtSave->numPuInfoStored] = curPuSbt;
      pSbtSave->puTrs[pSbtSave->numPuInfoStored] = curPuTrs;
      pSbtSave->numPuInfoStored++;
      return true;
    }
    
    void SaveLoadEncInfoSbt::resetSaveloadSbt( int maxSbtSize )
    {
      int numSizeIdx = gp_sizeIdxInfo->idxFrom( maxSbtSize ) - MIN_CU_LOG2 + 1;
      int numPosIdx = MAX_CU_SIZE >> MIN_CU_LOG2;
    
      for( int xIdx = 0; xIdx < numPosIdx; xIdx++ )
      {
        for( int yIdx = 0; yIdx < numPosIdx; yIdx++ )
        {
          for( int wIdx = 0; wIdx < numSizeIdx; wIdx++ )
          {
            memset( m_saveLoadSbt[xIdx][yIdx][wIdx], 0, numSizeIdx * sizeof( SaveLoadStructSbt ) );
          }
        }
      }
    }
    #endif
    
    
    bool CacheBlkInfoCtrl::getInter(const UnitArea& area)
    {
      unsigned idx1, idx2, idx3, idx4;
      getAreaIdx(area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4);
    
      return m_codedCUInfo[idx1][idx2][idx3][idx4]->isInter;
    }
    void CacheBlkInfoCtrl::setGbiIdx(const UnitArea& area, uint8_t gBiIdx)
    {
      unsigned idx1, idx2, idx3, idx4;
      getAreaIdx(area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4);
    
      m_codedCUInfo[idx1][idx2][idx3][idx4]->GBiIdx = gBiIdx;
    }
    uint8_t CacheBlkInfoCtrl::getGbiIdx(const UnitArea& area)
    {
      unsigned idx1, idx2, idx3, idx4;
      getAreaIdx(area.Y(), *m_slice_chblk->getPPS()->pcv, idx1, idx2, idx3, idx4);
    
      return m_codedCUInfo[idx1][idx2][idx3][idx4]->GBiIdx;
    }
    
    static bool isTheSameNbHood( const CodingUnit &cu, const CodingStructure& cs, const Partitioner &partitioner
    #if JVET_M0170_MRG_SHARELIST
                                , const PredictionUnit &pu, int picW, int picH
    #endif
                               )
    
    {
      if( cu.chType != partitioner.chType )
      {
        return false;
      }
    
      const PartitioningStack &ps = partitioner.getPartStack();
    
      int i = 1;
    
      for( ; i < ps.size(); i++ )
      {
        if( ps[i].split != CU::getSplitAtDepth( cu, i - 1 ) )
        {
          break;
        }
      }
    
      const UnitArea &cmnAnc = ps[i - 1].parts[ps[i - 1].idx];
    
      const UnitArea cuArea  = CS::getArea( cs, cu, partitioner.chType );
    
    #if JVET_M0170_MRG_SHARELIST
      bool sharedListReuseMode = true;
      if(
          pu.mergeFlag == true &&
    
          cu.affine == false &&
    
          cu.predMode == MODE_INTER
        )
      {
        sharedListReuseMode = false;
    
        if ((cu.lumaSize().width*cu.lumaSize().height) >= MRG_SHARELIST_SHARSIZE)
        {
          sharedListReuseMode = true;
        }
    
        if (((cmnAnc.lumaSize().width)*(cmnAnc.lumaSize().height) <= MRG_SHARELIST_SHARSIZE))
        {
          sharedListReuseMode = true;
        }
      }
      else
      {
        sharedListReuseMode = true;
      }
    //#endif
    #endif
    
        if( i < cuArea.blocks.size() && cuArea.blocks[i].valid() && cuArea.blocks[i].pos() != cmnAnc.blocks[i].pos() )
    
    #if JVET_M0170_MRG_SHARELIST
      if(!sharedListReuseMode)
      {
        return false;
      }
    #endif
    
    
    
      return true;
    }
    
    void BestEncInfoCache::create( const ChromaFormat chFmt )
    {
      const unsigned numPos = MAX_CU_SIZE >> MIN_CU_LOG2;
    
      m_numWidths  = gp_sizeIdxInfo->numWidths();
      m_numHeights = gp_sizeIdxInfo->numHeights();
    
      for( unsigned x = 0; x < numPos; x++ )
      {
        for( unsigned y = 0; y < numPos; y++ )
        {
          m_bestEncInfo[x][y] = new BestEncodingInfo**[m_numWidths];
    
          for( int wIdx = 0; wIdx < gp_sizeIdxInfo->numWidths(); wIdx++ )
          {
            if( gp_sizeIdxInfo->isCuSize( gp_sizeIdxInfo->sizeFrom( wIdx ) ) && x + ( gp_sizeIdxInfo->sizeFrom( wIdx ) >> MIN_CU_LOG2 ) <= ( MAX_CU_SIZE >> MIN_CU_LOG2 ) )
            {
              m_bestEncInfo[x][y][wIdx] = new BestEncodingInfo*[gp_sizeIdxInfo->numHeights()];
    
              for( int hIdx = 0; hIdx < gp_sizeIdxInfo->numHeights(); hIdx++ )
              {
                if( gp_sizeIdxInfo->isCuSize( gp_sizeIdxInfo->sizeFrom( hIdx ) ) && y + ( gp_sizeIdxInfo->sizeFrom( hIdx ) >> MIN_CU_LOG2 ) <= ( MAX_CU_SIZE >> MIN_CU_LOG2 ) )
                {
                  m_bestEncInfo[x][y][wIdx][hIdx] = new BestEncodingInfo;
    
                  int w = gp_sizeIdxInfo->sizeFrom( wIdx );
                  int h = gp_sizeIdxInfo->sizeFrom( hIdx );
    
                  const UnitArea area( chFmt, Area( 0, 0, w, h ) );
    
    
                  new ( &m_bestEncInfo[x][y][wIdx][hIdx]->cu ) CodingUnit    ( area );
                  new ( &m_bestEncInfo[x][y][wIdx][hIdx]->pu ) PredictionUnit( area );
    
    #if REUSE_CU_RESULTS_WITH_MULTIPLE_TUS
                  m_bestEncInfo[x][y][wIdx][hIdx]->numTus = 0;
                  for( int i = 0; i < MAX_NUM_TUS; i++ )
                  {
    
                    new ( &m_bestEncInfo[x][y][wIdx][hIdx]->tus[i] ) TransformUnit( area );
    
                  new ( &m_bestEncInfo[x][y][wIdx][hIdx]->tu ) TransformUnit( area );
    
    
                  m_bestEncInfo[x][y][wIdx][hIdx]->poc      = -1;
                  m_bestEncInfo[x][y][wIdx][hIdx]->testMode = EncTestMode();
                }
                else
                {
                  m_bestEncInfo[x][y][wIdx][hIdx] = nullptr;
                }
              }
            }
            else
            {
              m_bestEncInfo[x][y][wIdx] = nullptr;
            }
          }
        }
      }
    }
    
    void BestEncInfoCache::destroy()
    {
      const unsigned numPos = MAX_CU_SIZE >> MIN_CU_LOG2;
    
      for( unsigned x = 0; x < numPos; x++ )
      {
        for( unsigned y = 0; y < numPos; y++ )
        {
          for( int wIdx = 0; wIdx < gp_sizeIdxInfo->numWidths(); wIdx++ )
          {
            if( m_bestEncInfo[x][y][wIdx] )
            {
              for( int hIdx = 0; hIdx < gp_sizeIdxInfo->numHeights(); hIdx++ )
              {
                if( m_bestEncInfo[x][y][wIdx][hIdx] )
                {
                  delete m_bestEncInfo[x][y][wIdx][hIdx];
                }
              }
    
              delete[] m_bestEncInfo[x][y][wIdx];
            }
          }
    
          delete[] m_bestEncInfo[x][y];
        }
      }
    
      delete[] m_pCoeff;
      delete[] m_pPcmBuf;
    }
    
    void BestEncInfoCache::init( const Slice &slice )
    {
      bool isInitialized = m_slice_bencinf;
    
      m_slice_bencinf = &slice;
    
      if( isInitialized ) return;
    
      const unsigned numPos = MAX_CU_SIZE >> MIN_CU_LOG2;
    
      m_numWidths  = gp_sizeIdxInfo->numWidths();
      m_numHeights = gp_sizeIdxInfo->numHeights();
    
      size_t numCoeff = 0;
    
      for( unsigned x = 0; x < numPos; x++ )
      {
        for( unsigned y = 0; y < numPos; y++ )
        {
          for( int wIdx = 0; wIdx < gp_sizeIdxInfo->numWidths(); wIdx++ )
          {
            if( m_bestEncInfo[x][y][wIdx] ) for( int hIdx = 0; hIdx < gp_sizeIdxInfo->numHeights(); hIdx++ )
            {
              if( m_bestEncInfo[x][y][wIdx][hIdx] )
              {
                for( const CompArea& blk : m_bestEncInfo[x][y][wIdx][hIdx]->cu.blocks )
                {
                  numCoeff += blk.area();
                }
              }
            }
          }
        }
      }
    
    
    #if REUSE_CU_RESULTS_WITH_MULTIPLE_TUS
      m_pCoeff  = new TCoeff[numCoeff*MAX_NUM_TUS];
      m_pPcmBuf = new Pel   [numCoeff*MAX_NUM_TUS];
    #else
    
      m_pCoeff  = new TCoeff[numCoeff];
      m_pPcmBuf = new Pel   [numCoeff];
    
    
      TCoeff *coeffPtr = m_pCoeff;
      Pel    *pcmPtr   = m_pPcmBuf;
    
      m_dummyCS.pcv = m_slice_bencinf->getPPS()->pcv;
    
      for( unsigned x = 0; x < numPos; x++ )
      {
        for( unsigned y = 0; y < numPos; y++ )
        {
          for( int wIdx = 0; wIdx < gp_sizeIdxInfo->numWidths(); wIdx++ )
          {
            if( m_bestEncInfo[x][y][wIdx] ) for( int hIdx = 0; hIdx < gp_sizeIdxInfo->numHeights(); hIdx++ )
            {
              if( m_bestEncInfo[x][y][wIdx][hIdx] )
              {
                TCoeff *coeff[MAX_NUM_TBLOCKS] = { 0, };
                Pel    *pcmbf[MAX_NUM_TBLOCKS] = { 0, };
    
    
    #if REUSE_CU_RESULTS_WITH_MULTIPLE_TUS
                for( int i = 0; i < MAX_NUM_TUS; i++ )
                {
                  TransformUnit &tu = m_bestEncInfo[x][y][wIdx][hIdx]->tus[i];
                  const UnitArea &area = tu;
    
                  for( int i = 0; i < area.blocks.size(); i++ )
                  {
                    coeff[i] = coeffPtr; coeffPtr += area.blocks[i].area();
                    pcmbf[i] = pcmPtr;   pcmPtr += area.blocks[i].area();
                  }
    
                  tu.cs = &m_dummyCS;
                  tu.init(coeff, pcmbf);
                }
    #else
    
                const UnitArea &area = m_bestEncInfo[x][y][wIdx][hIdx]->tu;
    
                for( int i = 0; i < area.blocks.size(); i++ )
                {
                  coeff[i] = coeffPtr; coeffPtr += area.blocks[i].area();
                  pcmbf[i] =   pcmPtr;   pcmPtr += area.blocks[i].area();
                }
    
                m_bestEncInfo[x][y][wIdx][hIdx]->tu.cs = &m_dummyCS;
                m_bestEncInfo[x][y][wIdx][hIdx]->tu.init( coeff, pcmbf );
    
              }
            }
          }
        }
      }
    }
    
    bool BestEncInfoCache::setFromCs( const CodingStructure& cs, const Partitioner& partitioner )
    {
    
    #if REUSE_CU_RESULTS_WITH_MULTIPLE_TUS
      if( cs.cus.size() != 1 || cs.pus.size() != 1 )
    #else
    
      if( cs.cus.size() != 1 || cs.tus.size() != 1 || cs.pus.size() != 1 )
    
      {
        return false;
      }
    
      unsigned idx1, idx2, idx3, idx4;
      getAreaIdx( cs.area.Y(), *m_slice_bencinf->getPPS()->pcv, idx1, idx2, idx3, idx4 );
    
      BestEncodingInfo& encInfo = *m_bestEncInfo[idx1][idx2][idx3][idx4];
    
      encInfo.poc            =  cs.picture->poc;
      encInfo.cu.repositionTo( *cs.cus.front() );
      encInfo.pu.repositionTo( *cs.pus.front() );
    
    #if !REUSE_CU_RESULTS_WITH_MULTIPLE_TUS
    
      encInfo.tu.repositionTo( *cs.tus.front() );
    
      encInfo.cu             = *cs.cus.front();
      encInfo.pu             = *cs.pus.front();
    
    #if REUSE_CU_RESULTS_WITH_MULTIPLE_TUS
      int tuIdx = 0;
      for( auto tu : cs.tus )
      {
        encInfo.tus[tuIdx].repositionTo( *tu );
        encInfo.tus[tuIdx].resizeTo( *tu );
        for( auto &blk : tu->blocks )
        {
          if( blk.valid() )
            encInfo.tus[tuIdx].copyComponentFrom( *tu, blk.compID );
        }
        tuIdx++;
      }
      CHECKD( cs.tus.size() > MAX_NUM_TUS, "Exceeding tus array boundaries" );
      encInfo.numTus = cs.tus.size();
    #else
    
      for( auto &blk : cs.tus.front()->blocks )
      {
        if( blk.valid() ) encInfo.tu.copyComponentFrom( *cs.tus.front(), blk.compID );
      }
    
    bool BestEncInfoCache::isValid( const CodingStructure& cs, const Partitioner& partitioner, int qp )
    
    {
      unsigned idx1, idx2, idx3, idx4;
      getAreaIdx( cs.area.Y(), *m_slice_bencinf->getPPS()->pcv, idx1, idx2, idx3, idx4 );
    
      BestEncodingInfo& encInfo = *m_bestEncInfo[idx1][idx2][idx3][idx4];
    
    
      if( encInfo.cu.qp != qp )
        return false;
    
      if( cs.picture->poc != encInfo.poc || CS::getArea( cs, cs.area, partitioner.chType ) != CS::getArea( cs, encInfo.cu, partitioner.chType ) || !isTheSameNbHood( encInfo.cu, cs, partitioner
    #if JVET_M0170_MRG_SHARELIST
        , encInfo.pu, (cs.picture->Y().width), (cs.picture->Y().height)
    #endif
    
    Yu Han's avatar
    Yu Han committed
    #if JVET_M0483_IBC
    
    Yu Han's avatar
    Yu Han committed
        || CU::isIBC(encInfo.cu)
    #else
    
    Yu Han's avatar
    Yu Han committed
        || encInfo.cu.ibc
    
    Yu Han's avatar
    Yu Han committed
    #endif
    
      {
        return false;
      }
      else
      {
        return true;
      }
    }
    
    bool BestEncInfoCache::setCsFrom( CodingStructure& cs, EncTestMode& testMode, const Partitioner& partitioner ) const
    {
      unsigned idx1, idx2, idx3, idx4;
      getAreaIdx( cs.area.Y(), *m_slice_bencinf->getPPS()->pcv, idx1, idx2, idx3, idx4 );
    
      BestEncodingInfo& encInfo = *m_bestEncInfo[idx1][idx2][idx3][idx4];
    
    
      if( cs.picture->poc != encInfo.poc || CS::getArea( cs, cs.area, partitioner.chType ) != CS::getArea( cs, encInfo.cu, partitioner.chType ) || !isTheSameNbHood( encInfo.cu, cs, partitioner
    
    #if JVET_M0170_MRG_SHARELIST
        , encInfo.pu, (cs.picture->Y().width), (cs.picture->Y().height)
    #endif
    ) )
    
      {
        return false;
      }
    
      CodingUnit     &cu = cs.addCU( CS::getArea( cs, cs.area, partitioner.chType ), partitioner.chType );
      PredictionUnit &pu = cs.addPU( CS::getArea( cs, cs.area, partitioner.chType ), partitioner.chType );
    
    #if !REUSE_CU_RESULTS_WITH_MULTIPLE_TUS
    
      TransformUnit  &tu = cs.addTU( CS::getArea( cs, cs.area, partitioner.chType ), partitioner.chType );
    
    
      cu          .repositionTo( encInfo.cu );
      pu          .repositionTo( encInfo.pu );
    
    #if !REUSE_CU_RESULTS_WITH_MULTIPLE_TUS