UnitTools.cpp 157 KB
Newer Older
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
/* The copyright in this software is being made available under the BSD
 * License, included below. This software may be subject to other third party
 * and contributor rights, including patent rights, and no such rights are
 * granted under this license.
 *
 * Copyright (c) 2010-2018, ITU/ISO/IEC
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
 *    be used to endorse or promote products derived from this software without
 *    specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

/** \file     UnitTool.cpp
 *  \brief    defines operations for basic units
 */

#include "UnitTools.h"

#include "dtrace_next.h"

#include "Unit.h"
#include "Slice.h"
#include "Picture.h"

#include <utility>
#include <algorithm>

// CS tools


uint64_t CS::getEstBits(const CodingStructure &cs)
{
  return cs.fracBits >> SCALE_BITS;
}



bool CS::isDualITree( const CodingStructure &cs )
{
61
  return cs.slice->isIRAP() && !cs.pcv->ISingleTree;
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
}

UnitArea CS::getArea( const CodingStructure &cs, const UnitArea &area, const ChannelType chType )
{
  return isDualITree( cs ) ? area.singleChan( chType ) : area;
}

// CU tools

bool CU::isIntra(const CodingUnit &cu)
{
  return cu.predMode == MODE_INTRA;
}

bool CU::isInter(const CodingUnit &cu)
{
  return cu.predMode == MODE_INTER;
}

bool CU::isRDPCMEnabled(const CodingUnit& cu)
{
  return cu.cs->sps->getSpsRangeExtension().getRdpcmEnabledFlag(cu.predMode == MODE_INTRA ? RDPCM_SIGNAL_IMPLICIT : RDPCM_SIGNAL_EXPLICIT);
}

bool CU::isLosslessCoded(const CodingUnit &cu)
{
  return cu.cs->pps->getTransquantBypassEnabledFlag() && cu.transQuantBypass;
}

bool CU::isSameSlice(const CodingUnit& cu, const CodingUnit& cu2)
{
  return cu.slice->getIndependentSliceIdx() == cu2.slice->getIndependentSliceIdx();
}

#if HEVC_TILES_WPP
bool CU::isSameTile(const CodingUnit& cu, const CodingUnit& cu2)
{
  return cu.tileIdx == cu2.tileIdx;
}

bool CU::isSameSliceAndTile(const CodingUnit& cu, const CodingUnit& cu2)
{
  return ( cu.slice->getIndependentSliceIdx() == cu2.slice->getIndependentSliceIdx() ) && ( cu.tileIdx == cu2.tileIdx );
}
#endif

bool CU::isSameCtu(const CodingUnit& cu, const CodingUnit& cu2)
{
  uint32_t ctuSizeBit = g_aucLog2[cu.cs->sps->getMaxCUWidth()];

  Position pos1Ctu(cu.lumaPos().x  >> ctuSizeBit, cu.lumaPos().y  >> ctuSizeBit);
  Position pos2Ctu(cu2.lumaPos().x >> ctuSizeBit, cu2.lumaPos().y >> ctuSizeBit);

  return pos1Ctu.x == pos2Ctu.x && pos1Ctu.y == pos2Ctu.y;
}

uint32_t CU::getIntraSizeIdx(const CodingUnit &cu)
{
  uint8_t uiWidth = cu.lumaSize().width;

  uint32_t  uiCnt   = 0;

  while (uiWidth)
  {
    uiCnt++;
    uiWidth >>= 1;
  }

  uiCnt -= 2;

  return uiCnt > 6 ? 6 : uiCnt;
}

bool CU::isLastSubCUOfCtu( const CodingUnit &cu )
{
  const SPS &sps      = *cu.cs->sps;
  const Area cuAreaY = CS::isDualITree( *cu.cs ) ? Area( recalcPosition( cu.chromaFormat, cu.chType, CHANNEL_TYPE_LUMA, cu.blocks[cu.chType].pos() ), recalcSize( cu.chromaFormat, cu.chType, CHANNEL_TYPE_LUMA, cu.blocks[cu.chType].size() ) ) : ( const Area& ) cu.Y();

  return ( ( ( ( cuAreaY.x + cuAreaY.width  ) & cu.cs->pcv->maxCUWidthMask  ) == 0 || cuAreaY.x + cuAreaY.width  == sps.getPicWidthInLumaSamples()  ) &&
           ( ( ( cuAreaY.y + cuAreaY.height ) & cu.cs->pcv->maxCUHeightMask ) == 0 || cuAreaY.y + cuAreaY.height == sps.getPicHeightInLumaSamples() ) );
}

uint32_t CU::getCtuAddr( const CodingUnit &cu )
{
  return getCtuAddr( cu.blocks[cu.chType].lumaPos(), *cu.cs->pcv );
}

int CU::predictQP( const CodingUnit& cu, const int prevQP )
{
  const CodingStructure &cs = *cu.cs;

#if ENABLE_WPP_PARALLELISM
  if( cs.sps->getSpsNext().getUseNextDQP() )
  {
    // Inter-CTU 2D "planar"   c(orner)  a(bove)
    // predictor arrangement:  b(efore)  p(rediction)

    // restrict the lookup, as it might cross CTU/slice/tile boundaries
    const CodingUnit *cuA = cs.getCURestricted( cu.blocks[cu.chType].pos().offset(  0, -1 ), cu, cu.chType );
    const CodingUnit *cuB = cs.getCURestricted( cu.blocks[cu.chType].pos().offset( -1,  0 ), cu, cu.chType );
    const CodingUnit *cuC = cs.getCURestricted( cu.blocks[cu.chType].pos().offset( -1, -1 ), cu, cu.chType );

    const int a = cuA ? cuA->qp : cs.slice->getSliceQpBase();
    const int b = cuB ? cuB->qp : cs.slice->getSliceQpBase();
    const int c = cuC ? cuC->qp : cs.slice->getSliceQpBase();

    return Clip3( ( a < b ? a : b ), ( a > b ? a : b ), a + b - c ); // derived from Martucci's Median Adaptive Prediction, 1990
  }

#endif
  // only predict within the same CTU, use HEVC's above+left prediction
  const int a = ( cu.blocks[cu.chType].y & ( cs.pcv->maxCUHeightMask >> getChannelTypeScaleY( cu.chType, cu.chromaFormat ) ) ) ? ( cs.getCU( cu.blocks[cu.chType].pos().offset( 0, -1 ), cu.chType ) )->qp : prevQP;
  const int b = ( cu.blocks[cu.chType].x & ( cs.pcv->maxCUWidthMask  >> getChannelTypeScaleX( cu.chType, cu.chromaFormat ) ) ) ? ( cs.getCU( cu.blocks[cu.chType].pos().offset( -1, 0 ), cu.chType ) )->qp : prevQP;

  return ( a + b + 1 ) >> 1;
}

179 180 181
#if JVET_L0362_QG_FIX
bool CU::isQGStart( const CodingUnit& cu, Partitioner& partitioner )
#else
182
bool CU::isQGStart( const CodingUnit& cu )
183
#endif
184
{
185 186 187 188 189 190 191 192 193 194 195 196 197 198
#if JVET_L0362_QG_FIX
  int maxDqpDepth = cu.slice->getPPS()->getMaxCuDQPDepth();
  if( partitioner.currDepth >= maxDqpDepth )
  {
    PartLevel splitAtMaxDepth = partitioner.getPartStack().at( maxDqpDepth ); 
    // the parent node of qtDepth + mttDepth == maxDqpDepth
    if( splitAtMaxDepth.parts[splitAtMaxDepth.idx].blocks[partitioner.chType].pos() == cu.blocks[partitioner.chType].pos() )
      return true;
    else
      return false;
  }
  else
    return true;
#else
199 200 201 202 203
  const SPS &sps = *cu.cs->sps;
  const PPS &pps = *cu.cs->pps;

  return ( cu.blocks[cu.chType].x % ( ( 1 << ( g_aucLog2[sps.getMaxCUWidth()]  - pps.getMaxCuDQPDepth() ) ) >> getChannelTypeScaleX( cu.chType, cu.chromaFormat ) ) ) == 0 &&
         ( cu.blocks[cu.chType].y % ( ( 1 << ( g_aucLog2[sps.getMaxCUHeight()] - pps.getMaxCuDQPDepth() ) ) >> getChannelTypeScaleY( cu.chType, cu.chromaFormat ) ) ) == 0;
204
#endif
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
}

uint32_t CU::getNumPUs( const CodingUnit& cu )
{
  uint32_t cnt = 0;
  PredictionUnit *pu = cu.firstPU;

  do
  {
    cnt++;
  } while( ( pu != cu.lastPU ) && ( pu = pu->next ) );

  return cnt;
}

void CU::addPUs( CodingUnit& cu )
{
  cu.cs->addPU( CS::getArea( *cu.cs, cu, cu.chType ), cu.chType );
}


PartSplit CU::getSplitAtDepth( const CodingUnit& cu, const unsigned depth )
{
  if( depth >= cu.depth ) return CU_DONT_SPLIT;

  const PartSplit cuSplitType = PartSplit( ( cu.splitSeries >> ( depth * SPLIT_DMULT ) ) & SPLIT_MASK );

  if     ( cuSplitType == CU_QUAD_SPLIT    ) return CU_QUAD_SPLIT;

  else if( cuSplitType == CU_HORZ_SPLIT    ) return CU_HORZ_SPLIT;

  else if( cuSplitType == CU_VERT_SPLIT    ) return CU_VERT_SPLIT;

  else if( cuSplitType == CU_TRIH_SPLIT    ) return CU_TRIH_SPLIT;
  else if( cuSplitType == CU_TRIV_SPLIT    ) return CU_TRIV_SPLIT;
  else   { THROW( "Unknown split mode"    ); return CU_QUAD_SPLIT; }
}

