Skip to content
Snippets Groups Projects
IntraSearch.cpp 235 KiB
Newer Older
  • Learn to ignore specific revisions
  •     qp[ch] = cQP.Qp(true);
    #else
        qp[ch] = cQP.Qp(false);
    #endif
        qpRem[ch] = qp[ch] % 6;
        qpPer[ch] = qp[ch] / 6;
        quantiserScale[ch] = g_quantScales[0][qpRem[ch]];
        quantiserRightShift[ch] = QUANT_SHIFT + qpPer[ch];
        rightShiftOffset[ch] = 1 << (quantiserRightShift[ch] - 1);
        invquantiserRightShift[ch] = IQUANT_SHIFT;
        add[ch] = 1 << (invquantiserRightShift[ch] - 1);
      }
    
      for (uint32_t ch = compBegin; ch < (compBegin + numComp); ch++)
      {
        const int  channelBitDepth = cu.cs->sps->getBitDepth(toChannelType((ComponentID)ch));
        paPixelValue[ch] = Pel(std::max<int>(0, ((orgBuf[ch] * quantiserScale[ch] + rightShiftOffset[ch]) >> quantiserRightShift[ch])));
        assert(paPixelValue[ch] < (1 << (channelBitDepth + 1)));
        paRecoValue[ch] = (((paPixelValue[ch] * g_invQuantScales[0][qpRem[ch]]) << qpPer[ch]) + add[ch]) >> invquantiserRightShift[ch];
        paRecoValue[ch] = Pel(ClipBD<int>(paRecoValue[ch], channelBitDepth));//to be checked
      }
    }
    
    void IntraSearch::preCalcPLTIndexRD(CodingStructure& cs, Partitioner& partitioner, ComponentID compBegin, uint32_t numComp)
    {
      CodingUnit &cu = *cs.getCU(partitioner.chType);
      uint32_t height = cu.block(compBegin).height;
      uint32_t width = cu.block(compBegin).width;
    
      CPelBuf   orgBuf[3];
      for (int comp = compBegin; comp < (compBegin + numComp); comp++)
      {
        CompArea  area = cu.blocks[comp];
    
    Brian Heng's avatar
    Brian Heng committed
    #if JVET_P1006_PICTURE_HEADER
        if (m_pcEncCfg->getReshaper() && (cs.picHeader->getLmcsEnabledFlag() && m_pcReshape->getCTUFlag()))
    #else
    
        if (m_pcEncCfg->getReshaper() && (cs.slice->getLmcsEnabledFlag() && m_pcReshape->getCTUFlag()))
    
    Brian Heng's avatar
    Brian Heng committed
    #endif
    
    2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499
        {
          orgBuf[comp] = cs.getPredBuf(area);
        }
        else
        {
          orgBuf[comp] = cs.getOrgBuf(area);
        }
      }
    
      int rasPos;
      uint32_t scaleX = getComponentScaleX(COMPONENT_Cb, cs.sps->getChromaFormatIdc());
      uint32_t scaleY = getComponentScaleY(COMPONENT_Cb, cs.sps->getChromaFormatIdc());
      for (uint32_t y = 0; y < height; y++)
      {
        for (uint32_t x = 0; x < width; x++)
        {
          rasPos = y * width + x;;
          // chroma discard
          bool discardChroma = (compBegin == COMPONENT_Y) && (y&scaleY || x&scaleX);
          Pel curPel[3];
          for (int comp = compBegin; comp < (compBegin + numComp); comp++)
          {
            uint32_t pX1 = (comp > 0 && compBegin == COMPONENT_Y) ? (x >> scaleX) : x;
            uint32_t pY1 = (comp > 0 && compBegin == COMPONENT_Y) ? (y >> scaleY) : y;
            curPel[comp] = orgBuf[comp].at(pX1, pY1);
          }
    
          uint8_t  pltIdx = 0;
          double minError = MAX_DOUBLE;
          uint8_t  bestIdx = 0;
          while (pltIdx < cu.curPLTSize[compBegin])
          {
            uint64_t sqrtError = 0;
            for (int comp = compBegin; comp < (discardChroma ? 1 : (compBegin + numComp)); comp++)
            {
              int64_t tmpErr = int64_t(curPel[comp] - cu.curPLT[comp][pltIdx]);
              if (isChroma((ComponentID)comp))
              {
                sqrtError += uint64_t(tmpErr*tmpErr*ENC_CHROMA_WEIGHTING);
              }
              else
              {
                sqrtError += tmpErr*tmpErr;
              }
            }
            m_indexError[pltIdx][rasPos] = (double)sqrtError;
            if (sqrtError < minError)
            {
              minError = (double)sqrtError;
              bestIdx = pltIdx;
            }
            pltIdx++;
          }
    
          Pel paPixelValue[3], paRecoValue[3];
          calcPixelPredRD(cs, partitioner, curPel, paPixelValue, paRecoValue, compBegin, numComp);
          uint64_t error = 0, rate = 0;
          for (int comp = compBegin; comp < (discardChroma ? 1 : (compBegin + numComp)); comp++)
          {
            int64_t tmpErr = int64_t(curPel[comp] - paRecoValue[comp]);
            if (isChroma((ComponentID)comp))
            {
              error += uint64_t(tmpErr*tmpErr*ENC_CHROMA_WEIGHTING);
            }
            else
            {
              error += tmpErr*tmpErr;
            }
            rate += m_escapeNumBins[paPixelValue[comp]]; // encode quantized escape color
          }
          double rdCost = (double)error + m_pcRdCost->getLambda()*(double)rate;
          m_indexError[cu.curPLTSize[compBegin]][rasPos] = rdCost;
          if (rdCost < minError) 
          {
            minError = rdCost;
            bestIdx = (uint8_t)cu.curPLTSize[compBegin];
          }
          m_minErrorIndexMap[rasPos] = bestIdx; // save the optimal index of the current pixel
        }
      }
    }
    
    void IntraSearch::deriveIndexMap(CodingStructure& cs, Partitioner& partitioner, ComponentID compBegin, uint32_t numComp, PLTScanMode pltScanMode, double& dMinCost)
    {
      CodingUnit    &cu = *cs.getCU(partitioner.chType);
      TransformUnit &tu = *cs.getTU(partitioner.chType);
      uint32_t      height = cu.block(compBegin).height;
      uint32_t      width = cu.block(compBegin).width;
    
      int   total     = height*width;
      Pel  *runIndex = tu.getPLTIndex(compBegin);
      bool *runType  = tu.getRunTypes(compBegin);
      m_scanOrder = g_scanOrder[SCAN_UNGROUPED][pltScanMode ? SCAN_TRAV_VER : SCAN_TRAV_HOR][gp_sizeIdxInfo->idxFrom(width)][gp_sizeIdxInfo->idxFrom(height)];
    // Trellis initialization
      for (int i = 0; i < 2; i++)
      {
        memset(m_prevRunTypeRDOQ[i], 0, sizeof(Pel)*NUM_TRELLIS_STATE);
        memset(m_prevRunPosRDOQ[i],  0, sizeof(int)*NUM_TRELLIS_STATE);
        memset(m_stateCostRDOQ[i],  0, sizeof (double)*NUM_TRELLIS_STATE);
      }
      for (int state = 0; state < NUM_TRELLIS_STATE; state++)
      {
        m_statePtRDOQ[state][0] = 0;
      }
    // Context modeling
      const FracBitsAccess& fracBits = m_CABACEstimator->getCtx().getFracBitsAcess();
      BinFracBits fracBitsPltCopyFlagIndex[RUN_IDX_THRE + 1];
      for (int dist = 0; dist <= RUN_IDX_THRE; dist++)
      {
        const unsigned  ctxId = DeriveCtx::CtxPltCopyFlag(PLT_RUN_INDEX, dist);
        fracBitsPltCopyFlagIndex[dist] = fracBits.getFracBitsArray(Ctx::IdxRunModel( ctxId ) );
      }
      BinFracBits fracBitsPltCopyFlagAbove[RUN_IDX_THRE + 1];
      for (int dist = 0; dist <= RUN_IDX_THRE; dist++)
      {
        const unsigned  ctxId = DeriveCtx::CtxPltCopyFlag(PLT_RUN_COPY, dist);
        fracBitsPltCopyFlagAbove[dist] = fracBits.getFracBitsArray(Ctx::CopyRunModel( ctxId ) );
      }
      const BinFracBits fracBitsPltRunType = fracBits.getFracBitsArray( Ctx::RunTypeFlag() );
    
    // Trellis RDO per CG
      bool contTrellisRD = true;
      for (int subSetId = 0; ( subSetId <= (total - 1) >> LOG2_PALETTE_CG_SIZE ) && contTrellisRD; subSetId++)
      {
        int minSubPos = subSetId << LOG2_PALETTE_CG_SIZE;
        int maxSubPos = minSubPos + (1 << LOG2_PALETTE_CG_SIZE);
        maxSubPos = (maxSubPos > total) ? total : maxSubPos; // if last position is out of the current CU size
        contTrellisRD = deriveSubblockIndexMap(cs, partitioner, compBegin, pltScanMode, minSubPos, maxSubPos, fracBitsPltRunType, fracBitsPltCopyFlagIndex, fracBitsPltCopyFlagAbove, dMinCost, (bool)pltScanMode);
      }
      if (!contTrellisRD)
      {
        return;
      }
    
    
    // best state at the last scan position
      double  sumRdCost = MAX_DOUBLE;
      uint8_t bestState = 0;
      for (uint8_t state = 0; state < NUM_TRELLIS_STATE; state++)
      {
        if (m_stateCostRDOQ[0][state] < sumRdCost)
        {
          sumRdCost = m_stateCostRDOQ[0][state];
          bestState = state;
        }
      }
    
         bool checkRunTable  [MAX_CU_BLKSIZE_PLT*MAX_CU_BLKSIZE_PLT];
      uint8_t checkIndexTable[MAX_CU_BLKSIZE_PLT*MAX_CU_BLKSIZE_PLT];
      uint8_t bestStateTable [MAX_CU_BLKSIZE_PLT*MAX_CU_BLKSIZE_PLT];
      uint8_t nextState = bestState;
    // best trellis path
      for (int i = (width*height - 1); i >= 0; i--)
      {
        bestStateTable[i] = nextState;
        int rasterPos = m_scanOrder[i].idx;
        nextState = m_statePtRDOQ[nextState][rasterPos];
      }
    // reconstruct index and runs based on the state pointers
      for (int i = 0; i < (width*height); i++)
      {
        int rasterPos = m_scanOrder[i].idx;
        int  abovePos = (pltScanMode == PLT_SCAN_HORTRAV) ? m_scanOrder[i].idx - width : m_scanOrder[i].idx - 1;
            nextState = bestStateTable[i];
        if ( nextState == 0 ) // same as the previous
        {
          checkRunTable[rasterPos] = checkRunTable[ m_scanOrder[i - 1].idx ];
          if ( checkRunTable[rasterPos] == PLT_RUN_INDEX )
          {
            checkIndexTable[rasterPos] = checkIndexTable[m_scanOrder[i - 1].idx];
          }
          else
          {
            checkIndexTable[rasterPos] = checkIndexTable[ abovePos ];
          }
        }
        else if (nextState == 1) // CopyAbove mode
        {
          checkRunTable[rasterPos] = PLT_RUN_COPY;
          checkIndexTable[rasterPos] = checkIndexTable[abovePos];
        }
        else if (nextState == 2) // Index mode
        {
          checkRunTable[rasterPos] = PLT_RUN_INDEX;
          checkIndexTable[rasterPos] = m_minErrorIndexMap[rasterPos];
        }
      }
    
    // Escape flag
      m_bestEscape = false;
      for (int pos = 0; pos < (width*height); pos++)
      {
        uint8_t index = checkIndexTable[pos];
        if (index == cu.curPLTSize[compBegin])
        {
          m_bestEscape = true;
          break;
        }
      }
    
    // Horizontal scan v.s vertical scan
      if (sumRdCost < dMinCost)
      {
        cu.useEscape[compBegin] = m_bestEscape;
        m_bestScanRotationMode = pltScanMode;
        for (int pos = 0; pos < (width*height); pos++)
        {
          runIndex[pos] = checkIndexTable[pos];
          runType[pos] = checkRunTable[pos];
        }
        dMinCost = sumRdCost;
      }
    }
    
    bool IntraSearch::deriveSubblockIndexMap(
      CodingStructure& cs,
      Partitioner&  partitioner,
      ComponentID   compBegin,
      PLTScanMode   pltScanMode,
      int           minSubPos,
      int           maxSubPos,
      const BinFracBits& fracBitsPltRunType,
      const BinFracBits* fracBitsPltIndexINDEX,
      const BinFracBits* fracBitsPltIndexCOPY,
      const double minCost,
      bool         useRotate
    )
    {
      CodingUnit &cu    = *cs.getCU(partitioner.chType);
      uint32_t   height = cu.block(compBegin).height;
      uint32_t   width  = cu.block(compBegin).width;
      int indexMaxValue = cu.curPLTSize[compBegin];
    
      int refId = 0;
      int currRasterPos, currScanPos, prevScanPos, aboveScanPos, roffset;
      int log2Width = (pltScanMode == PLT_SCAN_HORTRAV) ? floorLog2(width): floorLog2(height);
      int buffersize = (pltScanMode == PLT_SCAN_HORTRAV) ? 2*width: 2*height;
      for (int curPos = minSubPos; curPos < maxSubPos; curPos++)
      {
        currRasterPos = m_scanOrder[curPos].idx;
        prevScanPos = (curPos == 0) ? 0 : (curPos - 1) % buffersize;
        roffset = (curPos >> log2Width) << log2Width;
        aboveScanPos = roffset - (curPos - roffset + 1);
        aboveScanPos %= buffersize;
        currScanPos = curPos % buffersize;
        if ((pltScanMode == PLT_SCAN_HORTRAV && curPos < width) || (pltScanMode == PLT_SCAN_VERTRAV && curPos < height))
        {
          aboveScanPos = -1; // first column/row: above row is not valid
        }
    
    // Trellis stats: 
    // 1st state: same as previous scanned sample
    // 2nd state: Copy_Above mode
    // 3rd state: Index mode 
    // Loop of current state
        for ( int curState = 0; curState < NUM_TRELLIS_STATE; curState++ ) 
        {
          double    minRdCost          = MAX_DOUBLE;
          int       minState           = 0; // best prevState
          uint8_t   bestRunIndex       = 0;
          bool      bestRunType        = 0;
          bool      bestPrevCodedType  = 0;
          int       bestPrevCodedPos   = 0;
          if ( ( curState == 0 && curPos == 0 ) || ( curState == 1 && aboveScanPos < 0 ) ) // state not available
          {
            m_stateCostRDOQ[1 - refId][curState] = MAX_DOUBLE;
            continue;
          }
    
          bool    runType  = 0;
          uint8_t runIndex = 0;
          if ( curState == 1 ) // 2nd state: Copy_Above mode
          {
            runType = PLT_RUN_COPY;
          }
          else if ( curState == 2 ) // 3rd state: Index mode 
          {
            runType = PLT_RUN_INDEX;
            runIndex = m_minErrorIndexMap[currRasterPos];
          }
    
    // Loop of previous state
          for ( int stateID = 0; stateID < NUM_TRELLIS_STATE; stateID++ ) 
          {
            if ( m_stateCostRDOQ[refId][stateID] == MAX_DOUBLE )
            {
              continue;
            }
            if ( curState == 0 ) // 1st state: same as previous scanned sample
            {
              runType = m_runMapRDOQ[refId][stateID][prevScanPos];
              runIndex = ( runType == PLT_RUN_INDEX ) ? m_indexMapRDOQ[refId][stateID][ prevScanPos ] : m_indexMapRDOQ[refId][stateID][ aboveScanPos ];
            }
            else if ( curState == 1 ) // 2nd state: Copy_Above mode
            {
              runIndex = m_indexMapRDOQ[refId][stateID][aboveScanPos];
            }
            bool    prevRunType   = m_runMapRDOQ[refId][stateID][prevScanPos];
            uint8_t prevRunIndex  = m_indexMapRDOQ[refId][stateID][prevScanPos];
            uint8_t aboveRunIndex = (aboveScanPos >= 0) ? m_indexMapRDOQ[refId][stateID][aboveScanPos] : 0;
            int      dist = curPos - m_prevRunPosRDOQ[refId][stateID] - 1;
            double rdCost = m_stateCostRDOQ[refId][stateID];
            if ( rdCost >= minRdCost ) continue;
    
    // Calculate Rd cost 
            bool prevCodedRunType = m_prevRunTypeRDOQ[refId][stateID];
            int  prevCodedPos     = m_prevRunPosRDOQ [refId][stateID];
            const BinFracBits* fracBitsPt = (m_prevRunTypeRDOQ[refId][stateID] == PLT_RUN_INDEX) ? fracBitsPltIndexINDEX : fracBitsPltIndexCOPY;
            rdCost += rateDistOptPLT(runType, runIndex, prevRunType, prevRunIndex, aboveRunIndex, prevCodedRunType, prevCodedPos, curPos, (pltScanMode == PLT_SCAN_HORTRAV) ? width : height, dist, indexMaxValue, fracBitsPt, fracBitsPltRunType);
            if (rdCost < minRdCost) // update minState ( minRdCost )
            {
              minRdCost    = rdCost;
              minState     = stateID;
              bestRunType  = runType;
              bestRunIndex = runIndex;
              bestPrevCodedType = prevCodedRunType;
              bestPrevCodedPos  = prevCodedPos;
            }
          }
    // Update trellis info of current state
          m_stateCostRDOQ  [1 - refId][curState]  = minRdCost;
          m_prevRunTypeRDOQ[1 - refId][curState]  = bestPrevCodedType;
          m_prevRunPosRDOQ [1 - refId][curState]  = bestPrevCodedPos;
          m_statePtRDOQ[curState][currRasterPos] = minState;
          int buffer2update = std::min(buffersize, curPos);
          memcpy(m_indexMapRDOQ[1 - refId][curState], m_indexMapRDOQ[refId][minState], sizeof(uint8_t)*buffer2update);
          memcpy(m_runMapRDOQ[1 - refId][curState], m_runMapRDOQ[refId][minState], sizeof(bool)*buffer2update);
          m_indexMapRDOQ[1 - refId][curState][currScanPos] = bestRunIndex;
          m_runMapRDOQ  [1 - refId][curState][currScanPos] = bestRunType;
        }
    
        if (useRotate) // early terminate: Rd cost >= min cost in horizontal scan
        {
          if ((m_stateCostRDOQ[1 - refId][0] >= minCost) &&
             (m_stateCostRDOQ[1 - refId][1] >= minCost) &&
             (m_stateCostRDOQ[1 - refId][2] >= minCost) )
          {
            return 0;
          }
        }
        refId = 1 - refId;
      }
      return 1;
    }
    
    double IntraSearch::rateDistOptPLT(
      bool      runType,
      uint8_t   runIndex,
      bool      prevRunType,
      uint8_t   prevRunIndex,
      uint8_t   aboveRunIndex,
      bool&     prevCodedRunType,
      int&      prevCodedPos,
      int       scanPos,
      uint32_t  width,
      int       dist,
      int       indexMaxValue,
      const BinFracBits* IndexfracBits,
      const BinFracBits& TypefracBits)
    {
      double rdCost = 0.0;
      bool identityFlag = !( (runType != prevRunType) || ( (runType == PLT_RUN_INDEX) && (runIndex != prevRunIndex) ) );
    
      if ( ( !identityFlag && runType == PLT_RUN_INDEX ) || scanPos == 0 ) // encode index value
      {
        uint8_t refIndex = (prevRunType == PLT_RUN_INDEX) ? prevRunIndex : aboveRunIndex;
        refIndex = (scanPos == 0) ? ( indexMaxValue + 1) : refIndex;
        if ( runIndex == refIndex )
        {
          rdCost = MAX_DOUBLE;
          return rdCost;
        }
        rdCost += m_pcRdCost->getLambda()*m_truncBinBits[(runIndex > refIndex) ? runIndex - 1 : runIndex][(scanPos == 0) ? (indexMaxValue + 1) : indexMaxValue];
      }
      rdCost += m_indexError[runIndex][m_scanOrder[scanPos].idx];
      if (scanPos > 0)
      {
        rdCost += m_pcRdCost->getLambda()*( identityFlag ? (IndexfracBits[(dist < RUN_IDX_THRE) ? dist : RUN_IDX_THRE].intBits[1] >> SCALE_BITS) : (IndexfracBits[(dist < RUN_IDX_THRE) ? dist : RUN_IDX_THRE].intBits[0] >> SCALE_BITS));
      }
      if ( !identityFlag && scanPos >= width && prevRunType != PLT_RUN_COPY )
      {
        rdCost += m_pcRdCost->getLambda()*(TypefracBits.intBits[runType] >> SCALE_BITS);
      }
      if (!identityFlag || scanPos == 0)
      {
        prevCodedRunType = runType;
        prevCodedPos = scanPos;
      }
      return rdCost;
    }
    uint32_t IntraSearch::getEpExGolombNumBins(uint32_t symbol, uint32_t count)
    {
      uint32_t numBins = 0;
      while (symbol >= (uint32_t)(1 << count))
      {
        numBins++;
        symbol -= 1 << count;
        count++;
      }
      numBins++;
      numBins += count;
      assert(numBins <= 32);
      return numBins;
    }
    
    uint32_t IntraSearch::getTruncBinBits(uint32_t symbol, uint32_t maxSymbol)
    {
      uint32_t idxCodeBit = 0;
      uint32_t thresh;
      if (maxSymbol > 256)
      {
        uint32_t threshVal = 1 << 8;
        thresh = 8;
        while (threshVal <= maxSymbol)
        {
          thresh++;
          threshVal <<= 1;
        }
        thresh--;
      }
      else
      {
        thresh = g_tbMax[maxSymbol];
      }
      uint32_t uiVal = 1 << thresh;
      assert(uiVal <= maxSymbol);
      assert((uiVal << 1) > maxSymbol);
      assert(symbol < maxSymbol);
      uint32_t b = maxSymbol - uiVal;
      assert(b < uiVal);
      if (symbol < uiVal - b)
      {
        idxCodeBit = thresh;
      }
      else
      {
        idxCodeBit = thresh + 1;
      }
      return idxCodeBit;
    }
    
    void IntraSearch::initTBCTable(int bitDepth)
    {
      for (uint32_t i = 0; i < m_symbolSize; i++)
      {
        memset(m_truncBinBits[i], 0, sizeof(uint16_t)*(m_symbolSize + 1));
      }
      for (uint32_t i = 0; i < (m_symbolSize + 1); i++)
      {
        for (uint32_t j = 0; j < i; j++)
        {
          m_truncBinBits[j][i] = getTruncBinBits(j, i);
        }
      }
      memset(m_escapeNumBins, 0, sizeof(uint16_t)*m_symbolSize);
      for (uint32_t i = 0; i < m_symbolSize; i++)
      {
        m_escapeNumBins[i] = getEpExGolombNumBins(i, 3);
      }
    }
    #else
    
    void IntraSearch::deriveRunAndCalcBits(CodingStructure& cs, Partitioner& partitioner, ComponentID compBegin, uint32_t numComp, PLTScanMode pltScanMode, uint64_t& minBits)
    
      CodingUnit    &cu = *cs.getCU(partitioner.chType);
    
      TransformUnit &tu = *cs.getTU(partitioner.chType);
    
      uint32_t height = cu.block(compBegin).height;
      uint32_t width = cu.block(compBegin).width;
      Pel  *runLength = tu.getRunLens (compBegin);
    
      bool *runType   = tu.getRunTypes(compBegin);
    
      cu.useRotation[compBegin] = (pltScanMode == PLT_SCAN_VERTRAV);
    
    Yung-Hsuan Chao (Jessie)'s avatar
    Yung-Hsuan Chao (Jessie) committed
      m_scanOrder = g_scanOrder[SCAN_UNGROUPED][(cu.useRotation[compBegin]) ? SCAN_TRAV_VER : SCAN_TRAV_HOR][gp_sizeIdxInfo->idxFrom(width)][gp_sizeIdxInfo->idxFrom(height)];
    
      deriveRun(cs, partitioner, compBegin);
    
      m_CABACEstimator->getCtx() = PLTCtx(m_orgCtxRD);
      m_CABACEstimator->resetBits();
      CUCtx cuCtx;
      cuCtx.isDQPCoded = true;
      cuCtx.isChromaQpAdjCoded = true;
      m_CABACEstimator->cu_palette_info(cu, compBegin, numComp, cuCtx);
    
      uint64_t bitsTemp = m_CABACEstimator->getEstFracBits();
      if (minBits > bitsTemp)
    
    Yung-Hsuan Chao (Jessie)'s avatar
    Yung-Hsuan Chao (Jessie) committed
        m_bestScanRotationMode = pltScanMode;
    
        memcpy(m_runTypeRD, runType, sizeof(bool)*width*height);
        memcpy(m_runLengthRD, runLength, sizeof(Pel)*width*height);
        minBits = bitsTemp;
    
    void IntraSearch::deriveRun(CodingStructure& cs, Partitioner& partitioner, ComponentID compBegin)
    
      CodingUnit    &cu = *cs.getCU(partitioner.chType);
    
      TransformUnit &tu = *cs.getTU(partitioner.chType);
    
      uint32_t height = cu.block(compBegin).height;
      uint32_t width = cu.block(compBegin).width;
      uint32_t total = height * width, idx = 0;
      uint32_t startPos = 0;
    
      uint64_t indexBits = 0, runBitsIndex = 0, runBitsCopy = 0;
    
    Yung-Hsuan Chao (Jessie)'s avatar
    Yung-Hsuan Chao (Jessie) committed
      m_storeCtxRun = PLTCtx(m_orgCtxRD);
    
    
      PLTtypeBuf  runType = tu.getrunType(compBegin);
      PelBuf      runLength = tu.getrunLength(compBegin);
    
      while (idx < total)
    
        startPos = idx;
        double aveBitsPerPix[NUM_PLT_RUN];
        uint32_t indexRun = 0;
        bool runValid = calIndexRun(cs, partitioner, startPos, total, indexRun, compBegin);
    
    Yung-Hsuan Chao (Jessie)'s avatar
    Yung-Hsuan Chao (Jessie) committed
        m_CABACEstimator->getCtx() = PLTCtx(m_storeCtxRun);
    
        aveBitsPerPix[PLT_RUN_INDEX] = runValid ? getRunBits(cu, indexRun, startPos, PLT_RUN_INDEX, &indexBits, &runBitsIndex, compBegin) : MAX_DOUBLE;
    
    Yung-Hsuan Chao (Jessie)'s avatar
    Yung-Hsuan Chao (Jessie) committed
        m_storeCtxRunIndex = PLTCtx(m_CABACEstimator->getCtx());
    
        uint32_t copyRun = 0;
        bool copyValid = calCopyRun(cs, partitioner, startPos, total, copyRun, compBegin);
    
    Yung-Hsuan Chao (Jessie)'s avatar
    Yung-Hsuan Chao (Jessie) committed
        m_CABACEstimator->getCtx() = PLTCtx(m_storeCtxRun);
    
        aveBitsPerPix[PLT_RUN_COPY] = copyValid ? getRunBits(cu, copyRun, startPos, PLT_RUN_COPY, &indexBits, &runBitsCopy, compBegin) : MAX_DOUBLE;
    
    Yung-Hsuan Chao (Jessie)'s avatar
    Yung-Hsuan Chao (Jessie) committed
        m_storeCtxRunCopy = PLTCtx(m_CABACEstimator->getCtx());
    
        if (copyValid == 0 && runValid == 0)
    
          if (aveBitsPerPix[PLT_RUN_COPY] <= aveBitsPerPix[PLT_RUN_INDEX])
    
            for (int runidx = 0; runidx <copyRun; runidx++)
    
    Yung-Hsuan Chao (Jessie)'s avatar
    Yung-Hsuan Chao (Jessie) committed
              uint32_t posy = m_scanOrder[idx + runidx].y;
              uint32_t posx = m_scanOrder[idx + runidx].x;
    
              runType.at(posx, posy) = PLT_RUN_COPY;
    
              runLength.at(posx, posy) = copyRun;
    
    Yung-Hsuan Chao (Jessie)'s avatar
    Yung-Hsuan Chao (Jessie) committed
            m_storeCtxRun = PLTCtx(m_storeCtxRunCopy);
    
            for (int runidx = 0; runidx <indexRun; runidx++)
    
    Yung-Hsuan Chao (Jessie)'s avatar
    Yung-Hsuan Chao (Jessie) committed
              uint32_t posy = m_scanOrder[idx + runidx].y;
              uint32_t posx = m_scanOrder[idx + runidx].x;
    
              runType.at(posx, posy) = PLT_RUN_INDEX;
    
              runLength.at(posx, posy) = indexRun;
    
    Yung-Hsuan Chao (Jessie)'s avatar
    Yung-Hsuan Chao (Jessie) committed
            m_storeCtxRun = PLTCtx(m_storeCtxRunIndex);
    
      assert(idx == total);
    
    double IntraSearch::getRunBits(const CodingUnit&  cu, uint32_t run, uint32_t strPos, PLTRunMode paletteRunMode, uint64_t* indexBits, uint64_t* runBits, ComponentID compBegin)
    
      TransformUnit&   tu = *cu.firstTU;
    
      uint32_t height = cu.block(compBegin).height;
      uint32_t width  = cu.block(compBegin).width;
      uint32_t endPos = height*width;
      PLTtypeBuf runType   = tu.getrunType(compBegin);
      PelBuf     curPLTIdx = tu.getcurPLTIdx(compBegin);
      uint32_t   indexMaxSize = (cu.useEscape[compBegin]) ? (cu.curPLTSize[compBegin] + 1) : cu.curPLTSize[compBegin];
    
    
      m_CABACEstimator->resetBits();
      ///////////////// encode Run Type
    
    Yung-Hsuan Chao (Jessie)'s avatar
    Yung-Hsuan Chao (Jessie) committed
      m_CABACEstimator->encodeRunType(cu, runType, strPos, m_scanOrder, compBegin);
    
      uint64_t runTypeBits = m_CABACEstimator->getEstFracBits();
    
      uint32_t curLevel = 0;
      switch (paletteRunMode)
      {
      case PLT_RUN_INDEX:
    
        curLevel = m_CABACEstimator->writePLTIndex(cu, strPos, curPLTIdx, runType, indexMaxSize, compBegin);
        *indexBits = m_CABACEstimator->getEstFracBits() - runTypeBits;
    
        m_CABACEstimator->cu_run_val(run - 1, PLT_RUN_INDEX, curLevel, endPos - strPos - 1);
    
        *runBits = m_CABACEstimator->getEstFracBits() - runTypeBits - (*indexBits);
    
        break;
      case PLT_RUN_COPY:
        m_CABACEstimator->cu_run_val(run - 1, PLT_RUN_COPY, curLevel, endPos - strPos - 1);
    
        *runBits = m_CABACEstimator->getEstFracBits() - runTypeBits;
    
      double costPerPixel = (double)m_CABACEstimator->getEstFracBits() / (double)run;
      return costPerPixel;
    
    void IntraSearch::preCalcPLTIndex(CodingStructure& cs, Partitioner& partitioner, ComponentID compBegin, uint32_t numComp)
    
      CodingUnit &cu = *cs.getCU(partitioner.chType);
      TransformUnit &tu = *cs.getTU(partitioner.chType);
      const int  channelBitDepth_L = cs.sps->getBitDepth(CHANNEL_TYPE_LUMA);
      const int  channelBitDepth_C = cs.sps->getBitDepth(CHANNEL_TYPE_CHROMA);
      const int  pcmShiftRight_L = (channelBitDepth_L - PLT_ENCBITDEPTH);
      const int  pcmShiftRight_C = (channelBitDepth_C - PLT_ENCBITDEPTH);
    
    
      uint32_t height = cu.block(compBegin).height;
      uint32_t width = cu.block(compBegin).width;
    
    
      CPelBuf   orgBuf[3];
      for (int comp = compBegin; comp < (compBegin + numComp); comp++)
      {
        CompArea  area = cu.blocks[comp];
        if (m_pcEncCfg->getReshaper() && (cs.slice->getLmcsEnabledFlag() && m_pcReshape->getCTUFlag()))
        {
          orgBuf[comp] = cs.getPredBuf(area);
        }
        else
        {
          orgBuf[comp] = cs.getOrgBuf(area);
        }
      }
    
      PelBuf   curPLTIdx = tu.getcurPLTIdx(compBegin);
    
    Yung-Hsuan Chao (Jessie)'s avatar
    Yung-Hsuan Chao (Jessie) committed
      int      errorLimit = numComp * g_paletteQuant[cu.qp];
    
      uint32_t bestIdx = 0;
    
      uint32_t scaleX = getComponentScaleX(COMPONENT_Cb, cs.sps->getChromaFormatIdc());
      uint32_t scaleY = getComponentScaleY(COMPONENT_Cb, cs.sps->getChromaFormatIdc());
    
      for (uint32_t y = 0; y < height; y++)
    
        for (uint32_t x = 0; x < width; x++)
    
          uint32_t pltIdx = 0;
          uint32_t minError = MAX_UINT;
          while (pltIdx < cu.curPLTSize[compBegin])
    
            uint32_t absError = 0, pX, pY;
    
            for (int comp = compBegin; comp < (compBegin + numComp); comp++)
            {
    
              pX = (comp > 0 && compBegin == COMPONENT_Y) ? (x >> scaleX) : x;
              pY = (comp > 0 && compBegin == COMPONENT_Y) ? (y >> scaleY) : y;
    
    #if JVET_P0526_PLT_ENCODER
              if (isChroma((ComponentID) comp))
              {
                absError += int(double(abs(cu.curPLT[comp][pltIdx] - orgBuf[comp].at(pX, pY))) * PLT_CHROMA_WEIGHTING) >> pcmShiftRight_C;
              }
              else
              {
                absError += abs(cu.curPLT[comp][pltIdx] - orgBuf[comp].at(pX, pY)) >> pcmShiftRight_L;
              }
    #else
    
              int shift = (comp > 0) ? pcmShiftRight_C : pcmShiftRight_L;
    
              absError += abs(cu.curPLT[comp][pltIdx] - orgBuf[comp].at(pX, pY)) >> shift;
    
            if (absError < minError)
    
              bestIdx = pltIdx;
              minError = absError;
              if (minError == 0)
    
          curPLTIdx.at(x, y) = bestIdx;
          if (minError > errorLimit)
    
            curPLTIdx.at(x, y) = cu.curPLTSize[compBegin];
    
            cu.useEscape[compBegin] = true;
    
            calcPixelPred(cs, partitioner, y, x, compBegin, numComp);
    
    void IntraSearch::calcPixelPred(CodingStructure& cs, Partitioner& partitioner, uint32_t yPos, uint32_t xPos, ComponentID compBegin, uint32_t numComp)
    
      CodingUnit    &cu = *cs.getCU(partitioner.chType);
    
      TransformUnit &tu = *cs.getTU(partitioner.chType);
    
      CPelBuf   orgBuf[3];
      for (int comp = compBegin; comp < (compBegin + numComp); comp++)
      {
        CompArea  area = cu.blocks[comp];
    
    Brian Heng's avatar
    Brian Heng committed
    #if JVET_P1006_PICTURE_HEADER
        if (m_pcEncCfg->getReshaper() && (cs.picHeader->getLmcsEnabledFlag() && m_pcReshape->getCTUFlag()))
    #else
    
        if (m_pcEncCfg->getReshaper() && (cs.slice->getLmcsEnabledFlag() && m_pcReshape->getCTUFlag()))
    
    Brian Heng's avatar
    Brian Heng committed
    #endif
    
        {
          orgBuf[comp] = cs.getPredBuf(area);
        }
        else
        {
          orgBuf[comp] = cs.getOrgBuf(area);
        }
      }
    
    
      int qp[3];
      int qpRem[3];
      int qpPer[3];
    
      int quantiserScale[3];
      int quantiserRightShift[3];
      int rightShiftOffset[3];
    
      int invquantiserRightShift[3];
    
      for (uint32_t ch = compBegin; ch < (compBegin + numComp); ch++)
      {
        QpParam cQP(tu, ComponentID(ch));
    
    #if JVET_P0460_PLT_TS_MIN_QP
        qp[ch] = cQP.Qp(true);
    #else
    
        qp[ch] = cQP.Qp(false);
    
        qpRem[ch] = qp[ch] % 6;
        qpPer[ch] = qp[ch] / 6;
        quantiserScale[ch] = g_quantScales[0][qpRem[ch]];
        quantiserRightShift[ch] = QUANT_SHIFT + qpPer[ch];
    
        rightShiftOffset[ch] = 1 << (quantiserRightShift[ch] - 1);
    
        invquantiserRightShift[ch] = IQUANT_SHIFT;
        add[ch] = 1 << (invquantiserRightShift[ch] - 1);
    
      }
    
      uint32_t scaleX = getComponentScaleX(COMPONENT_Cb, cs.sps->getChromaFormatIdc());
      uint32_t scaleY = getComponentScaleY(COMPONENT_Cb, cs.sps->getChromaFormatIdc());
      for (uint32_t ch = compBegin; ch < (compBegin + numComp); ch++)
      {
    
        const int channelBitDepth = cu.cs->sps->getBitDepth(toChannelType((ComponentID)ch));
    
        CompArea  area = cu.blocks[ch];
        PelBuf    recBuf = cs.getRecoBuf(area);
    
        PLTescapeBuf escapeValue = tu.getescapeValue((ComponentID)ch);
    
        if (compBegin != COMPONENT_Y || ch == 0)
        {
    
          escapeValue.at(xPos, yPos) = TCoeff(std::max<int>(0, ((orgBuf[ch].at(xPos, yPos) * quantiserScale[ch] + rightShiftOffset[ch]) >> quantiserRightShift[ch])));
          assert(escapeValue.at(xPos, yPos) < (1 << (channelBitDepth + 1)));
    
          recBuf.at(xPos, yPos) = (((escapeValue.at(xPos, yPos)*g_invQuantScales[0][qpRem[ch]]) << qpPer[ch]) + add[ch]) >> invquantiserRightShift[ch];
    
          recBuf.at(xPos, yPos) = Pel(ClipBD<int>(recBuf.at(xPos, yPos), channelBitDepth));//to be checked
    
        else if (compBegin == COMPONENT_Y && ch > 0 && yPos % (1 << scaleY) == 0 && xPos % (1 << scaleX) == 0)
    
          uint32_t yPosC = yPos >> scaleY;
          uint32_t xPosC = xPos >> scaleX;
          escapeValue.at(xPosC, yPosC) = TCoeff(std::max<int>(0, ((orgBuf[ch].at(xPosC, yPosC) * quantiserScale[ch] + rightShiftOffset[ch]) >> quantiserRightShift[ch])));
          assert(escapeValue.at(xPosC, yPosC) < (1 << (channelBitDepth + 1)));
    
          recBuf.at(xPosC, yPosC) = (((escapeValue.at(xPosC, yPosC)*g_invQuantScales[0][qpRem[ch]]) << qpPer[ch]) + add[ch]) >> invquantiserRightShift[ch];
    
          recBuf.at(xPosC, yPosC) = Pel(ClipBD<int>(recBuf.at(xPosC, yPosC), channelBitDepth));//to be checked
    
    void IntraSearch::derivePLTLossy(CodingStructure& cs, Partitioner& partitioner, ComponentID compBegin, uint32_t numComp)
    
      CodingUnit &cu = *cs.getCU(partitioner.chType);
      const int channelBitDepth_L = cs.sps->getBitDepth(CHANNEL_TYPE_LUMA);
      const int channelBitDepth_C = cs.sps->getBitDepth(CHANNEL_TYPE_CHROMA);
      const int pcmShiftRight_L = (channelBitDepth_L - PLT_ENCBITDEPTH);
      const int pcmShiftRight_C = (channelBitDepth_C - PLT_ENCBITDEPTH);
    
    
      uint32_t height = cu.block(compBegin).height;
      uint32_t width = cu.block(compBegin).width;
    
    
      CPelBuf   orgBuf[3];
      for (int comp = compBegin; comp < (compBegin + numComp); comp++)
      {
        CompArea  area = cu.blocks[comp];
    
    Brian Heng's avatar
    Brian Heng committed
    #if JVET_P1006_PICTURE_HEADER
        if (m_pcEncCfg->getReshaper() && (cs.picHeader->getLmcsEnabledFlag() && m_pcReshape->getCTUFlag()))
    #else
    
        if (m_pcEncCfg->getReshaper() && (cs.slice->getLmcsEnabledFlag() && m_pcReshape->getCTUFlag()))
    
    Brian Heng's avatar
    Brian Heng committed
    #endif
    
        {
          orgBuf[comp] = cs.getPredBuf(area);
        }
        else
        {
          orgBuf[comp] = cs.getOrgBuf(area);
        }
      }
    
    
    Yung-Hsuan Chao (Jessie)'s avatar
    Yung-Hsuan Chao (Jessie) committed
      int errorLimit = g_paletteQuant[cu.qp];
    
      uint32_t totalSize = height*width;
      SortingElement *pelList = new SortingElement[totalSize];
      SortingElement  element;
      SortingElement *pelListSort = new SortingElement[MAXPLTSIZE + 1];
    
      uint32_t dictMaxSize = MAXPLTSIZE;
    
      int last = -1;
    
      uint32_t scaleX = getComponentScaleX(COMPONENT_Cb, cs.sps->getChromaFormatIdc());
      uint32_t scaleY = getComponentScaleY(COMPONENT_Cb, cs.sps->getChromaFormatIdc());
    
      for (uint32_t y = 0; y < height; y++)
    
        for (uint32_t x = 0; x < width; x++)
    
          uint32_t org[3], pX, pY;
    
          for (int comp = compBegin; comp < (compBegin + numComp); comp++)
          {
    
            pX = (comp > 0 && compBegin == COMPONENT_Y) ? (x >> scaleX) : x;
            pY = (comp > 0 && compBegin == COMPONENT_Y) ? (y >> scaleY) : y;
            org[comp] = orgBuf[comp].at(pX, pY);
    
          element.setAll(org, compBegin, numComp);
          int besti = last, bestSAD = (last == -1) ? MAX_UINT : pelList[last].getSAD(element, cs.sps->getBitDepths(), compBegin, numComp);
    
            for (int i = idx - 1; i >= 0; i--)
    
              uint32_t sad = pelList[i].getSAD(element, cs.sps->getBitDepths(), compBegin, numComp);
    
              if (sad < bestSAD)
              {
                bestSAD = sad;
                besti = i;
                if (!sad) break;
              }
            }
          }
    
          if (besti >= 0 && pelList[besti].almostEqualData(element, errorLimit, cs.sps->getBitDepths(), compBegin, numComp))
    
            pelList[besti].addElement(element, compBegin, numComp);
    
            pelList[idx].copyDataFrom(element, compBegin, numComp);
    
      for (int i = 0; i < dictMaxSize; i++)
    
        pelListSort[i].resetAll(compBegin, numComp);
    
      dictMaxSize = 1;
      for (int i = 0; i < idx; i++)
    
        if (pelList[i].getCnt() > pelListSort[dictMaxSize - 1].getCnt())
    
          for (j = dictMaxSize; j > 0; j--)
    
            if (pelList[i].getCnt() > pelListSort[j - 1].getCnt() )
    
              pelListSort[j].copyAllFrom(pelListSort[j - 1], compBegin, numComp);
              dictMaxSize = std::min(dictMaxSize + 1, (uint32_t)MAXPLTSIZE);
    
          pelListSort[j].copyAllFrom(pelList[i], compBegin, numComp);
    
      uint32_t paletteSize = 0;
    
      uint64_t numColorBits = 0;
      for (int comp = compBegin; comp < (compBegin + numComp); comp++)
      {
        numColorBits += (comp > 0) ? channelBitDepth_C : channelBitDepth_L;
      }
    
    #if JVET_P0526_PLT_ENCODER
      const int plt_lambda_shift = (compBegin > 0) ? pcmShiftRight_C : pcmShiftRight_L;
      double    bitCost          = m_pcRdCost->getLambda() / (double) (1 << (2 * plt_lambda_shift)) * numColorBits;
    #else
    
      double bitCost = m_pcRdCost->getLambda()*numColorBits;
    
      for (int i = 0; i < MAXPLTSIZE; i++)
      {
    
          for (int comp = compBegin; comp < (compBegin + numComp); comp++)
          {
    
    Yung-Hsuan Chao (Jessie)'s avatar
    Yung-Hsuan Chao (Jessie) committed
            cu.curPLT[comp][paletteSize] = (pelListSort[i].getSumData(comp) + half) / pelListSort[i].getCnt();
    
          {
            double pal[MAX_NUM_COMPONENT], err = 0.0, bestCost = 0.0;
            for (int comp = compBegin; comp < (compBegin + numComp); comp++)
            {
    
    #if !JVET_P0526_PLT_ENCODER
    
              const int shift = (comp > 0) ? pcmShiftRight_C : pcmShiftRight_L;
    
    Yung-Hsuan Chao (Jessie)'s avatar
    Yung-Hsuan Chao (Jessie) committed
              pal[comp] = pelListSort[i].getSumData(comp) / (double)pelListSort[i].getCnt();
    
              err = pal[comp] - cu.curPLT[comp][paletteSize];
    
    #if JVET_P0526_PLT_ENCODER
              if (isChroma((ComponentID) comp))
              {
                bestCost += (err * err * PLT_CHROMA_WEIGHTING) / (1 << (2 * pcmShiftRight_C));
              }
              else
              {
                bestCost += (err * err) / (1 << (2 * pcmShiftRight_L));
              }
    #else
    
              bestCost += (err*err) / (1 << (2 * shift));
    
            bestCost = bestCost * pelListSort[i].getCnt() + bitCost;
    
    
            for (int t = 0; t < cs.prevPLT.curPLTSize[compBegin]; t++)
            {
              double cost = 0.0;
              for (int comp = compBegin; comp < (compBegin + numComp); comp++)
              {
    
    #if !JVET_P0526_PLT_ENCODER
    
                const int shift = (comp > 0) ? pcmShiftRight_C : pcmShiftRight_L;
    
                err = pal[comp] - cs.prevPLT.curPLT[comp][t];
    
    #if JVET_P0526_PLT_ENCODER
                if (isChroma((ComponentID) comp))
                {
                  cost += (err * err * PLT_CHROMA_WEIGHTING) / (1 << (2 * pcmShiftRight_C));
                }
                else
                {
                  cost += (err * err) / (1 << (2 * pcmShiftRight_L));
                }
    #else
    
                cost += (err*err) / (1 << (2 * shift));
    
              if (cost < bestCost)
              {
                best = t;
                bestCost = cost;
              }
            }
            if (best != -1)
            {
              for (int comp = compBegin; comp < (compBegin + numComp); comp++)
              {
    
                cu.curPLT[comp][paletteSize] = cs.prevPLT.curPLT[comp][best];
    
          bool duplicate = false;
    
            for (int t = 0; t<paletteSize; t++)
    
              bool duplicateTmp = true;
    
              for (int comp = compBegin; comp < (compBegin + numComp); comp++)
              {
    
                duplicateTmp = duplicateTmp && (cu.curPLT[comp][paletteSize] == cu.curPLT[comp][t]);
    
          if (!duplicate) paletteSize++;