Skip to content
Snippets Groups Projects
EncSlice.cpp 72.2 KiB
Newer Older
  • Learn to ignore specific revisions
  • 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 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 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 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 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 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 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
    /* 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     EncSlice.cpp
        \brief    slice encoder class
    */
    
    #include "EncSlice.h"
    
    #include "EncLib.h"
    #include "CommonLib/UnitTools.h"
    #include "CommonLib/Picture.h"
    
    #if ENABLE_WPP_PARALLELISM
    #include <mutex>
    extern recursive_mutex g_cache_mutex;
    #endif
    
    #include <math.h>
    
    //! \ingroup EncoderLib
    //! \{
    
    // ====================================================================================================================
    // Constructor / destructor / create / destroy
    // ====================================================================================================================
    
    EncSlice::EncSlice()
     : m_encCABACTableIdx(I_SLICE)
    {
    }
    
    EncSlice::~EncSlice()
    {
      destroy();
    }
    
    void EncSlice::create( int iWidth, int iHeight, ChromaFormat chromaFormat, uint32_t iMaxCUWidth, uint32_t iMaxCUHeight, uint8_t uhTotalDepth )
    {
    }
    
    void EncSlice::destroy()
    {
      // free lambda and QP arrays
      m_vdRdPicLambda.clear();
      m_vdRdPicQp.clear();
      m_viRdPicQp.clear();
    }
    
    void EncSlice::init( EncLib* pcEncLib, const SPS& sps )
    {
      m_pcCfg             = pcEncLib;
      m_pcLib             = pcEncLib;
      m_pcListPic         = pcEncLib->getListPic();
    
      m_pcGOPEncoder      = pcEncLib->getGOPEncoder();
      m_pcCuEncoder       = pcEncLib->getCuEncoder();
      m_pcInterSearch     = pcEncLib->getInterSearch();
      m_CABACWriter       = pcEncLib->getCABACEncoder()->getCABACWriter   (&sps);
      m_CABACEstimator    = pcEncLib->getCABACEncoder()->getCABACEstimator(&sps);
      m_pcTrQuant         = pcEncLib->getTrQuant();
      m_pcRdCost          = pcEncLib->getRdCost();
    
      // create lambda and QP arrays
      m_vdRdPicLambda.resize(m_pcCfg->getDeltaQpRD() * 2 + 1 );
      m_vdRdPicQp.resize(    m_pcCfg->getDeltaQpRD() * 2 + 1 );
      m_viRdPicQp.resize(    m_pcCfg->getDeltaQpRD() * 2 + 1 );
      m_pcRateCtrl        = pcEncLib->getRateCtrl();
    }
    
    void
    EncSlice::setUpLambda( Slice* slice, const double dLambda, int iQP)
    {
      // store lambda
      m_pcRdCost ->setLambda( dLambda, slice->getSPS()->getBitDepths() );
    
      // for RDO
      // in RdCost there is only one lambda because the luma and chroma bits are not separated, instead we weight the distortion of chroma.
      double dLambdas[MAX_NUM_COMPONENT] = { dLambda };
      for( uint32_t compIdx = 1; compIdx < MAX_NUM_COMPONENT; compIdx++ )
      {
        const ComponentID compID = ComponentID( compIdx );
        int chromaQPOffset       = slice->getPPS()->getQpOffset( compID ) + slice->getSliceChromaQpDelta( compID );
        int qpc                  = ( iQP + chromaQPOffset < 0 ) ? iQP : getScaledChromaQP( iQP + chromaQPOffset, m_pcCfg->getChromaFormatIdc() );
        double tmpWeight         = pow( 2.0, ( iQP - qpc ) / 3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
    #if JVET_K0072
        if( m_pcCfg->getDepQuantEnabledFlag() )
        {
          tmpWeight *= ( m_pcCfg->getGOPSize() >= 8 ? pow( 2.0, 0.1/3.0 ) : pow( 2.0, 0.2/3.0 ) );  // increase chroma weight for dependent quantization (in order to reduce bit rate shift from chroma to luma)
        }
    #endif
        m_pcRdCost->setDistortionWeight( compID, tmpWeight );
    #if ENABLE_WPP_PARALLELISM
        for( int jId = 1; jId < ( m_pcLib->getNumWppThreads() + m_pcLib->getNumWppExtraLines() ); jId++ )
        {
          m_pcLib->getRdCost( slice->getPic()->scheduler.getWppDataId( jId ) )->setDistortionWeight( compID, tmpWeight );
        }
    #endif
        dLambdas[compIdx] = dLambda / tmpWeight;
      }
    
    #if RDOQ_CHROMA_LAMBDA
      // for RDOQ
      m_pcTrQuant->setLambdas( dLambdas );
    #else
      m_pcTrQuant->setLambda( dLambda );
    #endif
    
      // for SAO
      slice->setLambdas( dLambdas );
    }
    
    
    
    /**
     - non-referenced frame marking
     - QP computation based on temporal structure
     - lambda computation based on QP
     - set temporal layer ID and the parameter sets
     .
     \param pcPic         picture class
     \param pocLast       POC of last picture
     \param pocCurr       current POC
     \param iNumPicRcvd   number of received pictures
     \param iGOPid        POC offset for hierarchical structure
     \param rpcSlice      slice header class
     \param isField       true for field coding
     */
    
    void EncSlice::initEncSlice( Picture* pcPic, const int pocLast, const int pocCurr, const int iGOPid, Slice*& rpcSlice, const bool isField )
    {
      double dQP;
      double dLambda;
    
      rpcSlice = pcPic->slices[0];
      rpcSlice->setSliceBits(0);
      rpcSlice->setPic( pcPic );
      rpcSlice->initSlice();
      rpcSlice->setPicOutputFlag( true );
      rpcSlice->setPOC( pocCurr );
    #if JVET_K0072
      rpcSlice->setDepQuantEnabledFlag( m_pcCfg->getDepQuantEnabledFlag() );
    #if HEVC_USE_SIGN_HIDING
      rpcSlice->setSignDataHidingEnabledFlag( m_pcCfg->getSignDataHidingEnabledFlag() );
    #endif
    #endif
    
    #if SHARP_LUMA_DELTA_QP
      pcPic->fieldPic = isField;
      m_gopID = iGOPid;
    #endif
    
      // depth computation based on GOP size
      int depth;
      {
        int poc = rpcSlice->getPOC();
        if(isField)
        {
          poc = (poc/2) % (m_pcCfg->getGOPSize()/2);
        }
        else
        {
          poc = poc % m_pcCfg->getGOPSize();
        }
    
        if ( poc == 0 )
        {
          depth = 0;
        }
        else
        {
          int step = m_pcCfg->getGOPSize();
          depth    = 0;
          for( int i=step>>1; i>=1; i>>=1 )
          {
            for ( int j=i; j<m_pcCfg->getGOPSize(); j+=step )
            {
              if ( j == poc )
              {
                i=0;
                break;
              }
            }
            step >>= 1;
            depth++;
          }
        }
    
        if(m_pcCfg->getHarmonizeGopFirstFieldCoupleEnabled() && poc != 0)
        {
          if (isField && ((rpcSlice->getPOC() % 2) == 1))
          {
            depth++;
          }
        }
      }
    
      // slice type
      SliceType eSliceType;
    
      eSliceType=B_SLICE;
      if(!(isField && pocLast == 1) || !m_pcCfg->getEfficientFieldIRAPEnabled())
      {
        if(m_pcCfg->getDecodingRefreshType() == 3)
        {
          eSliceType = (pocLast == 0 || pocCurr % m_pcCfg->getIntraPeriod() == 0             || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
        }
        else
        {
          eSliceType = (pocLast == 0 || (pocCurr - (isField ? 1 : 0)) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
        }
      }
    
      rpcSlice->setSliceType    ( eSliceType );
    
      // ------------------------------------------------------------------------------------------------------------------
      // Non-referenced frame marking
      // ------------------------------------------------------------------------------------------------------------------
    
      if(pocLast == 0)
      {
        rpcSlice->setTemporalLayerNonReferenceFlag(false);
      }
      else
      {
        rpcSlice->setTemporalLayerNonReferenceFlag(!m_pcCfg->getGOPEntry(iGOPid).m_refPic);
      }
      pcPic->referenced = true;
    
      // ------------------------------------------------------------------------------------------------------------------
      // QP setting
      // ------------------------------------------------------------------------------------------------------------------
    
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
      dQP = m_pcCfg->getQPForPicture(iGOPid, rpcSlice);
    #else
      dQP = m_pcCfg->getBaseQP();
      if(eSliceType!=I_SLICE)
      {
    #if SHARP_LUMA_DELTA_QP
        if (!(( m_pcCfg->getMaxDeltaQP() == 0) && (!m_pcCfg->getLumaLevelToDeltaQPMapping().isEnabled()) && (dQP == -rpcSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA) ) && (rpcSlice->getPPS()->getTransquantBypassEnabledFlag())))
    #else
        if (!(( m_pcCfg->getMaxDeltaQP() == 0 ) && (dQP == -rpcSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA) ) && (rpcSlice->getPPS()->getTransquantBypassEnabledFlag())))
    #endif
        {
          dQP += m_pcCfg->getGOPEntry(iGOPid).m_QPOffset;
        }
      }
    
      // modify QP
      const int* pdQPs = m_pcCfg->getdQPs();
      if ( pdQPs )
      {
        dQP += pdQPs[ rpcSlice->getPOC() ];
      }
    
      if (m_pcCfg->getCostMode()==COST_LOSSLESS_CODING)
      {
        dQP=LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP;
        m_pcCfg->setDeltaQpRD(0);
      }
    #endif
    
      // ------------------------------------------------------------------------------------------------------------------
      // Lambda computation
      // ------------------------------------------------------------------------------------------------------------------
    
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
      const int temporalId=m_pcCfg->getGOPEntry(iGOPid).m_temporalId;
    #if !SHARP_LUMA_DELTA_QP
      const std::vector<double> &intraLambdaModifiers=m_pcCfg->getIntraLambdaModifier();
    #endif
    #endif
      int iQP;
      double dOrigQP = dQP;
    
      // pre-compute lambda and QP values for all possible QP candidates
      for ( int iDQpIdx = 0; iDQpIdx < 2 * m_pcCfg->getDeltaQpRD() + 1; iDQpIdx++ )
      {
        // compute QP value
        dQP = dOrigQP + ((iDQpIdx+1)>>1)*(iDQpIdx%2 ? -1 : 1);
    #if SHARP_LUMA_DELTA_QP
        dLambda = calculateLambda(rpcSlice, iGOPid, depth, dQP, dQP, iQP );
    #else
        // compute lambda value
        int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
        int    SHIFT_QP = 12;
    
    #if DISTORTION_LAMBDA_BUGFIX
        int    bitdepth_luma_qp_scale =
          6
          * (rpcSlice->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) - 8
             - DISTORTION_PRECISION_ADJUSTMENT(rpcSlice->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA)));
    #else
    #if FULL_NBIT
        int    bitdepth_luma_qp_scale = 6 * (rpcSlice->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) - 8);
    #else
        int    bitdepth_luma_qp_scale = 0;
    #endif
    #endif
        double qp_temp = (double) dQP + bitdepth_luma_qp_scale - SHIFT_QP;
    #if FULL_NBIT
        double qp_temp_orig = (double) dQP - SHIFT_QP;
    #endif
        // Case #1: I or P-slices (key-frame)
        double dQPFactor = m_pcCfg->getGOPEntry(iGOPid).m_QPFactor;
        if ( eSliceType==I_SLICE )
        {
          if (m_pcCfg->getIntraQpFactor()>=0.0 && m_pcCfg->getGOPEntry(iGOPid).m_sliceType != I_SLICE)
          {
            dQPFactor=m_pcCfg->getIntraQpFactor();
          }
          else
          {
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
            if(m_pcCfg->getLambdaFromQPEnable())
            {
              dQPFactor=0.57;
            }
            else
            {
    #endif
            double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(double)(isField ? NumberBFrames/2 : NumberBFrames) );
    
            dQPFactor=0.57*dLambda_scale;
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
            }
    #endif
          }
        }
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
        else if( m_pcCfg->getLambdaFromQPEnable() )
        {
          dQPFactor=0.57;
        }
    #endif
    
        dLambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
    
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
        if(!m_pcCfg->getLambdaFromQPEnable() && depth>0)
    #else
        if ( depth>0 )
    #endif
        {
    #if FULL_NBIT
            dLambda *= Clip3( 2.00, 4.00, (qp_temp_orig / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
    #else
            dLambda *= Clip3( 2.00, 4.00, (qp_temp / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
    #endif
        }
    
        // if hadamard is used in ME process
        if ( !m_pcCfg->getUseHADME() && rpcSlice->getSliceType( ) != I_SLICE )
        {
          dLambda *= 0.95;
        }
    
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
        double lambdaModifier;
        if( rpcSlice->getSliceType( ) != I_SLICE || intraLambdaModifiers.empty())
        {
          lambdaModifier = m_pcCfg->getLambdaModifier( temporalId );
        }
        else
        {
          lambdaModifier = intraLambdaModifiers[ (temporalId < intraLambdaModifiers.size()) ? temporalId : (intraLambdaModifiers.size()-1) ];
        }
        dLambda *= lambdaModifier;
    #endif
    
        iQP = max( -rpcSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), min( MAX_QP, (int) floor( dQP + 0.5 ) ) );
    #endif
    
        m_vdRdPicLambda[iDQpIdx] = dLambda;
        m_vdRdPicQp    [iDQpIdx] = dQP;
        m_viRdPicQp    [iDQpIdx] = iQP;
      }
    
      // obtain dQP = 0 case
      dLambda = m_vdRdPicLambda[0];
      dQP     = m_vdRdPicQp    [0];
      iQP     = m_viRdPicQp    [0];
    
    #if !X0038_LAMBDA_FROM_QP_CAPABILITY
      const int temporalId=m_pcCfg->getGOPEntry(iGOPid).m_temporalId;
      const std::vector<double> &intraLambdaModifiers=m_pcCfg->getIntraLambdaModifier();
    #endif
    
    #if W0038_CQP_ADJ
      if(rpcSlice->getPPS()->getSliceChromaQpFlag())
      {
        const bool bUseIntraOrPeriodicOffset = rpcSlice->getSliceType()==I_SLICE || (m_pcCfg->getSliceChromaOffsetQpPeriodicity()!=0 && (rpcSlice->getPOC()%m_pcCfg->getSliceChromaOffsetQpPeriodicity())==0);
        int cbQP = bUseIntraOrPeriodicOffset? m_pcCfg->getSliceChromaOffsetQpIntraOrPeriodic(false) : m_pcCfg->getGOPEntry(iGOPid).m_CbQPoffset;
        int crQP = bUseIntraOrPeriodicOffset? m_pcCfg->getSliceChromaOffsetQpIntraOrPeriodic(true)  : m_pcCfg->getGOPEntry(iGOPid).m_CrQPoffset;
    
        cbQP = Clip3( -12, 12, cbQP + rpcSlice->getPPS()->getQpOffset(COMPONENT_Cb) ) - rpcSlice->getPPS()->getQpOffset(COMPONENT_Cb);
        crQP = Clip3( -12, 12, crQP + rpcSlice->getPPS()->getQpOffset(COMPONENT_Cr) ) - rpcSlice->getPPS()->getQpOffset(COMPONENT_Cr);
        rpcSlice->setSliceChromaQpDelta(COMPONENT_Cb, Clip3( -12, 12, cbQP));
        CHECK(!(rpcSlice->getSliceChromaQpDelta(COMPONENT_Cb)+rpcSlice->getPPS()->getQpOffset(COMPONENT_Cb)<=12 && rpcSlice->getSliceChromaQpDelta(COMPONENT_Cb)+rpcSlice->getPPS()->getQpOffset(COMPONENT_Cb)>=-12), "Unspecified error");
        rpcSlice->setSliceChromaQpDelta(COMPONENT_Cr, Clip3( -12, 12, crQP));
        CHECK(!(rpcSlice->getSliceChromaQpDelta(COMPONENT_Cr)+rpcSlice->getPPS()->getQpOffset(COMPONENT_Cr)<=12 && rpcSlice->getSliceChromaQpDelta(COMPONENT_Cr)+rpcSlice->getPPS()->getQpOffset(COMPONENT_Cr)>=-12), "Unspecified error");
      }
      else
      {
        rpcSlice->setSliceChromaQpDelta( COMPONENT_Cb, 0 );
        rpcSlice->setSliceChromaQpDelta( COMPONENT_Cr, 0 );
      }
    #endif
    
    #if !X0038_LAMBDA_FROM_QP_CAPABILITY
      double lambdaModifier;
      if( rpcSlice->getSliceType( ) != I_SLICE || intraLambdaModifiers.empty())
      {
        lambdaModifier = m_pcCfg->getLambdaModifier( temporalId );
      }
      else
      {
        lambdaModifier = intraLambdaModifiers[ (temporalId < intraLambdaModifiers.size()) ? temporalId : (intraLambdaModifiers.size()-1) ];
      }
    
      dLambda *= lambdaModifier;
    #endif
    
      setUpLambda(rpcSlice, dLambda, iQP);
      
    #if WCG_EXT
      // cost = Distortion + Lambda*R,
      // when QP is adjusted by luma, distortion is changed, so we have to adjust lambda to match the distortion, then the cost function becomes
      // costA = Distortion + AdjustedLambda * R          -- currently, costA is still used when calculating intermediate cost of using SAD, HAD, resisual etc.
      // an alternative way is to weight the distortion to before the luma QP adjustment, then the cost function becomes
      // costB = weightedDistortion + Lambda * R          -- currently, costB is used to calculat final cost, and when DF_FUNC is DF_DEFAULT
      m_pcRdCost->saveUnadjustedLambda();
    #endif
    
      if (m_pcCfg->getFastMEForGenBLowDelayEnabled())
      {
        // restore original slice type
    
        if(!(isField && pocLast == 1) || !m_pcCfg->getEfficientFieldIRAPEnabled())
        {
          if(m_pcCfg->getDecodingRefreshType() == 3)
          {
            eSliceType = (pocLast == 0 || (pocCurr)                     % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
          }
          else
          {
            eSliceType = (pocLast == 0 || (pocCurr - (isField ? 1 : 0)) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
          }
        }
    
        rpcSlice->setSliceType        ( eSliceType );
      }
    
      if (m_pcCfg->getUseRecalculateQPAccordingToLambda())
      {
        dQP = xGetQPValueAccordingToLambda( dLambda );
        iQP = max( -rpcSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), min( MAX_QP, (int) floor( dQP + 0.5 ) ) );
      }
    
      rpcSlice->setSliceQp           ( iQP );
      rpcSlice->setSliceQpDelta      ( 0 );
    #if !W0038_CQP_ADJ
      rpcSlice->setSliceChromaQpDelta( COMPONENT_Cb, 0 );
      rpcSlice->setSliceChromaQpDelta( COMPONENT_Cr, 0 );
    #endif
      rpcSlice->setUseChromaQpAdj( rpcSlice->getPPS()->getPpsRangeExtension().getChromaQpOffsetListEnabledFlag() );
      rpcSlice->setNumRefIdx(REF_PIC_LIST_0,m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive);
      rpcSlice->setNumRefIdx(REF_PIC_LIST_1,m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive);
    
      if ( m_pcCfg->getDeblockingFilterMetric() )
      {
        rpcSlice->setDeblockingFilterOverrideFlag(true);
        rpcSlice->setDeblockingFilterDisable(false);
        rpcSlice->setDeblockingFilterBetaOffsetDiv2( 0 );
        rpcSlice->setDeblockingFilterTcOffsetDiv2( 0 );
      }
      else if (rpcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
      {
        rpcSlice->setDeblockingFilterOverrideFlag( rpcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag() );
        rpcSlice->setDeblockingFilterDisable( rpcSlice->getPPS()->getPPSDeblockingFilterDisabledFlag() );
        if ( !rpcSlice->getDeblockingFilterDisable())
        {
          if ( rpcSlice->getDeblockingFilterOverrideFlag() && eSliceType!=I_SLICE)
          {
            rpcSlice->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getGOPEntry(iGOPid).m_betaOffsetDiv2 + m_pcCfg->getLoopFilterBetaOffset()  );
            rpcSlice->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getGOPEntry(iGOPid).m_tcOffsetDiv2 + m_pcCfg->getLoopFilterTcOffset() );
          }
          else
          {
            rpcSlice->setDeblockingFilterBetaOffsetDiv2( m_pcCfg->getLoopFilterBetaOffset() );
            rpcSlice->setDeblockingFilterTcOffsetDiv2( m_pcCfg->getLoopFilterTcOffset() );
          }
        }
      }
      else
      {
        rpcSlice->setDeblockingFilterOverrideFlag( false );
        rpcSlice->setDeblockingFilterDisable( false );
        rpcSlice->setDeblockingFilterBetaOffsetDiv2( 0 );
        rpcSlice->setDeblockingFilterTcOffsetDiv2( 0 );
      }
    
      rpcSlice->setDepth            ( depth );
    
      pcPic->layer =  temporalId;
      if(eSliceType==I_SLICE)
      {
        pcPic->layer = 0;
      }
      rpcSlice->setTLayer( pcPic->layer );
    
      rpcSlice->setSliceMode            ( m_pcCfg->getSliceMode()            );
      rpcSlice->setSliceArgument        ( m_pcCfg->getSliceArgument()        );
    #if HEVC_DEPENDENT_SLICES
      rpcSlice->setSliceSegmentMode     ( m_pcCfg->getSliceSegmentMode()     );
      rpcSlice->setSliceSegmentArgument ( m_pcCfg->getSliceSegmentArgument() );
    #endif
      rpcSlice->setMaxNumMergeCand      ( m_pcCfg->getMaxNumMergeCand()      );
      rpcSlice->setMaxBTSize            ( rpcSlice->isIntra() ? MAX_BT_SIZE : MAX_BT_SIZE_INTER );
    }
    
    
    #if SHARP_LUMA_DELTA_QP
    double EncSlice::calculateLambda( const Slice*     slice,
                                      const int        GOPid, // entry in the GOP table
                                      const int        depth, // slice GOP hierarchical depth.
                                      const double     refQP, // initial slice-level QP
                                      const double     dQP,   // initial double-precision QP
                                            int       &iQP )  // returned integer QP.
    {
      enum   SliceType eSliceType    = slice->getSliceType();
      const  bool      isField       = slice->getPic()->fieldPic;
      const  int       NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
      const  int       SHIFT_QP      = 12;
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
      const int temporalId=m_pcCfg->getGOPEntry(GOPid).m_temporalId;
      const std::vector<double> &intraLambdaModifiers=m_pcCfg->getIntraLambdaModifier();
    #endif
    
    #if DISTORTION_LAMBDA_BUGFIX
      int bitdepth_luma_qp_scale = 6
                                   * (slice->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) - 8
                                      - DISTORTION_PRECISION_ADJUSTMENT(slice->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA)));
    #else
    #if FULL_NBIT
      int    bitdepth_luma_qp_scale = 6 * (slice->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) - 8);
    #else
      int    bitdepth_luma_qp_scale = 0;
    #endif
    #endif
      double qp_temp = dQP + bitdepth_luma_qp_scale - SHIFT_QP;
      // Case #1: I or P-slices (key-frame)
      double dQPFactor = m_pcCfg->getGOPEntry(GOPid).m_QPFactor;
      if ( eSliceType==I_SLICE )
      {
        if (m_pcCfg->getIntraQpFactor()>=0.0 && m_pcCfg->getGOPEntry(GOPid).m_sliceType != I_SLICE)
        {
          dQPFactor=m_pcCfg->getIntraQpFactor();
        }
        else
        {
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
          if(m_pcCfg->getLambdaFromQPEnable())
          {
            dQPFactor=0.57;
          }
          else
          {
    #endif
            double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(double)(isField ? NumberBFrames/2 : NumberBFrames) );
            dQPFactor=0.57*dLambda_scale;
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
          }
    #endif
        }
      }
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
      else if( m_pcCfg->getLambdaFromQPEnable() )
      {
        dQPFactor=0.57;
      }
    #endif
    
      double dLambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
    
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
      if( !(m_pcCfg->getLambdaFromQPEnable()) && depth>0 )
    #else
      if ( depth>0 )
    #endif
      {
    #if DISTORTION_LAMBDA_BUGFIX
        double qp_temp_ref = refQP + bitdepth_luma_qp_scale - SHIFT_QP;
        dLambda *= Clip3(2.00, 4.00, (qp_temp_ref / 6.0));   // (j == B_SLICE && p_cur_frm->layer != 0 )
    #else
    #if FULL_NBIT
          double qp_temp_ref_orig = refQP - SHIFT_QP;
          dLambda *= Clip3( 2.00, 4.00, (qp_temp_ref_orig / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
    #else
          double qp_temp_ref = refQP + bitdepth_luma_qp_scale - SHIFT_QP;
          dLambda *= Clip3( 2.00, 4.00, (qp_temp_ref / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
    #endif
    #endif
      }
    
      // if hadamard is used in ME process
      if ( !m_pcCfg->getUseHADME() && slice->getSliceType( ) != I_SLICE )
      {
        dLambda *= 0.95;
      }
    
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
      double lambdaModifier;
      if( eSliceType != I_SLICE || intraLambdaModifiers.empty())
      {
        lambdaModifier = m_pcCfg->getLambdaModifier( temporalId );
      }
      else
      {
        lambdaModifier = intraLambdaModifiers[ (temporalId < intraLambdaModifiers.size()) ? temporalId : (intraLambdaModifiers.size()-1) ];
      }
      dLambda *= lambdaModifier;
    #endif
    
      iQP = max( -slice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), min( MAX_QP, (int) floor( dQP + 0.5 ) ) );
    
    #if JVET_K0072
      if( m_pcCfg->getDepQuantEnabledFlag() )
      {
        dLambda *= pow( 2.0, 0.25/3.0 ); // slight lambda adjustment for dependent quantization (due to different slope of quantizer)
      }
    #endif
    
      // NOTE: the lambda modifiers that are sometimes applied later might be best always applied in here.
      return dLambda;
    }
    #endif
    
    void EncSlice::resetQP( Picture* pic, int sliceQP, double lambda )
    {
      Slice* slice = pic->slices[0];
    
      // store lambda
      slice->setSliceQp( sliceQP );
      setUpLambda(slice, lambda, sliceQP);
    }
    
    #if ENABLE_QPA
    static inline int apprI2Log2 (const double d)
    {
      return d < 6.0e-20 ? -128 : int(floor(2.0 * log(d) / log(2.0) + 0.5));
    }
    
    #ifndef HLM_L1_NORM
      #define HLM_L1_NORM
    #endif
    
    static int filterAndCalculateAverageEnergies (const Pel* pSrc,     const int  iSrcStride,
                                                  double &hpEner,      const int  iHeight,    const int iWidth,
                                                  const int  iPOC = 0)
    {
      int iHpValue;
      uint32_t uHpERow, uHpEner = 0;
    
      // skip first row as there may be a black border frame
      pSrc += iSrcStride;
      // center rows
      for (int y = 1; y < iHeight - 1; y++)
      {
        uHpERow = 0;
        // skip column as there may be a black border frame
    
        for (int x = 1; x < iWidth - 1; x++) // and columns
        {
          iHpValue = 4 * (int)pSrc[x] - (int)pSrc[x-1] - (int)pSrc[x+1] - (int)pSrc[x-iSrcStride] - (int)pSrc[x+iSrcStride];
    #ifdef HLM_L1_NORM
          uHpERow += abs (iHpValue);
    #else
          uHpERow += iHpValue * iHpValue;
    #endif
        }
        // skip column as there may be a black border frame
    #ifdef HLM_L1_NORM
        uHpEner += uHpERow;
    #else
        uHpEner += (uHpERow + 64) >> 7; // avoids overflows
    #endif
        pSrc += iSrcStride;
      }
      // skip last row as there may be a black border frame
    
      hpEner = double(uHpEner) / double((iWidth - 2) * (iHeight - 2));
    #ifdef HLM_L1_NORM
      hpEner *= hpEner;
    #endif
      // lower limit, compensate for highpass amplification
      if (hpEner < 64.0) hpEner = 64.0;
    
      if (iPOC  <= 0) return 0;
      return 1; // OK
    }
    
    #ifdef HLM_L1_NORM
      #undef HLM_L1_NORM
    #endif
    
    #if ENABLE_QPA
    static bool applyQPAdaptation (Picture* const pcPic, Slice* const pcSlice,    const PreCalcValues& pcv,
                                   const uint32_t startAddr, const uint32_t boundingAddr, const bool useSharpLumaDQP,
                                   const int gopSize,    const double hpEnerAvg,  const double hpEnerMax)
    {
      const int  iBitDepth   = pcSlice->getSPS()->getBitDepth (CHANNEL_TYPE_LUMA);
      const int  iQPIndex    = pcSlice->getSliceQp(); // initial QP index for current slice, used in following loops
    #if HEVC_TILES_WPP
      const TileMap& tileMap = *pcPic->tileMap;
    #endif
      bool   sliceQPModified = false;
      double hpEnerPic = 1.0 / (1.5 * double(1 << iBitDepth)); // speedup: multiply instead of divide in loops below
    
      if (pcv.lumaWidth > 2048 && pcv.lumaHeight > 1280) // for UHD/4K
      {
        hpEnerPic *= 1.5;
      }
    
      if ((pcPic->getPOC() & 1) && (iQPIndex >= MAX_QP))
      {
        int iQPFixed = Clip3 (0, MAX_QP, iQPIndex + ((apprI2Log2 (hpEnerAvg * hpEnerPic) + apprI2Log2 (hpEnerMax * hpEnerPic) + 1) >> 1)); // adapted slice QP = (mean(QP) + max(QP)) / 2
    #if SHARP_LUMA_DELTA_QP
    
        // change new fixed QP based on average CTU luma value (Sharp)
        if (useSharpLumaDQP)
        {
          uint64_t uAvgLuma = 0;
    
          for (uint32_t ctuTsAddr = startAddr; ctuTsAddr < boundingAddr; ctuTsAddr++)
          {
    #if HEVC_TILES_WPP
            const uint32_t ctuRsAddr = tileMap.getCtuTsToRsAddrMap (ctuTsAddr);
    #else
            const uint32_t ctuRsAddr = ctuTsAddr;
    #endif
    
            uAvgLuma += (uint64_t)pcPic->m_iOffsetCtu[ctuRsAddr];
          }
          uAvgLuma = (uAvgLuma + ((boundingAddr - startAddr) >> 1)) / (boundingAddr - startAddr);
    
          iQPFixed = Clip3 (0, MAX_QP, iQPFixed + 1 - int((3 * uAvgLuma * uAvgLuma) >> uint64_t(2 * iBitDepth - 1)));
        }
    #endif
    
        if (iQPFixed < iQPIndex) iQPFixed = iQPIndex;
        else
        if (iQPFixed > iQPIndex)
        {
          const double* oldLambdas = pcSlice->getLambdas();
          const double  corrFactor = pow (2.0, double(iQPFixed - iQPIndex) / 3.0);
          const double  newLambdas[MAX_NUM_COMPONENT] = {oldLambdas[0] * corrFactor, oldLambdas[1] * corrFactor, oldLambdas[2] * corrFactor};
    
          CHECK (iQPIndex != pcSlice->getSliceQpBase(), "Invalid slice QP!");
          pcSlice->setLambdas (newLambdas);
          pcSlice->setSliceQp (iQPFixed); // update the slice/base QPs
          pcSlice->setSliceQpBase (iQPFixed);
    
          sliceQPModified = true;
        }
    
        for (uint32_t ctuTsAddr = startAddr; ctuTsAddr < boundingAddr; ctuTsAddr++)
        {
    #if HEVC_TILES_WPP
          const uint32_t ctuRsAddr = tileMap.getCtuTsToRsAddrMap (ctuTsAddr);
    #else
          const uint32_t ctuRsAddr = ctuTsAddr;
    #endif
    
          pcPic->m_iOffsetCtu[ctuRsAddr] = (Pel)iQPFixed; // fixed QPs
        }
      }
      else
      {
        for (uint32_t ctuTsAddr = startAddr; ctuTsAddr < boundingAddr; ctuTsAddr++)
        {
    #if HEVC_TILES_WPP
          const uint32_t ctuRsAddr = tileMap.getCtuTsToRsAddrMap (ctuTsAddr);
    #else
          const uint32_t ctuRsAddr = ctuTsAddr;
    #endif
    
          int iQPAdapt = Clip3 (0, MAX_QP, iQPIndex + apprI2Log2 (pcPic->m_uEnerHpCtu[ctuRsAddr] * hpEnerPic));
    
    #if SHARP_LUMA_DELTA_QP
          if ((pcv.widthInCtus > 1) && (gopSize > 1)) // try to enforce CTU SNR greater than zero dB
    #else
          if ((!pcSlice->isIntra()) && (gopSize > 1)) // try to enforce CTU SNR greater than zero dB
    #endif
          {
            const Pel      dcOffset   = pcPic->m_iOffsetCtu[ctuRsAddr];
    #if SHARP_LUMA_DELTA_QP
    
            // change adaptive QP based on mean CTU luma value (Sharp)
            if (useSharpLumaDQP)
            {
              const uint64_t uAvgLuma   = (uint64_t)dcOffset;
    
              iQPAdapt = max (0, iQPAdapt + 1 - int((3 * uAvgLuma * uAvgLuma) >> uint64_t(2 * iBitDepth - 1)));
            }
    
    #endif
            const uint32_t     uRefScale  = g_invQuantScales[iQPAdapt % 6] << ((iQPAdapt / 6) + iBitDepth - (pcSlice->isIntra() ? 4 : 3));
            const CompArea subArea    = clipArea (CompArea (COMPONENT_Y, pcPic->chromaFormat, Area ((ctuRsAddr % pcv.widthInCtus) * pcv.maxCUWidth, (ctuRsAddr / pcv.widthInCtus) * pcv.maxCUHeight, pcv.maxCUWidth, pcv.maxCUHeight)), pcPic->Y());
            const Pel*     pSrc       = pcPic->getOrigBuf (subArea).buf;
            const SizeType iSrcStride = pcPic->getOrigBuf (subArea).stride;
            const SizeType iSrcHeight = pcPic->getOrigBuf (subArea).height;
            const SizeType iSrcWidth  = pcPic->getOrigBuf (subArea).width;
            uint32_t uAbsDCless = 0;
    
            // compute sum of absolute DC-less (high-pass) luma values
            for (SizeType h = 0; h < iSrcHeight; h++)
            {
              for (SizeType w = 0; w < iSrcWidth; w++)
              {
                uAbsDCless += (uint32_t)abs (pSrc[w] - dcOffset);
              }
              pSrc += iSrcStride;
            }
    
            if (iSrcHeight >= 64 || iSrcWidth >= 64)  // normalization
            {
              const uint64_t blockSize = uint64_t(iSrcWidth * iSrcHeight);
    
              uAbsDCless = uint32_t((uint64_t(uAbsDCless) * 64*64 + (blockSize >> 1)) / blockSize);
            }
    
            if (uAbsDCless < 64*64) uAbsDCless = 64*64;  // limit to 1
    
            // reduce QP index if CTU would be fully quantized to zero
            if (uAbsDCless < uRefScale)
            {
              const int limit  = min (0, ((iQPIndex + 4) >> 3) - 6);
              const int redVal = max (limit, apprI2Log2 ((double)uAbsDCless / (double)uRefScale));
    
              iQPAdapt = max (0, iQPAdapt + redVal);
            }
    #if SHARP_LUMA_DELTA_QP
    
            if (iQPAdapt > MAX_QP) iQPAdapt = MAX_QP;
    #endif
          }
    
          pcPic->m_iOffsetCtu[ctuRsAddr] = (Pel)iQPAdapt; // adapted QPs
    
          if ((pcv.widthInCtus > 1) && (gopSize > 1)) // try to reduce local bitrate peaks via minimum smoothing
          {
            iQPAdapt = ctuRsAddr % pcv.widthInCtus; // horizontal offset
            if (iQPAdapt == 0)
            {
              iQPAdapt = (ctuRsAddr > 1) ? pcPic->m_iOffsetCtu[ctuRsAddr - 2] : 0;
            }
            else // iQPAdapt >= 1
            {
              iQPAdapt = (iQPAdapt > 1) ? min (pcPic->m_iOffsetCtu[ctuRsAddr - 2], pcPic->m_iOffsetCtu[ctuRsAddr]) : pcPic->m_iOffsetCtu[ctuRsAddr];
            }
            if (ctuRsAddr > pcv.widthInCtus)
            {
              iQPAdapt = min (iQPAdapt, (int)pcPic->m_iOffsetCtu[ctuRsAddr - 1 - pcv.widthInCtus]); // min(L, T)
            }
            if ((ctuRsAddr > 0) && (pcPic->m_iOffsetCtu[ctuRsAddr - 1] < (Pel)iQPAdapt))
            {
              pcPic->m_iOffsetCtu[ctuRsAddr - 1] = (Pel)iQPAdapt;
            }
            if ((ctuTsAddr == boundingAddr - 1) && (ctuRsAddr > pcv.widthInCtus)) // last CTU in the given slice
            {
              iQPAdapt = min (pcPic->m_iOffsetCtu[ctuRsAddr - 1], pcPic->m_iOffsetCtu[ctuRsAddr - pcv.widthInCtus]);
              if (pcPic->m_iOffsetCtu[ctuRsAddr] < (Pel)iQPAdapt)
              {
                pcPic->m_iOffsetCtu[ctuRsAddr] = (Pel)iQPAdapt;
              }
            }
          }
        } // end iteration over all CTUs in current slice
      }
    
      return sliceQPModified;
    }
    #endif // ENABLE_QPA
    
    #endif // ENABLE_QPA || ENABLE_PRIVATE
    
    // ====================================================================================================================
    // Public member functions
    // ====================================================================================================================
    
    //! set adaptive search range based on poc difference
    void EncSlice::setSearchRange( Slice* pcSlice )
    {
      int iCurrPOC = pcSlice->getPOC();
      int iRefPOC;
      int iGOPSize = m_pcCfg->getGOPSize();
      int iOffset = (iGOPSize >> 1);
      int iMaxSR = m_pcCfg->getSearchRange();
      int iNumPredDir = pcSlice->isInterP() ? 1 : 2;
    
      for (int iDir = 0; iDir < iNumPredDir; iDir++)
      {
        RefPicList  e = ( iDir ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
        for (int iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(e); iRefIdx++)
        {
          iRefPOC = pcSlice->getRefPic(e, iRefIdx)->getPOC();
          int newSearchRange = Clip3(m_pcCfg->getMinSearchWindow(), iMaxSR, (iMaxSR*ADAPT_SR_SCALE*abs(iCurrPOC - iRefPOC)+iOffset)/iGOPSize);
          m_pcInterSearch->setAdaptiveSearchRange(iDir, iRefIdx, newSearchRange);
    #if ENABLE_WPP_PARALLELISM
          for( int jId = 1; jId < m_pcLib->getNumCuEncStacks(); jId++ )
          {
            m_pcLib->getInterSearch( jId )->setAdaptiveSearchRange( iDir, iRefIdx, newSearchRange );
          }
    #endif
        }
      }
    }
    
    /**
     Multi-loop slice encoding for different slice QP
    
     \param pcPic    picture class
     */
    void EncSlice::precompressSlice( Picture* pcPic )
    {
      // if deltaQP RD is not used, simply return
      if ( m_pcCfg->getDeltaQpRD() == 0 )
      {
        return;
      }
    
      if ( m_pcCfg->getUseRateCtrl() )
      {
        THROW("\nMultiple QP optimization is not allowed when rate control is enabled." );
      }
    
      Slice* pcSlice        = pcPic->slices[getSliceSegmentIdx()];
    
    #if HEVC_DEPENDENT_SLICES
      if (pcSlice->getDependentSliceSegmentFlag())
      {
        // if this is a dependent slice segment, then it was optimised
        // when analysing the entire slice.
        return;
      }
    #endif
    
      if (pcSlice->getSliceMode()==FIXED_NUMBER_OF_BYTES)
      {
        // TODO: investigate use of average cost per CTU so that this Slice Mode can be used.
        THROW( "Unable to optimise Slice-level QP if Slice Mode is set to FIXED_NUMBER_OF_BYTES\n" );
      }
    
      double     dPicRdCostBest = MAX_DOUBLE;
      uint32_t       uiQpIdxBest = 0;
    
      double dFrameLambda;
    #if DISTORTION_LAMBDA_BUGFIX
      int SHIFT_QP = 12
                     + 6
                         * (pcSlice->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) - 8
                            - DISTORTION_PRECISION_ADJUSTMENT(pcSlice->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA)));
    #else
    #if FULL_NBIT
      int    SHIFT_QP = 12 + 6 * (pcSlice->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) - 8);
    #else
      int    SHIFT_QP = 12;
    #endif