bool CU::hasNonTsCodedBlock( const CodingUnit& cu )
{
  bool hasAnyNonTSCoded = false;

  for( auto &currTU : traverseTUs( cu ) )
  {
    for( uint32_t i = 0; i < ::getNumberValidTBlocks( *cu.cs->pcv ); i++ )
    {
      hasAnyNonTSCoded |= ( currTU.blocks[i].valid() && !currTU.transformSkip[i] && TU::getCbf( currTU, ComponentID( i ) ) );
    }
  }

  return hasAnyNonTSCoded;
}

uint32_t CU::getNumNonZeroCoeffNonTs( const CodingUnit& cu )
{
  uint32_t count = 0;
  for( auto &currTU : traverseTUs( cu ) )
  {
    count += TU::getNumNonZeroCoeffsNonTS( currTU );
  }

  return count;
}




PUTraverser CU::traversePUs( CodingUnit& cu )
{
  return PUTraverser( cu.firstPU, cu.lastPU->next );
}

TUTraverser CU::traverseTUs( CodingUnit& cu )
{
  return TUTraverser( cu.firstTU, cu.lastTU->next );
}

cPUTraverser CU::traversePUs( const CodingUnit& cu )
{
  return cPUTraverser( cu.firstPU, cu.lastPU->next );
}

cTUTraverser CU::traverseTUs( const CodingUnit& cu )
{
  return cTUTraverser( cu.firstTU, cu.lastTU->next );
}

// PU tools

int PU::getIntraMPMs( const PredictionUnit &pu, unsigned* mpm, const ChannelType &channelType /*= CHANNEL_TYPE_LUMA*/ )
{
296
  const int numMPMs = NUM_MOST_PROBABLE_MODES;
297
  const int extendRefLine = (channelType == CHANNEL_TYPE_LUMA) ? pu.multiRefIdx : 0;
298 299
  {
    int numCand      = -1;
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    int leftIntraDir = PLANAR_IDX, aboveIntraDir = PLANAR_IDX;

    const CompArea &area = pu.block(getFirstComponentOfChannel(channelType));
    const Position posRT = area.topRight();
    const Position posLB = area.bottomLeft();

    // Get intra direction of left PU
    const PredictionUnit *puLeft = pu.cs->getPURestricted(posLB.offset(-1, 0), pu, channelType);
    if (puLeft && CU::isIntra(*puLeft->cu))
    {
      leftIntraDir = puLeft->intraDir[channelType];
    }

    // Get intra direction of above PU
    const PredictionUnit *puAbove = pu.cs->getPURestricted(posRT.offset(0, -1), pu, channelType);
    if (puAbove && CU::isIntra(*puAbove->cu) && CU::isSameCtu(*pu.cu, *puAbove->cu))
    {
      aboveIntraDir = puAbove->intraDir[channelType];
    }

    CHECK(2 >= numMPMs, "Invalid number of most probable modes");

322
    const int offset = (int)NUM_LUMA_MODE - 6;
323 324
    const int mod = offset + 3;

325
    if (extendRefLine)
326
    {
327 328 329
      int modeIdx = 0;
      int angularMode[2] = { 0, 0 };

330 331
      if (leftIntraDir > DC_IDX)
      {
332 333
        angularMode[modeIdx++] = leftIntraDir;
      }
334
      if (aboveIntraDir > DC_IDX && aboveIntraDir != leftIntraDir)
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
      {
        angularMode[modeIdx++] = aboveIntraDir;
      }
      if (modeIdx == 0)
      {
        mpm[0] = VER_IDX;
        mpm[1] = HOR_IDX;
        mpm[2] = 2;
        mpm[3] = DIA_IDX;
        mpm[4] = VDIA_IDX;
        mpm[5] = 26;
      }
      else if (modeIdx == 1)
      {
        mpm[0] = angularMode[0];
        mpm[1] = ((angularMode[0] + offset) % mod) + 2;
        mpm[2] = ((angularMode[0] - 1) % mod) + 2;
        mpm[3] = ((angularMode[0] + offset - 1) % mod) + 2;
        mpm[4] = (angularMode[0] % mod) + 2;
        mpm[5] = ((angularMode[0] + offset - 2) % mod) + 2;
      }
      else
      {
        mpm[0] = angularMode[0];
        mpm[1] = angularMode[1];
        int maxCandModeIdx = mpm[0] > mpm[1] ? 0 : 1;
        int minCandModeIdx = 1 - maxCandModeIdx;
        if (mpm[maxCandModeIdx] - mpm[minCandModeIdx] == 1)
        {
          mpm[2] = ((angularMode[minCandModeIdx] + offset) % mod) + 2;
          mpm[3] = ((angularMode[maxCandModeIdx] - 1) % mod) + 2;
          mpm[4] = ((angularMode[minCandModeIdx] + offset - 1) % mod) + 2;
          mpm[5] = ( angularMode[maxCandModeIdx] % mod) + 2;
        }
        else if (mpm[maxCandModeIdx] - mpm[minCandModeIdx] >= 62)
        {
          mpm[2] = ((angularMode[minCandModeIdx] - 1) % mod) + 2;
          mpm[3] = ((angularMode[maxCandModeIdx] + offset) % mod) + 2;
          mpm[4] = ((angularMode[minCandModeIdx]) % mod) + 2;
          mpm[5] = ((angularMode[maxCandModeIdx] + offset - 1) % mod) + 2;
        }
        else if (mpm[maxCandModeIdx] - mpm[minCandModeIdx] == 2)
        {
          mpm[2] = ((angularMode[minCandModeIdx] - 1) % mod) + 2;
          mpm[3] = ((angularMode[minCandModeIdx] + offset) % mod) + 2;
          mpm[4] = ((angularMode[maxCandModeIdx] - 1) % mod) + 2;
          mpm[5] = ((angularMode[minCandModeIdx] + offset - 1) % mod) + 2;
        }
        else
        {
          mpm[2] = ((angularMode[minCandModeIdx] + offset) % mod) + 2;
          mpm[3] = ((angularMode[minCandModeIdx] - 1) % mod) + 2;
          mpm[4] = ((angularMode[maxCandModeIdx] + offset) % mod) + 2;
          mpm[5] = ((angularMode[maxCandModeIdx] - 1) % mod) + 2;
        }
390 391
      }
    }
392
    else
393 394
    {
      mpm[0] = leftIntraDir;
395 396 397 398 399
      mpm[1] = (mpm[0] == PLANAR_IDX) ? DC_IDX : PLANAR_IDX;
      mpm[2] = VER_IDX;
      mpm[3] = HOR_IDX;
      mpm[4] = VER_IDX - 4;
      mpm[5] = VER_IDX + 4;
400

401
      if (leftIntraDir == aboveIntraDir)
402
      {
403 404
        numCand = 1;
        if (leftIntraDir > DC_IDX)
405
        {
406 407 408 409 410 411
          mpm[0] = leftIntraDir;
          mpm[1] = PLANAR_IDX;
          mpm[2] = DC_IDX;
          mpm[3] = ((leftIntraDir + offset) % mod) + 2;
          mpm[4] = ((leftIntraDir - 1) % mod) + 2;
          mpm[5] = ((leftIntraDir + offset - 1) % mod) + 2;
412 413
        }
      }
414
      else //L!=A
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
        numCand = 2;
        mpm[0] = leftIntraDir;
        mpm[1] = aboveIntraDir;
        bool maxCandModeIdx = mpm[0] > mpm[1] ? 0 : 1;

        if ((leftIntraDir > DC_IDX) && (aboveIntraDir > DC_IDX))
        {
          mpm[2] = PLANAR_IDX;
          mpm[3] = DC_IDX;
          if ((mpm[maxCandModeIdx] - mpm[!maxCandModeIdx] < 63) && (mpm[maxCandModeIdx] - mpm[!maxCandModeIdx] > 1))
          {
            mpm[4] = ((mpm[maxCandModeIdx] + offset) % mod) + 2;
            mpm[5] = ((mpm[maxCandModeIdx] - 1) % mod) + 2;
          }
          else
          {
            mpm[4] = ((mpm[maxCandModeIdx] + offset - 1) % mod) + 2;
            mpm[5] = ((mpm[maxCandModeIdx]) % mod) + 2;
          }
        }
        else if (leftIntraDir + aboveIntraDir >= 2)
        {
          mpm[2] = (mpm[!maxCandModeIdx] == PLANAR_IDX) ? DC_IDX : PLANAR_IDX;
          mpm[3] = ((mpm[maxCandModeIdx] + offset) % mod) + 2;
          mpm[4] = ((mpm[maxCandModeIdx] - 1) % mod) + 2;
          mpm[5] = ((mpm[maxCandModeIdx] + offset - 1) % mod) + 2;
        }
443 444
      }
    }
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
    for (int i = 0; i < numMPMs; i++)
    {
      CHECK(mpm[i] >= NUM_LUMA_MODE, "Invalid MPM");
    }
    CHECK(numCand == 0, "No candidates found");
    return numCand;
  }
}


void PU::getIntraChromaCandModes( const PredictionUnit &pu, unsigned modeList[NUM_CHROMA_MODE] )
{
  {
    modeList[  0 ] = PLANAR_IDX;
    modeList[  1 ] = VER_IDX;
    modeList[  2 ] = HOR_IDX;
    modeList[  3 ] = DC_IDX;
    modeList[4] = LM_CHROMA_IDX;
463 464 465
    modeList[5] = MDLM_L_IDX;
    modeList[6] = MDLM_T_IDX;
    modeList[7] = DM_CHROMA_IDX;
466

Li's avatar
Li committed
467
    Position topLeftPos = pu.blocks[pu.chType].lumaPos();
Li's avatar
Li committed
468
    Position refPos = topLeftPos.offset( pu.blocks[pu.chType].lumaSize().width >> 1, pu.blocks[pu.chType].lumaSize().height >> 1 );
Li's avatar
Li committed
469
    const PredictionUnit *lumaPU = CS::isDualITree( *pu.cs ) ? pu.cs->picture->cs->getPU( refPos, CHANNEL_TYPE_LUMA ) : &pu;
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    const uint32_t lumaMode = lumaPU->intraDir[CHANNEL_TYPE_LUMA];
    for( int i = 0; i < 4; i++ )
    {
      if( lumaMode == modeList[i] )
      {
        modeList[i] = VDIA_IDX;
        break;
      }
    }
  }
}


bool PU::isLMCMode(unsigned mode)
{
485
  return (mode >= LM_CHROMA_IDX && mode <= MDLM_T_IDX);
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
}
bool PU::isLMCModeEnabled(const PredictionUnit &pu, unsigned mode)
{
  if ( pu.cs->sps->getSpsNext().getUseLMChroma() )
  {
    return true;
  }
  return false;
}

int PU::getLMSymbolList(const PredictionUnit &pu, int *pModeList)
{
  int iIdx = 0;

  pModeList[ iIdx++ ] = LM_CHROMA_IDX;
    pModeList[ iIdx++ ] = -1;
502 503
  pModeList[iIdx++] = MDLM_L_IDX;
  pModeList[iIdx++] = MDLM_T_IDX;
504 505 506 507 508 509 510 511 512 513
  return iIdx;
}



bool PU::isChromaIntraModeCrossCheckMode( const PredictionUnit &pu )
{
  return pu.intraDir[CHANNEL_TYPE_CHROMA] == DM_CHROMA_IDX;
}

514 515
int PU::getMHIntraMPMs(const PredictionUnit &pu, unsigned* mpm, const ChannelType &channelType /*= CHANNEL_TYPE_LUMA*/, const bool isChromaMDMS /*= false*/, const unsigned startIdx /*= 0*/)
{
516
  const int numMPMs = 3; // Multi-hypothesis intra uses only 3 MPM
517 518 519 520 521 522 523 524 525 526
  {
    int numCand = -1;
    uint32_t leftIntraDir = DC_IDX, aboveIntraDir = DC_IDX;

    const CompArea& area = pu.block(getFirstComponentOfChannel(channelType));
    const Position& pos = area.pos();

    // Get intra direction of left PU
    const PredictionUnit *puLeft = pu.cs->getPURestricted(pos.offset(-1, 0), pu, channelType);

527
    if (puLeft && (CU::isIntra(*puLeft->cu) || puLeft->mhIntraFlag))
528 529 530 531 532 533 534 535 536 537 538 539
    {
      leftIntraDir = puLeft->intraDir[channelType];

      if (isChroma(channelType) && leftIntraDir == DM_CHROMA_IDX)
      {
        leftIntraDir = puLeft->intraDir[0];
      }
    }

    // Get intra direction of above PU
    const PredictionUnit* puAbove = pu.cs->getPURestricted(pos.offset(0, -1), pu, channelType);

540
    if (puAbove && (CU::isIntra(*puAbove->cu) || puAbove->mhIntraFlag) && CU::isSameCtu(*pu.cu, *puAbove->cu))
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
    {
      aboveIntraDir = puAbove->intraDir[channelType];

      if (isChroma(channelType) && aboveIntraDir == DM_CHROMA_IDX)
      {
        aboveIntraDir = puAbove->intraDir[0];
      }
    }

    CHECK(2 >= numMPMs, "Invalid number of most probable modes");

    uint32_t leftIntraDir2 = leftIntraDir;
    uint32_t aboveIntraDir2 = aboveIntraDir;

    leftIntraDir2 = (leftIntraDir2 > DC_IDX) ? ((leftIntraDir2 <= DIA_IDX) ? HOR_IDX : VER_IDX) : leftIntraDir2;
    aboveIntraDir2 = (aboveIntraDir2 > DC_IDX) ? ((aboveIntraDir2 <= DIA_IDX) ? HOR_IDX : VER_IDX) : aboveIntraDir2;

    if (leftIntraDir2 == aboveIntraDir2)
    {
      numCand = 1;

      if (leftIntraDir2 > DC_IDX) // angular modes
      {
        mpm[0] = leftIntraDir2;
        mpm[1] = PLANAR_IDX;
        mpm[2] = DC_IDX;
      }
      else //non-angular
      {
        mpm[0] = PLANAR_IDX;
        mpm[1] = DC_IDX;
        mpm[2] = VER_IDX;
      }
    }
    else
    {
      numCand = 2;

      mpm[0] = leftIntraDir2;
      mpm[1] = aboveIntraDir2;

      if (leftIntraDir2 && aboveIntraDir2) //both modes are non-planar
      {
        mpm[2] = PLANAR_IDX;
      }
      else
      {
        mpm[2] = (leftIntraDir2 + aboveIntraDir2) < 2 ? VER_IDX : DC_IDX;
      }
    }
    int narrowCase = getNarrowShape(pu.lwidth(), pu.lheight());
    if (narrowCase > 0)
    {
      bool isMPM[NUM_LUMA_MODE];
      for (int idx = 0; idx < NUM_LUMA_MODE; idx++)
      {
        isMPM[idx] = false;
      }
      for (int idx = 0; idx < numMPMs; idx++)
      {
        isMPM[mpm[idx]] = true;
      }
      if (narrowCase == 1 && isMPM[HOR_IDX])
      {
        for (int idx = 0; idx < numMPMs; idx++)
        {
          if (mpm[idx] == HOR_IDX)
          {
            if (!isMPM[PLANAR_IDX])
              mpm[idx] = PLANAR_IDX;
            else if (!isMPM[DC_IDX])
              mpm[idx] = DC_IDX;
            else if (!isMPM[VER_IDX])
              mpm[idx] = VER_IDX;
            break;
          }
        }
      }
      if (narrowCase == 2 && isMPM[VER_IDX])
      {
        for (int idx = 0; idx < numMPMs; idx++)
        {
          if (mpm[idx] == VER_IDX)
          {
            if (!isMPM[PLANAR_IDX])
              mpm[idx] = PLANAR_IDX;
            else if (!isMPM[DC_IDX])
              mpm[idx] = DC_IDX;
            else if (!isMPM[HOR_IDX])
              mpm[idx] = HOR_IDX;
            break;
          }
        }
      }
    }
    CHECK(numCand == 0, "No candidates found");
    CHECK(mpm[0] == mpm[1] || mpm[0] == mpm[2] || mpm[2] == mpm[1], "redundant MPM");
    return numCand;
  }
}
int PU::getNarrowShape(const int width, const int height)
{
  int longSide = (width > height) ? width : height;
  int shortSide = (width > height) ? height : width;
  if (longSide > (2 * shortSide))
  {
    if (longSide == width)
      return 1;
    else
      return 2;
  }
  else
  {
    return 0;
  }
}

658 659 660 661 662 663
uint32_t PU::getFinalIntraMode( const PredictionUnit &pu, const ChannelType &chType )
{
  uint32_t uiIntraMode = pu.intraDir[chType];

  if( uiIntraMode == DM_CHROMA_IDX && !isLuma( chType ) )
  {
Li's avatar
Li committed
664
    Position topLeftPos = pu.blocks[pu.chType].lumaPos();
Li's avatar
Li committed
665
    Position refPos = topLeftPos.offset( pu.blocks[pu.chType].lumaSize().width >> 1, pu.blocks[pu.chType].lumaSize().height >> 1 );
Li's avatar
Li committed
666
    const PredictionUnit &lumaPU = CS::isDualITree( *pu.cs ) ? *pu.cs->picture->cs->getPU( refPos, CHANNEL_TYPE_LUMA ) : *pu.cs->getPU( topLeftPos, CHANNEL_TYPE_LUMA );
667

668 669 670 671 672 673 674 675 676
    uiIntraMode = lumaPU.intraDir[0];
  }
  if( pu.chromaFormat == CHROMA_422 && !isLuma( chType ) )
  {
    uiIntraMode = g_chroma422IntraAngleMappingTable[uiIntraMode];
  }
  return uiIntraMode;
}

677 678 679 680 681 682 683 684
bool PU::xCheckSimilarMotion(const int mergeCandIndex, const int prevCnt, const MergeCtx mergeCandList, bool hasPruned[MRG_MAX_NUM_CANDS])
{
  for (uint32_t ui = 0; ui < prevCnt; ui++)
  {
    if (hasPruned[ui])
    {
      continue;
    }
685
    if (mergeCandList.interDirNeighbours[ui] == mergeCandList.interDirNeighbours[mergeCandIndex])
686 687 688
    {
      if (mergeCandList.interDirNeighbours[ui] == 3)
      {
Li's avatar
Li committed
689 690
        int offset0 = (ui * 2);
        int offset1 = (mergeCandIndex * 2);
691 692 693 694 695 696 697 698 699 700 701 702
        if (mergeCandList.mvFieldNeighbours[offset0].refIdx == mergeCandList.mvFieldNeighbours[offset1].refIdx &&
            mergeCandList.mvFieldNeighbours[offset0 + 1].refIdx == mergeCandList.mvFieldNeighbours[offset1 + 1].refIdx &&
            mergeCandList.mvFieldNeighbours[offset0].mv == mergeCandList.mvFieldNeighbours[offset1].mv &&
            mergeCandList.mvFieldNeighbours[offset0 + 1].mv == mergeCandList.mvFieldNeighbours[offset1 + 1].mv
          )
        {
          hasPruned[ui] = true;
          return true;
        }
      }
      else
      {
Li's avatar
Li committed
703 704
        int offset0 = (ui * 2) + mergeCandList.interDirNeighbours[ui] - 1;
        int offset1 = (mergeCandIndex * 2) + mergeCandList.interDirNeighbours[ui] - 1;
705
        if (mergeCandList.mvFieldNeighbours[offset0].refIdx == mergeCandList.mvFieldNeighbours[offset1].refIdx &&
706
            mergeCandList.mvFieldNeighbours[offset0].mv == mergeCandList.mvFieldNeighbours[offset1].mv
707 708 709 710 711 712 713 714
          )
        {
          hasPruned[ui] = true;
          return true;
        }
      }
    }
  }
715

716 717
  return false;
}
718

719
#if JVET_L0090_PAIR_AVG
Xiaozhong Xu's avatar
Xiaozhong Xu committed
720 721

bool PU::addMergeHMVPCand(const Slice &slice, MergeCtx& mrgCtx, bool canFastExit, const int& mrgCandIdx, const uint32_t maxNumMergeCandMin1, int &cnt, const int prevCnt, bool isAvailableSubPu, unsigned subPuMvpPos
722
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
723 724 725
  , int mmvdList
#endif
)
726
#else
Xiaozhong Xu's avatar
Xiaozhong Xu committed
727 728

bool PU::addMergeHMVPCand(const Slice &slice, MergeCtx& mrgCtx, bool isCandInter[MRG_MAX_NUM_CANDS], bool canFastExit, const int& mrgCandIdx, const uint32_t maxNumMergeCandMin1, int &cnt, const int prevCnt, bool isAvailableSubPu, unsigned subPuMvpPos
729
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
730 731 732
  , int mmvdList
#endif
)
733 734
#endif
{
735
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
736 737
  int mrgCandIdxCPR = mrgCandIdx;
#endif
738 739
  MotionInfo miNeighbor;
  bool hasPruned[MRG_MAX_NUM_CANDS];
Li's avatar
Li committed
740
  memset(hasPruned, 0, MRG_MAX_NUM_CANDS * sizeof(bool));
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
  if (isAvailableSubPu)
  {
    hasPruned[subPuMvpPos] = true;
  }
  int num_avai_candInLUT = slice.getAvailableLUTMrgNum();
  for (int mrgIdx = 1; mrgIdx <= num_avai_candInLUT; mrgIdx++)
  {
    miNeighbor = slice.getMotionInfoFromLUTs(num_avai_candInLUT - mrgIdx);
    mrgCtx.interDirNeighbours[cnt] = miNeighbor.interDir;
    mrgCtx.mvFieldNeighbours[cnt << 1].setMvField(miNeighbor.mv[0], miNeighbor.refIdx[0]);
    if (slice.isInterB())
    {
      mrgCtx.mvFieldNeighbours[(cnt << 1) + 1].setMvField(miNeighbor.mv[1], miNeighbor.refIdx[1]);
    }
    if (!xCheckSimilarMotion(cnt, prevCnt, mrgCtx, hasPruned))
    {
#if !JVET_L0090_PAIR_AVG
      isCandInter[cnt] = true;
#endif
Xiaozhong Xu's avatar
Xiaozhong Xu committed
760 761 762 763 764 765 766 767 768
#if JVET_L0293_CPR
      if (miNeighbor.interDir == 1 && slice.getRefPic(REF_PIC_LIST_0, miNeighbor.refIdx[0])->getPOC() == slice.getPOC())
      {
        mrgCtx.mrgTypeNeighbours[cnt] = MRG_TYPE_CPR;
        if(mmvdList != 0 && mrgCandIdx != -1)
          mrgCandIdxCPR++;
      }
      if (mrgCandIdxCPR == cnt && canFastExit)
#else
769
      if (mrgCandIdx == cnt && canFastExit)
Xiaozhong Xu's avatar
Xiaozhong Xu committed
770
#endif
771 772 773 774 775 776 777 778 779 780 781 782
      {
        return true;
      }
      cnt ++;
      if (cnt  == maxNumMergeCandMin1)
      {
        break;
      }
    }
  }
  return false;
}
783

784
void PU::getInterMergeCandidates( const PredictionUnit &pu, MergeCtx& mrgCtx,
785 786
                                 int mmvdList,
                                 const int& mrgCandIdx )
787 788 789 790 791 792
{
  const CodingStructure &cs  = *pu.cs;
  const Slice &slice         = *pu.cs->slice;
  const uint32_t maxNumMergeCand = slice.getMaxNumMergeCand();
  const bool canFastExit     = pu.cs->pps->getLog2ParallelMergeLevelMinus2() == 0;

793 794
#if !JVET_L0090_PAIR_AVG
  // this variable is unused if remove HEVC combined candidates
795
  bool isCandInter[MRG_MAX_NUM_CANDS];
796
#endif
797 798 799

  for (uint32_t ui = 0; ui < maxNumMergeCand; ++ui)
  {
800
#if !JVET_L0090_PAIR_AVG
801
    isCandInter[ui] = false;
Yu-Chi Su's avatar
Yu-Chi Su committed
802
#endif
803
    mrgCtx.GBiIdx[ui] = GBI_DEFAULT;
804 805 806 807 808 809 810 811 812 813
    mrgCtx.interDirNeighbours[ui] = 0;
    mrgCtx.mrgTypeNeighbours [ui] = MRG_TYPE_DEFAULT_N;
    mrgCtx.mvFieldNeighbours[(ui << 1)    ].refIdx = NOT_VALID;
    mrgCtx.mvFieldNeighbours[(ui << 1) + 1].refIdx = NOT_VALID;
  }

  mrgCtx.numValidMergeCand = maxNumMergeCand;
  // compute the location of the current PU

  int cnt = 0;
Xiaozhong Xu's avatar
Xiaozhong Xu committed
814 815


816
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
817 818 819 820 821 822
  int mrgCandIdxCPR = mrgCandIdx;
#endif
#if JVET_L0293_CPR && !JVET_L0369_SUBBLOCK_MERGE
  int cntCPR = 0;
#endif

823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
  const Position posLT = pu.Y().topLeft();
  const Position posRT = pu.Y().topRight();
  const Position posLB = pu.Y().bottomLeft();

  MotionInfo miAbove, miLeft, miAboveLeft, miAboveRight, miBelowLeft;

  //left
  const PredictionUnit* puLeft = cs.getPURestricted( posLB.offset( -1, 0 ), pu, pu.chType );

  const bool isAvailableA1 = puLeft && isDiffMER( pu, *puLeft ) && pu.cu != puLeft->cu && CU::isInter( *puLeft->cu );

  if( isAvailableA1 )
  {
    miLeft = puLeft->getMotionInfo( posLB.offset(-1, 0) );

838
#if !JVET_L0090_PAIR_AVG
839
    isCandInter[cnt] = true;
840
#endif
841 842 843

    // get Inter Dir
    mrgCtx.interDirNeighbours[cnt] = miLeft.interDir;
844
    mrgCtx.GBiIdx[cnt] = (mrgCtx.interDirNeighbours[cnt] == 3) ? puLeft->cu->GBiIdx : GBI_DEFAULT;
845
    // get Mv from Left
Xiaozhong Xu's avatar
Xiaozhong Xu committed
846 847 848 849 850 851 852 853
#if JVET_L0293_CPR
    if (puLeft->cu->cpr)
    {
      mrgCtx.mrgTypeNeighbours[cnt] = MRG_TYPE_CPR;
#if !JVET_L0369_SUBBLOCK_MERGE
      cntCPR++;

#endif
854
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
855 856 857 858 859
      if (mmvdList != 0 && mrgCandIdx != -1)
        mrgCandIdxCPR++;
#endif
    }
#endif
860 861 862 863 864 865
    mrgCtx.mvFieldNeighbours[cnt << 1].setMvField(miLeft.mv[0], miLeft.refIdx[0]);

    if (slice.isInterB())
    {
      mrgCtx.mvFieldNeighbours[(cnt << 1) + 1].setMvField(miLeft.mv[1], miLeft.refIdx[1]);
    }
866
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
867 868
    if (mrgCandIdxCPR == cnt && canFastExit)
#else
869
    if( mrgCandIdx == cnt && canFastExit )
Xiaozhong Xu's avatar
Xiaozhong Xu committed
870
#endif
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
    {
      return;
    }

    cnt++;
  }

  // early termination
  if (cnt == maxNumMergeCand)
  {
    return;
  }


  // above
  const PredictionUnit *puAbove = cs.getPURestricted( posRT.offset( 0, -1 ), pu, pu.chType );

  bool isAvailableB1 = puAbove && isDiffMER( pu, *puAbove ) && pu.cu != puAbove->cu && CU::isInter( *puAbove->cu );

  if( isAvailableB1 )
  {
    miAbove = puAbove->getMotionInfo( posRT.offset( 0, -1 ) );

    if( !isAvailableA1 || ( miAbove != miLeft ) )
    {
896
#if !JVET_L0090_PAIR_AVG
897
      isCandInter[cnt] = true;
898
#endif
899 900 901

      // get Inter Dir
      mrgCtx.interDirNeighbours[cnt] = miAbove.interDir;
902
      // get Mv from Above
903
      mrgCtx.GBiIdx[cnt] = (mrgCtx.interDirNeighbours[cnt] == 3) ? puAbove->cu->GBiIdx : GBI_DEFAULT;
Xiaozhong Xu's avatar
Xiaozhong Xu committed
904 905 906 907 908 909 910 911
#if JVET_L0293_CPR
      if (puAbove->cu->cpr)
      {
        mrgCtx.mrgTypeNeighbours[cnt] = MRG_TYPE_CPR;
#if !JVET_L0369_SUBBLOCK_MERGE
        cntCPR++;

#endif
912
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
913 914 915 916 917
        if (mmvdList != 0 && mrgCandIdx != -1)
          mrgCandIdxCPR++;
#endif
      }
#endif
918
      mrgCtx.mvFieldNeighbours[cnt << 1].setMvField( miAbove.mv[0], miAbove.refIdx[0] );
919 920 921 922 923

      if( slice.isInterB() )
      {
        mrgCtx.mvFieldNeighbours[( cnt << 1 ) + 1].setMvField( miAbove.mv[1], miAbove.refIdx[1] );
      }
924
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
925 926
      if (mrgCandIdxCPR == cnt && canFastExit)
#else
927
      if( mrgCandIdx == cnt && canFastExit )
Xiaozhong Xu's avatar
Xiaozhong Xu committed
928
#endif
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
      {
        return;
      }

      cnt++;
    }
  }

  // early termination
  if( cnt == maxNumMergeCand )
  {
    return;
  }

  // above right
  const PredictionUnit *puAboveRight = cs.getPURestricted( posRT.offset( 1, -1 ), pu, pu.chType );

  bool isAvailableB0 = puAboveRight && isDiffMER( pu, *puAboveRight ) && CU::isInter( *puAboveRight->cu );

  if( isAvailableB0 )
  {
    miAboveRight = puAboveRight->getMotionInfo( posRT.offset( 1, -1 ) );

#if HM_JEM_MERGE_CANDS
    if( ( !isAvailableB1 || ( miAbove != miAboveRight ) ) && ( !isAvailableA1 || ( miLeft != miAboveRight ) ) )
#else
    if( !isAvailableB1 || ( miAbove != miAboveRight ) )
#endif
    {
958
#if !JVET_L0090_PAIR_AVG
959
      isCandInter[cnt] = true;
960
#endif
961 962 963

      // get Inter Dir
      mrgCtx.interDirNeighbours[cnt] = miAboveRight.interDir;
964
      // get Mv from Above-right
965
      mrgCtx.GBiIdx[cnt] = (mrgCtx.interDirNeighbours[cnt] == 3) ? puAboveRight->cu->GBiIdx : GBI_DEFAULT;
Xiaozhong Xu's avatar
Xiaozhong Xu committed
966 967 968 969 970 971 972 973
#if JVET_L0293_CPR
      if (puAboveRight->cu->cpr)
      {
        mrgCtx.mrgTypeNeighbours[cnt] = MRG_TYPE_CPR;
#if !JVET_L0369_SUBBLOCK_MERGE
        cntCPR++;

#endif
974
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
975 976 977 978 979
        if (mmvdList != 0 && mrgCandIdx != -1)
          mrgCandIdxCPR++;
#endif
      }
#endif
980
      mrgCtx.mvFieldNeighbours[cnt << 1].setMvField( miAboveRight.mv[0], miAboveRight.refIdx[0] );
981 982 983 984 985 986

      if( slice.isInterB() )
      {
        mrgCtx.mvFieldNeighbours[( cnt << 1 ) + 1].setMvField( miAboveRight.mv[1], miAboveRight.refIdx[1] );
      }

987
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
988 989
      if (mrgCandIdxCPR == cnt && canFastExit)
#else
990
      if( mrgCandIdx == cnt && canFastExit )
Xiaozhong Xu's avatar
Xiaozhong Xu committed
991
#endif
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
      {
        return;
      }

      cnt++;
    }
  }
  // early termination
  if( cnt == maxNumMergeCand )
  {
    return;
  }

  //left bottom
  const PredictionUnit *puLeftBottom = cs.getPURestricted( posLB.offset( -1, 1 ), pu, pu.chType );

  bool isAvailableA0 = puLeftBottom && isDiffMER( pu, *puLeftBottom ) && CU::isInter( *puLeftBottom->cu );

  if( isAvailableA0 )
  {
    miBelowLeft = puLeftBottom->getMotionInfo( posLB.offset( -1, 1 ) );

#if HM_JEM_MERGE_CANDS
    if( ( !isAvailableA1 || ( miBelowLeft != miLeft ) ) && ( !isAvailableB1 || ( miBelowLeft != miAbove ) ) && ( !isAvailableB0 || ( miBelowLeft != miAboveRight ) ) )
#else
    if( !isAvailableA1 || ( miBelowLeft != miLeft ) )
#endif
    {
1020
#if !JVET_L0090_PAIR_AVG
1021
      isCandInter[cnt] = true;
1022
#endif
1023 1024 1025

      // get Inter Dir
      mrgCtx.interDirNeighbours[cnt] = miBelowLeft.interDir;
1026
      mrgCtx.GBiIdx[cnt] = (mrgCtx.interDirNeighbours[cnt] == 3) ? puLeftBottom->cu->GBiIdx : GBI_DEFAULT;
1027
      // get Mv from Bottom-Left
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1028 1029 1030 1031 1032 1033 1034 1035
#if JVET_L0293_CPR
      if (puLeftBottom->cu->cpr)
      {
        mrgCtx.mrgTypeNeighbours[cnt] = MRG_TYPE_CPR;
#if !JVET_L0369_SUBBLOCK_MERGE
        cntCPR++;

#endif
1036
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1037 1038 1039 1040 1041
        if (mmvdList != 0 && mrgCandIdx != -1)
          mrgCandIdxCPR++;
#endif
      }
#endif
1042 1043 1044 1045 1046 1047 1048
      mrgCtx.mvFieldNeighbours[cnt << 1].setMvField( miBelowLeft.mv[0], miBelowLeft.refIdx[0] );

      if( slice.isInterB() )
      {
        mrgCtx.mvFieldNeighbours[( cnt << 1 ) + 1].setMvField( miBelowLeft.mv[1], miBelowLeft.refIdx[1] );
      }

1049
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1050 1051
      if (mrgCandIdxCPR == cnt && canFastExit)
#else
1052
      if( mrgCandIdx == cnt && canFastExit )
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1053
#endif
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
      {
        return;
      }

      cnt++;
    }
  }
  // early termination
  if( cnt == maxNumMergeCand )
  {
    return;
  }

1067
#if !JVET_L0369_SUBBLOCK_MERGE
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1068 1069 1070 1071

#if JVET_L0293_CPR
  bool enableSubPuMvp = slice.getSPS()->getSpsNext().getUseSubPuMvp() && !(slice.getPOC() == slice.getRefPic(REF_PIC_LIST_0, 0)->getPOC() && slice.isIRAP());
#else
1072
  bool enableSubPuMvp = slice.getSPS()->getSpsNext().getUseSubPuMvp();
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1073 1074
#endif

1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
  bool isAvailableSubPu = false;
  unsigned subPuMvpPos = 0;

  if( enableSubPuMvp )
  {
    CHECK( mrgCtx.subPuMvpMiBuf   .area() == 0 || !mrgCtx.subPuMvpMiBuf   .buf, "Buffer not initialized" );

    mrgCtx.subPuMvpMiBuf   .fill( MotionInfo() );
  }

  if( enableSubPuMvp && slice.getEnableTMVPFlag() )
  {
1087
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1088 1089
    bool bMrgIdxMatchATMVPCan = (mrgCandIdxCPR == cnt);
#else
1090
    bool bMrgIdxMatchATMVPCan = ( mrgCandIdx == cnt );
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1091
#endif
1092 1093
    bool tmpLICFlag           = false;

1094 1095 1096
    isAvailableSubPu = cs.sps->getSpsNext().getUseATMVP() &&     
      getInterMergeSubPuMvpCand( pu, mrgCtx, tmpLICFlag, cnt 
        , mmvdList
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1097 1098
#if JVET_L0293_CPR
      , cntCPR
1099
#endif
1100
    );
1101 1102 1103

    if( isAvailableSubPu )
    {
1104
#if !JVET_L0090_PAIR_AVG
1105
      isCandInter[cnt] = true;
1106
#endif
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123

      mrgCtx.mrgTypeNeighbours[cnt] = MRG_TYPE_SUBPU_ATMVP;

      if( bMrgIdxMatchATMVPCan )
      {
        return;
      }
      subPuMvpPos = cnt;
      cnt++;

      if( cnt == maxNumMergeCand )
      {
        return;
      }
    }

  }
1124
#endif
1125 1126

  // above left
1127 1128 1129
#if JVET_L0369_SUBBLOCK_MERGE
  if ( cnt < 4 )
#else
1130
  if( cnt < ( enableSubPuMvp ? 6 : 4 ) )
1131
#endif
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
  {
    const PredictionUnit *puAboveLeft = cs.getPURestricted( posLT.offset( -1, -1 ), pu, pu.chType );

    bool isAvailableB2 = puAboveLeft && isDiffMER( pu, *puAboveLeft ) && CU::isInter( *puAboveLeft->cu );

    if( isAvailableB2 )
    {
      miAboveLeft = puAboveLeft->getMotionInfo( posLT.offset( -1, -1 ) );

#if HM_JEM_MERGE_CANDS
      if( ( !isAvailableA1 || ( miLeft != miAboveLeft ) ) && ( !isAvailableB1 || ( miAbove != miAboveLeft ) ) && ( !isAvailableA0 || ( miBelowLeft != miAboveLeft ) ) && ( !isAvailableB0 || ( miAboveRight != miAboveLeft ) ) )
#else
      if( ( !isAvailableA1 || ( miLeft != miAboveLeft ) ) && ( !isAvailableB1 || ( miAbove != miAboveLeft ) ) )
#endif
      {
1147
#if !JVET_L0090_PAIR_AVG
1148
        isCandInter[cnt] = true;
1149
#endif
1150 1151 1152

        // get Inter Dir
        mrgCtx.interDirNeighbours[cnt] = miAboveLeft.interDir;
1153
        mrgCtx.GBiIdx[cnt] = (mrgCtx.interDirNeighbours[cnt] == 3) ? puAboveLeft->cu->GBiIdx : GBI_DEFAULT;
1154
        // get Mv from Above-Left
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1155 1156 1157 1158 1159 1160 1161 1162
#if JVET_L0293_CPR
        if (puAboveLeft->cu->cpr)
        {
          mrgCtx.mrgTypeNeighbours[cnt] = MRG_TYPE_CPR;
#if !JVET_L0369_SUBBLOCK_MERGE
          cntCPR++;

#endif
1163
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1164 1165 1166 1167 1168
          if (mmvdList != 0 && mrgCandIdx != -1)
            mrgCandIdxCPR++;
#endif
        }
#endif
1169 1170 1171 1172 1173 1174 1175
        mrgCtx.mvFieldNeighbours[cnt << 1].setMvField( miAboveLeft.mv[0], miAboveLeft.refIdx[0] );

        if( slice.isInterB() )
        {
          mrgCtx.mvFieldNeighbours[( cnt << 1 ) + 1].setMvField( miAboveLeft.mv[1], miAboveLeft.refIdx[1] );
        }

1176
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1177 1178
        if (mrgCandIdxCPR == cnt && canFastExit)
#else
1179
        if( mrgCandIdx == cnt && canFastExit )
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1180
#endif
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
        {
          return;
        }

        cnt++;
      }
    }
  }
  // early termination
  if (cnt == maxNumMergeCand)
  {
    return;
  }

  if (slice.getEnableTMVPFlag())
  {
    //>> MTK colocated-RightBottom
    // offset the pos to be sure to "point" to the same position the uiAbsPartIdx would've pointed to
    Position posRB = pu.Y().bottomRight().offset(-3, -3);

    const PreCalcValues& pcv = *cs.pcv;

    Position posC0;
    Position posC1 = pu.Y().center();
    bool C0Avail = false;

    if (((posRB.x + pcv.minCUWidth) < pcv.lumaWidth) && ((posRB.y + pcv.minCUHeight) < pcv.lumaHeight))
    {
      {
        Position posInCtu( posRB.x & pcv.maxCUWidthMask, posRB.y & pcv.maxCUHeightMask );

        if( ( posInCtu.x + 4 < pcv.maxCUWidth ) &&           // is not at the last column of CTU
            ( posInCtu.y + 4 < pcv.maxCUHeight ) )           // is not at the last row    of CTU
        {
          posC0 = posRB.offset( 4, 4 );
          C0Avail = true;
        }
        else if( posInCtu.x + 4 < pcv.maxCUWidth )           // is not at the last column of CTU But is last row of CTU
        {
          posC0 = posRB.offset( 4, 4 );
          // in the reference the CTU address is not set - thus probably resulting in no using this C0 possibility
        }
        else if( posInCtu.y + 4 < pcv.maxCUHeight )          // is not at the last row of CTU But is last column of CTU
        {
          posC0 = posRB.offset( 4, 4 );
          C0Avail = true;
        }
        else //is the right bottom corner of CTU
        {
          posC0 = posRB.offset( 4, 4 );
          // same as for last column but not last row
        }
      }
    }

    Mv        cColMv;
    int       iRefIdx     = 0;
    int       dir         = 0;
    unsigned  uiArrayAddr = cnt;
    bool      bExistMV    = ( C0Avail && getColocatedMVP(pu, REF_PIC_LIST_0, posC0, cColMv, iRefIdx ) )
                                      || getColocatedMVP(pu, REF_PIC_LIST_0, posC1, cColMv, iRefIdx );

    if (bExistMV)
    {
      dir     |= 1;
      mrgCtx.mvFieldNeighbours[2 * uiArrayAddr].setMvField(cColMv, iRefIdx);
    }

    if (slice.isInterB())
    {
      bExistMV = ( C0Avail && getColocatedMVP(pu, REF_PIC_LIST_1, posC0, cColMv, iRefIdx ) )
                           || getColocatedMVP(pu, REF_PIC_LIST_1, posC1, cColMv, iRefIdx );
      if (bExistMV)
      {
        dir     |= 2;
        mrgCtx.mvFieldNeighbours[2 * uiArrayAddr + 1].setMvField(cColMv, iRefIdx);
      }
    }

    if( dir != 0 )
    {
1262 1263 1264
#if JVET_L0369_SUBBLOCK_MERGE
      bool addTMvp = true;
#else
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
      bool addTMvp = !( cs.sps->getSpsNext().getUseSubPuMvp() && isAvailableSubPu );
      if( !addTMvp )
      {
        if ( dir != mrgCtx.interDirNeighbours[subPuMvpPos] )
        {
          addTMvp = true;
        }
        else
        {
          for( unsigned refList = 0; refList < NUM_REF_PIC_LIST_01; refList++ )
          {
            if( dir & ( 1 << refList ) )
            {
              if( mrgCtx.mvFieldNeighbours[( cnt << 1 ) + refList] != mrgCtx.mvFieldNeighbours[(subPuMvpPos << 1) + refList] )
              {
                addTMvp = true;
                break;
              }
            }
          }
        }
      }
1287
#endif
1288
#if HM_JEM_MERGE_CANDS
1289 1290 1291
#if JVET_L0369_SUBBLOCK_MERGE
      int iSpanCand = cnt;
#else
1292
      int iSpanCand = isAvailableSubPu ? cnt - 1 : cnt;
1293
#endif
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
      for( int i = 0; i < iSpanCand; i++ )
      {
        if( mrgCtx.interDirNeighbours[  i           ] == dir &&
            mrgCtx.mvFieldNeighbours [  i << 1      ] == mrgCtx.mvFieldNeighbours[  uiArrayAddr << 1      ] &&
            mrgCtx.mvFieldNeighbours [( i << 1 ) + 1] == mrgCtx.mvFieldNeighbours[( uiArrayAddr << 1 ) + 1] )
        {
          addTMvp = false;
        }
      }
#endif
      if( addTMvp )
      {
        mrgCtx.interDirNeighbours[uiArrayAddr] = dir;
1307
#if !JVET_L0090_PAIR_AVG
1308
        isCandInter              [uiArrayAddr] = true;
1309
#endif
1310
        mrgCtx.GBiIdx[uiArrayAddr] = GBI_DEFAULT;
1311
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1312 1313
        if (mrgCandIdxCPR == cnt && canFastExit)
#else
1314
        if( mrgCandIdx == cnt && canFastExit )
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1315
#endif
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
        {
          return;
        }

        cnt++;
      }
    }
  }

  // early termination
  if (cnt == maxNumMergeCand)
  {
    return;
  }
1330

1331 1332 1333
  int maxNumMergeCandMin1 = maxNumMergeCand - 1;
  if (cnt != maxNumMergeCandMin1)
  {
1334 1335 1336 1337
#if JVET_L0369_SUBBLOCK_MERGE
    bool isAvailableSubPu = false;
    unsigned subPuMvpPos = 0;
#endif
1338
#if JVET_L0090_PAIR_AVG
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1339
    bool bFound = addMergeHMVPCand(slice, mrgCtx, canFastExit
1340
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1341 1342 1343 1344 1345
      , (mmvdList != 0 && mrgCandIdx != -1) ? (const int) mrgCandIdxCPR : mrgCandIdx
#else
      , mrgCandIdx
#endif
      , maxNumMergeCandMin1, cnt, cnt, isAvailableSubPu, subPuMvpPos
1346
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1347 1348 1349 1350 1351 1352 1353
      , mmvdList
#endif
    );
#else
    bool bFound = addMergeHMVPCand(slice, mrgCtx, isCandInter, canFastExit
#if JVET_L0293_CPR
      , (mmvdList != 0 && mrgCandIdx != -1) ? (const int)mrgCandIdxCPR : mrgCandIdx
1354
#else
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1355 1356 1357
      , mrgCandIdx
#endif
      , maxNumMergeCandMin1, cnt, cnt, isAvailableSubPu, subPuMvpPos
1358
#if JVET_L0293_CPR
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1359 1360 1361
      , mmvdList
#endif
    );
1362 1363 1364 1365 1366 1367
#endif
    if (bFound)
    {
      return;
    }
  }
1368

1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
#if JVET_L0090_PAIR_AVG
  // pairwise-average candidates
  {
    const int cutoff = std::min( cnt, 4 );
    const int end = cutoff * (cutoff - 1) / 2;
    constexpr int PRIORITY_LIST0[] = { 0, 0, 1, 0, 1, 2 };
    constexpr int PRIORITY_LIST1[] = { 1, 2, 2, 3, 3, 3 };

    for( int idx = 0; idx < end && cnt != maxNumMergeCand; idx++ )
    {
      const int i = PRIORITY_LIST0[idx];
      const int j = PRIORITY_LIST1[idx];

      mrgCtx.mvFieldNeighbours[cnt * 2].setMvField( Mv( 0, 0 ), NOT_VALID );
      mrgCtx.mvFieldNeighbours[cnt * 2 + 1].setMvField( Mv( 0, 0 ), NOT_VALID );
      // calculate average MV for L0 and L1 seperately
      unsigned char interDir = 0;
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1386 1387 1388 1389 1390 1391 1392 1393 1394
#if JVET_L0293_CPR


      // skip when one is BV and one is MV
      if (mrgCtx.mrgTypeNeighbours[i] != mrgCtx.mrgTypeNeighbours[j] && pu.cs->sps->getSpsNext().getCPRMode())
      {
        continue;
      }
#endif
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
      for( int refListId = 0; refListId < (slice.isInterB() ? 2 : 1); refListId++ )
      {
        const short refIdxI = mrgCtx.mvFieldNeighbours[i * 2 + refListId].refIdx;
        const short refIdxJ = mrgCtx.mvFieldNeighbours[j * 2 + refListId].refIdx;

        // both MVs are invalid, skip
        if( (refIdxI == NOT_VALID) && (refIdxJ == NOT_VALID) )
        {
          continue;
        }

        interDir += 1 << refListId;
        // both MVs are valid, average these two MVs
        if( (refIdxI != NOT_VALID) && (refIdxJ != NOT_VALID) )
        {
          const Mv& MvI = mrgCtx.mvFieldNeighbours[i * 2 + refListId].mv;
          const Mv& MvJ = mrgCtx.mvFieldNeighbours[j * 2 + refListId].mv;

          // average two MVs
          Mv avgMv = MvI;
          avgMv += MvJ;
          avgMv.setHor( avgMv.getHor() / 2 );
          avgMv.setVer( avgMv.getVer() / 2 );
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
#if JVET_L0293_CPR



          if (mrgCtx.mrgTypeNeighbours[i] == MRG_TYPE_CPR && mrgCtx.mrgTypeNeighbours[j] == MRG_TYPE_CPR && pu.cs->sps->getSpsNext().getCPRMode())
          {
             mrgCtx.mrgTypeNeighbours[cnt] = MRG_TYPE_CPR;
             avgMv.setHor((avgMv.getHor() / 16) << 4);
             avgMv.setVer((avgMv.getVer() / 16) << 4);
          }
#endif
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459

          mrgCtx.mvFieldNeighbours[cnt * 2 + refListId].setMvField( avgMv, refIdxI );
        }
        // only one MV is valid, take the only one MV
        else if( refIdxI != NOT_VALID )
        {
          Mv singleMv = mrgCtx.mvFieldNeighbours[i * 2 + refListId].mv;
          mrgCtx.mvFieldNeighbours[cnt * 2 + refListId].setMvField( singleMv, refIdxI );
        }
        else if( refIdxJ != NOT_VALID )
        {
          Mv singleMv = mrgCtx.mvFieldNeighbours[j * 2 + refListId].mv;
          mrgCtx.mvFieldNeighbours[cnt * 2 + refListId].setMvField( singleMv, refIdxJ );
        }
      }

      mrgCtx.interDirNeighbours[cnt] = interDir;
      if( interDir > 0 )
      {
        cnt++;
      }
    }

    // early termination
    if( cnt == maxNumMergeCand )
    {
      return;
    }
  }
#endif

1460
  uint32_t uiArrayAddr = cnt;
1461
#if !JVET_L0090_PAIR_AVG
1462
  uint32_t uiCutoff    = std::min( uiArrayAddr, 3u );
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
  if (slice.isInterB())
  {
    static const uint32_t NUM_PRIORITY_LIST = 12;
    static const uint32_t uiPriorityList0[NUM_PRIORITY_LIST] = { 0 , 1, 0, 2, 1, 2, 0, 3, 1, 3, 2, 3 };
    static const uint32_t uiPriorityList1[NUM_PRIORITY_LIST] = { 1 , 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2 };

    for (int idx = 0; idx < uiCutoff * (uiCutoff - 1) && uiArrayAddr != maxNumMergeCand; idx++)
    {
      CHECK( idx >= NUM_PRIORITY_LIST, "Invalid priority list number" );
      int i = uiPriorityList0[idx];
      int j = uiPriorityList1[idx];
      if (isCandInter[i] && isCandInter[j] && (mrgCtx.interDirNeighbours[i] & 0x1) && (mrgCtx.interDirNeighbours[j] & 0x2))
      {
        isCandInter[uiArrayAddr] = true;
        mrgCtx.interDirNeighbours[uiArrayAddr] = 3;
1478
        mrgCtx.GBiIdx[uiArrayAddr] = ((mrgCtx.interDirNeighbours[uiArrayAddr] == 3)) ? CU::deriveGbiIdx(mrgCtx.GBiIdx[i], mrgCtx.GBiIdx[j]) : GBI_DEFAULT;
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503

        // get Mv from cand[i] and cand[j]
        mrgCtx.mvFieldNeighbours[ uiArrayAddr << 1     ].setMvField(mrgCtx.mvFieldNeighbours[ i << 1     ].mv, mrgCtx.mvFieldNeighbours[ i << 1     ].refIdx);
        mrgCtx.mvFieldNeighbours[(uiArrayAddr << 1) + 1].setMvField(mrgCtx.mvFieldNeighbours[(j << 1) + 1].mv, mrgCtx.mvFieldNeighbours[(j << 1) + 1].refIdx);

        int iRefPOCL0 = slice.getRefPOC(REF_PIC_LIST_0, mrgCtx.mvFieldNeighbours[(uiArrayAddr << 1)    ].refIdx);
        int iRefPOCL1 = slice.getRefPOC(REF_PIC_LIST_1, mrgCtx.mvFieldNeighbours[(uiArrayAddr << 1) + 1].refIdx);

        if( iRefPOCL0 == iRefPOCL1 && mrgCtx.mvFieldNeighbours[( uiArrayAddr << 1 )].mv == mrgCtx.mvFieldNeighbours[( uiArrayAddr << 1 ) + 1].mv )
        {
          isCandInter[uiArrayAddr] = false;
        }
        else
        {
          uiArrayAddr++;
        }
      }
    }
  }

  // early termination
  if (uiArrayAddr == maxNumMergeCand)
  {
    return;
  }
1504
#endif
1505 1506 1507 1508 1509 1510 1511

  int iNumRefIdx = slice.isInterB() ? std::min(slice.getNumRefIdx(REF_PIC_LIST_0), slice.getNumRefIdx(REF_PIC_LIST_1)) : slice.getNumRefIdx(REF_PIC_LIST_0);

  int r = 0;
  int refcnt = 0;
  while (uiArrayAddr < maxNumMergeCand)
  {
1512
#if !JVET_L0090_PAIR_AVG
1513
    isCandInter               [uiArrayAddr     ] = true;
1514
#endif
1515
    mrgCtx.interDirNeighbours [uiArrayAddr     ] = 1;
1516
    mrgCtx.GBiIdx             [uiArrayAddr     ] = GBI_DEFAULT;
1517 1518 1519 1520 1521 1522 1523 1524
    mrgCtx.mvFieldNeighbours  [uiArrayAddr << 1].setMvField(Mv(0, 0), r);

    if (slice.isInterB())
    {
      mrgCtx.interDirNeighbours [ uiArrayAddr          ] = 3;
      mrgCtx.mvFieldNeighbours  [(uiArrayAddr << 1) + 1].setMvField(Mv(0, 0), r);
    }

Xiaozhong Xu's avatar
Xiaozhong Xu committed
1525 1526 1527 1528 1529 1530 1531
#if JVET_L0293_CPR
    if ( mrgCtx.interDirNeighbours[uiArrayAddr] == 1 && pu.cs->slice->getRefPic(REF_PIC_LIST_0, mrgCtx.mvFieldNeighbours[uiArrayAddr << 1].refIdx)->getPOC() == pu.cs->slice->getPOC())
    {
      mrgCtx.mrgTypeNeighbours[uiArrayAddr] = MRG_TYPE_CPR;
    }
#endif

1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
    uiArrayAddr++;

    if (refcnt == iNumRefIdx - 1)
    {
      r = 0;
    }
    else
    {
      ++r;
      ++refcnt;
    }
  }
  mrgCtx.numValidMergeCand = uiArrayAddr;
}
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1546 1547 1548 1549 1550 1551 1552 1553
#if JVET_L0293_CPR
// for cpr pu validation
bool PU::isBlockVectorValid(PredictionUnit& pu, int xPos, int yPos, int width, int height, int picWidth, int picHeight, int xStartInCU, int yStartInCU, int xBv, int yBv, int ctuSize)
{
  const int ctuSizeLog2 = g_aucLog2[ctuSize];

  int refRightX = xPos + xBv + width - 1;
  int refBottomY = yPos + yBv + height - 1;
1554

Xiaozhong Xu's avatar
Xiaozhong Xu committed
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
  int refLeftX = xPos + xBv;
  int refTopY = yPos + yBv;

  if ((xPos + xBv) < 0)
  {
    return false;
  }
  if (refRightX >= picWidth)
  {
    return false;
  }

  if ((yPos + yBv) < 0)
  {
    return false;
  }
  if (refBottomY >= picHeight)
  {
    return false;
  }
  if ((xBv + width) > 0 && (yBv + height) > 0)
  {
    return false;
  }

  // cannot be in the above CTU row
  if (refTopY >> ctuSizeLog2 < yPos >> ctuSizeLog2)
    return false;

  // cannot be in the below CTU row
  if (refBottomY >> ctuSizeLog2 > yPos >> ctuSizeLog2)
  {
    return false;
  }

  // in the same CTU line

  if ((refRightX >> ctuSizeLog2 <= xPos >> ctuSizeLog2) && (refLeftX >> ctuSizeLog2 >= (xPos >> ctuSizeLog2)))
  {
    // in the same CTU, check if the reference block is already coded
    const Position refPosLT = pu.Y().topLeft().offset(xBv, yBv);
    const Position refPosBR = pu.Y().bottomRight().offset(xBv, yBv);
    const ChannelType      chType = toChannelType(COMPONENT_Y);
    {
      if (!pu.cs->isDecomp(refPosBR, chType))
        return false;
      if (!pu.cs->isDecomp(refPosLT, chType))
        return false;
    }
    return true;
  }
  else
    return false;

}// for cpr pu validation
#endif
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629

static int xGetDistScaleFactor(const int &iCurrPOC, const int &iCurrRefPOC, const int &iColPOC, const int &iColRefPOC)
{
  int iDiffPocD = iColPOC - iColRefPOC;
  int iDiffPocB = iCurrPOC - iCurrRefPOC;

  if (iDiffPocD == iDiffPocB)
  {
    return 4096;
  }
  else
  {
    int iTDB = Clip3(-128, 127, iDiffPocB);
    int iTDD = Clip3(-128, 127, iDiffPocD);
    int iX = (0x4000 + abs(iTDD / 2)) / iTDD;
    int iScale = Clip3(-4096, 4095, (iTDB * iX + 32) >> 6);
    return iScale;
  }
}
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
int PU::getDistScaleFactor(const int &currPOC, const int &currRefPOC, const int &colPOC, const int &colRefPOC)
{
  return xGetDistScaleFactor(currPOC, currRefPOC, colPOC, colRefPOC);
}

void PU::getInterMMVDMergeCandidates(const PredictionUnit &pu, MergeCtx& mrgCtx, const int& mrgCandIdx)
{
  int refIdxList0, refIdxList1;
  int k;
  int currBaseNum = 0;
  const uint16_t maxNumMergeCand = mrgCtx.numValidMergeCand;

  for (k = 0; k < maxNumMergeCand; k++)
  {
    if (mrgCtx.mrgTypeNeighbours[k] == MRG_TYPE_DEFAULT_N)
    {
      refIdxList0 = mrgCtx.mvFieldNeighbours[(k << 1)].refIdx;
      refIdxList1 = mrgCtx.mvFieldNeighbours[(k << 1) + 1].refIdx;

      if ((refIdxList0 >= 0) && (refIdxList1 >= 0))
      {
        mrgCtx.mmvdBaseMv[currBaseNum][0] = mrgCtx.mvFieldNeighbours[(k << 1)];
        mrgCtx.mmvdBaseMv[currBaseNum][1] = mrgCtx.mvFieldNeighbours[(k << 1) + 1];
      }
      else if (refIdxList0 >= 0)
      {
        mrgCtx.mmvdBaseMv[currBaseNum][0] = mrgCtx.mvFieldNeighbours[(k << 1)];
        mrgCtx.mmvdBaseMv[currBaseNum][1] = MvField(Mv(0, 0), -1);
      }
      else if (refIdxList1 >= 0)
      {
        mrgCtx.mmvdBaseMv[currBaseNum][0] = MvField(Mv(0, 0), -1);
        mrgCtx.mmvdBaseMv[currBaseNum][1] = mrgCtx.mvFieldNeighbours[(k << 1) + 1];
      }
1664

1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
      currBaseNum++;

      if (currBaseNum == MMVD_BASE_MV_NUM)
        break;
    }
  }

  if (currBaseNum < MMVD_BASE_MV_NUM)
  {
    for (k = currBaseNum; k < MMVD_BASE_MV_NUM; k++)
    {
      mrgCtx.mmvdBaseMv[k][0] = MvField(Mv(0, 0), 0);
      mrgCtx.mmvdBaseMv[k][0] = MvField(Mv(0, 0), 0);
    }
  }
}
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
bool PU::getColocatedMVP(const PredictionUnit &pu, const RefPicList &eRefPicList, const Position &_pos, Mv& rcMv, const int &refIdx )
{
  // don't perform MV compression when generally disabled or subPuMvp is used
  const unsigned scale = ( pu.cs->pcv->noMotComp ? 1 : 4 * std::max<int>(1, 4 * AMVP_DECIMATION_FACTOR / 4) );
  const unsigned mask  = ~( scale - 1 );

  const Position pos = Position{ PosType( _pos.x & mask ), PosType( _pos.y & mask ) };

  const Slice &slice = *pu.cs->slice;

  // use coldir.
  const Picture* const pColPic = slice.getRefPic(RefPicList(slice.isInterB() ? 1 - slice.getColFromL0Flag() : 0), slice.getColRefIdx());

  if( !pColPic )
  {
    return false;
  }

  RefPicList eColRefPicList = slice.getCheckLDC() ? eRefPicList : RefPicList(slice.getColFromL0Flag());

  const MotionInfo& mi = pColPic->cs->getMotionInfo( pos );

  if( !mi.isInter )
  {
    return false;
  }
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1707 1708 1709 1710 1711 1712
#if JVET_L0293_CPR
  if (eRefPicList == REF_PIC_LIST_0 && pu.cs->slice->getRefPic(eRefPicList, refIdx)->getPOC() == pu.cs->slice->getPOC())
  {
    return false;
  }
#endif
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
  int iColRefIdx = mi.refIdx[eColRefPicList];

  if (iColRefIdx < 0)
  {
    eColRefPicList = RefPicList(1 - eColRefPicList);
    iColRefIdx = mi.refIdx[eColRefPicList];

    if (iColRefIdx < 0)
    {
      return false;
    }
  }

  const Slice *pColSlice = nullptr;

  for( const auto s : pColPic->slices )
  {
    if( s->getIndependentSliceIdx() == mi.sliceIdx )
    {
      pColSlice = s;
      break;
    }
  }

  CHECK( pColSlice == nullptr, "Slice segment not found" );

  const Slice &colSlice = *pColSlice;

  const bool bIsCurrRefLongTerm = slice.getRefPic(eRefPicList, refIdx)->longTerm;
  const bool bIsColRefLongTerm  = colSlice.getIsUsedAsLongTerm(eColRefPicList, iColRefIdx);

  if (bIsCurrRefLongTerm != bIsColRefLongTerm)
  {
    return false;
  }


  // Scale the vector.
  Mv cColMv = mi.mv[eColRefPicList];

  if (bIsCurrRefLongTerm /*|| bIsColRefLongTerm*/)
  {
    rcMv = cColMv;
  }
  else
  {
    const int currPOC    = slice.getPOC();
    const int colPOC     = colSlice.getPOC();
    const int colRefPOC  = colSlice.getRefPOC(eColRefPicList, iColRefIdx);
    const int currRefPOC = slice.getRefPic(eRefPicList, refIdx)->getPOC();
    const int distscale  = xGetDistScaleFactor(currPOC, currRefPOC, colPOC, colRefPOC);

    if (distscale == 4096)
    {
      rcMv = cColMv;
    }
    else
    {
      rcMv = cColMv.scaleMv(distscale);
    }
  }

  return true;
}

bool PU::isDiffMER(const PredictionUnit &pu1, const PredictionUnit &pu2)
{
  const unsigned xN = pu1.lumaPos().x;
  const unsigned yN = pu1.lumaPos().y;
  const unsigned xP = pu2.lumaPos().x;
  const unsigned yP = pu2.lumaPos().y;

  unsigned plevel = pu1.cs->pps->getLog2ParallelMergeLevelMinus2() + 2;

  if ((xN >> plevel) != (xP >> plevel))
  {
    return true;
  }

  if ((yN >> plevel) != (yP >> plevel))
  {
    return true;
  }

  return false;
}
Xiaozhong Xu's avatar
Xiaozhong Xu committed
1799 1800 1801
#if JVET_L0293_CPR
void PU::getCprMVPsEncOnly(PredictionUnit &pu, Mv* MvPred, int& nbPred)
{
1802

Xiaozhong Xu's avatar
Xiaozhong Xu committed
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
  //-- Get Spatial MV
  Position posLT = pu.Y().topLeft();
  Position posRT = pu.Y().topRight();
  Position posLB = pu.Y().bottomLeft();

  unsigned int left = 0, above = 0;

  //left
  const PredictionUnit *neibLeftPU = NULL;
  neibLeftPU = pu.cs->getPURestricted(posLB.offset(-1, 0), pu, pu.cs->chType);
  left = (neibLeftPU) ? neibLeftPU->cu->cpr : 0;

  if (left)
  {
    MvPred[nbPred++] = neibLeftPU->bv;
    if (getDerivedBV(pu, MvPred[nbPred - 1], MvPred[nbPred]))
      nbPred++;
  }

  //above
  const PredictionUnit *neibAbovePU = NULL;
  neibAbovePU = pu.cs->getPURestricted(posRT.offset(0, -1), pu, pu.cs->chType);
  above = (neibAbovePU) ? neibAbovePU->cu->cpr : 0;

  if (above)
  {
    MvPred[nbPred++] = neibAbovePU->bv;
    if (getDerivedBV(pu, MvPred[nbPred - 1], MvPred[nbPred]))
      nbPred++;
  }

  // Below Left predictor search
  const PredictionUnit *neibBelowLeftPU = NULL;
  neibBelowLeftPU = pu.cs->getPURestricted(posLB.offset(-1, 1), pu, pu.cs->chType);
  unsigned int belowLeft = (neibBelowLeftPU) ? neibBelowLeftPU->cu->cpr : 0;

  if (belowLeft)
  {
    MvPred[nbPred++] = neibBelowLeftPU->bv;
    if (getDerivedBV(pu, MvPred[nbPred - 1], MvPred[nbPred]))
      nbPred++;
  }


  // Above Right predictor search
  const PredictionUnit *neibAboveRightPU = NULL;
  neibAboveRightPU = pu.cs->getPURestricted(posRT.offset(1, -1), pu, pu.cs->chType);
  unsigned int aboveRight = (neibAboveRightPU) ? neibAboveRightPU->cu->cpr : 0;

  if (aboveRight)
  {
    MvPred[nbPred++] = neibAboveRightPU->bv;
    if (getDerivedBV(pu, MvPred[nbPred - 1], MvPred[nbPred]))
      nbPred++;
  }


  // Above Left predictor search
  const PredictionUnit *neibAboveLeftPU = NULL;
  neibAboveLeftPU = pu.cs->getPURestricted(posLT.offset(-1, -1), pu, pu.cs->chType);
  unsigned int aboveLeft = (neibAboveLeftPU) ? neibAboveLeftPU->cu->cpr : 0;

  if (aboveLeft)
  {
    MvPred[nbPred++] = neibAboveLeftPU->bv;
    if (getDerivedBV(pu, MvPred[nbPred - 1], MvPred[nbPred]))
      nbPred++;
  }
}

bool PU::getDerivedBV(PredictionUnit &pu, const Mv& currentMv, Mv& derivedMv)
{
  int   cuPelX = pu.lumaPos().x;
  int   cuPelY = pu.lumaPos().y;
  int rX = cuPelX + currentMv.getHor();
  int rY = cuPelY + currentMv.getVer();
  int offsetX = currentMv.getHor();
  int offsetY = currentMv.getVer();


  if (rX < 0 || rY < 0 || rX >= pu.cs->slice->getSPS()->getPicWidthInLumaSamples() || rY >= pu.cs->slice->getSPS()->getPicHeightInLumaSamples())
  {
    return false;
  }

  const PredictionUnit *neibRefPU = NULL;
  neibRefPU = pu.cs->getPURestricted(pu.lumaPos().offset(offsetX, offsetY), pu, pu.cs->chType);

  bool isCPR = (neibRefPU) ? neibRefPU->cu->cpr : 0;
  if (isCPR)
  {
    derivedMv = neibRefPU->bv;
    derivedMv += currentMv;
  }
  return isCPR;
}
#endif // CPR
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987