Skip to content
Snippets Groups Projects
EncGOP.cpp 145 KiB
Newer Older
  • Learn to ignore specific revisions
  • 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 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 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
            }
          }
        }
      }
    }
    
    int EfficientFieldIRAPMapping::adjustGOPid(const int GOPid)
    {
      if(IRAPtoReorder)
      {
        if(swapIRAPForward)
        {
          if(GOPid == IRAPGOPid)
          {
            return IRAPGOPid +1;
          }
          else if(GOPid == IRAPGOPid +1)
          {
            return IRAPGOPid;
          }
        }
        else
        {
          if(GOPid == IRAPGOPid -1)
          {
            return IRAPGOPid;
          }
          else if(GOPid == IRAPGOPid)
          {
            return IRAPGOPid -1;
          }
        }
      }
      return GOPid;
    }
    
    int EfficientFieldIRAPMapping::restoreGOPid(const int GOPid)
    {
      if(IRAPtoReorder)
      {
        if(swapIRAPForward)
        {
          if(GOPid == IRAPGOPid)
          {
            IRAPtoReorder = false;
            return IRAPGOPid +1;
          }
          else if(GOPid == IRAPGOPid +1)
          {
            return GOPid -1;
          }
        }
        else
        {
          if(GOPid == IRAPGOPid)
          {
            return IRAPGOPid -1;
          }
          else if(GOPid == IRAPGOPid -1)
          {
            IRAPtoReorder = false;
            return IRAPGOPid;
          }
        }
      }
      return GOPid;
    }
    
    
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
    static uint32_t calculateCollocatedFromL0Flag(const Slice *pSlice)
    {
      const int refIdx = 0; // Zero always assumed
      const Picture *refPicL0 = pSlice->getRefPic(REF_PIC_LIST_0, refIdx);
      const Picture *refPicL1 = pSlice->getRefPic(REF_PIC_LIST_1, refIdx);
      return refPicL0->slices[0]->getSliceQp() > refPicL1->slices[0]->getSliceQp();
    }
    #else
    static uint32_t calculateCollocatedFromL1Flag(EncCfg *pCfg, const int GOPid, const int gopSize)
    {
      int iCloseLeft=1, iCloseRight=-1;
      for(int i = 0; i<pCfg->getGOPEntry(GOPid).m_numRefPics; i++)
      {
        int iRef = pCfg->getGOPEntry(GOPid).m_referencePics[i];
        if(iRef>0&&(iRef<iCloseRight||iCloseRight==-1))
        {
          iCloseRight=iRef;
        }
        else if(iRef<0&&(iRef>iCloseLeft||iCloseLeft==1))
        {
          iCloseLeft=iRef;
        }
      }
      if(iCloseRight>-1)
      {
        iCloseRight=iCloseRight+pCfg->getGOPEntry(GOPid).m_POC-1;
      }
      if(iCloseLeft<1)
      {
        iCloseLeft=iCloseLeft+pCfg->getGOPEntry(GOPid).m_POC-1;
        while(iCloseLeft<0)
        {
          iCloseLeft+=gopSize;
        }
      }
      int iLeftQP=0, iRightQP=0;
      for(int i=0; i<gopSize; i++)
      {
        if(pCfg->getGOPEntry(i).m_POC==(iCloseLeft%gopSize)+1)
        {
          iLeftQP= pCfg->getGOPEntry(i).m_QPOffset;
        }
        if (pCfg->getGOPEntry(i).m_POC==(iCloseRight%gopSize)+1)
        {
          iRightQP=pCfg->getGOPEntry(i).m_QPOffset;
        }
      }
      if(iCloseRight>-1&&iRightQP<iLeftQP)
      {
        return 0;
      }
      else
      {
        return 1;
      }
    }
    #endif
    
    
    static void
    printHash(const HashType hashType, const std::string &digestStr)
    {
      const char *decodedPictureHashModeName;
      switch (hashType)
      {
        case HASHTYPE_MD5:
          decodedPictureHashModeName = "MD5";
          break;
        case HASHTYPE_CRC:
          decodedPictureHashModeName = "CRC";
          break;
        case HASHTYPE_CHECKSUM:
          decodedPictureHashModeName = "Checksum";
          break;
        default:
          decodedPictureHashModeName = NULL;
          break;
      }
      if (decodedPictureHashModeName != NULL)
      {
        if (digestStr.empty())
        {
          msg( NOTICE, " [%s:%s]", decodedPictureHashModeName, "?");
        }
        else
        {
          msg( NOTICE, " [%s:%s]", decodedPictureHashModeName, digestStr.c_str());
        }
      }
    }
    
    bool isPicEncoded( int targetPoc, int curPoc, int curTLayer, int gopSize, int intraPeriod )
    {
      int  tarGop = targetPoc / gopSize;
      int  curGop = curPoc / gopSize;
    
      if( tarGop + 1 == curGop )
      {
        // part of next GOP only for tl0 pics
        return curTLayer == 0;
      }
    
      int  tarIFr = ( targetPoc / intraPeriod ) * intraPeriod;
      int  curIFr = ( curPoc / intraPeriod ) * intraPeriod;
    
      if( curIFr != tarIFr )
      {
        return false;
      }
    
      int  tarId = targetPoc - tarGop * gopSize;
    
      if( tarGop > curGop )
      {
        return ( tarId == 0 ) ? ( 0 == curTLayer ) : ( 1 >= curTLayer );
      }
    
      if( tarGop + 1 < curGop )
      {
        return false;
      }
    
      int  curId = curPoc - curGop * gopSize;
      int  tarTL = 0;
    
      while( tarId != 0 )
      {
        gopSize /= 2;
        if( tarId >= gopSize )
        {
          tarId -= gopSize;
          if( curId != 0 ) curId -= gopSize;
        }
        else if( curId == gopSize )
        {
          curId = 0;
        }
        tarTL++;
      }
    
      return curTLayer <= tarTL && curId == 0;
    }
    
    void trySkipOrDecodePicture( bool& decPic, bool& encPic, const EncCfg& cfg, Picture* pcPic )
    {
      // check if we should decode a leading bitstream
      if( !cfg.getDecodeBitstream( 0 ).empty() )
      {
        static bool bDecode1stPart = true; /* TODO: MT */
        if( bDecode1stPart )
        {
          if( cfg.getForceDecodeBitstream1() )
          {
            if( ( bDecode1stPart = tryDecodePicture( pcPic, pcPic->getPOC(), cfg.getDecodeBitstream( 0 ), false ) ) )
            {
              decPic = bDecode1stPart;
            }
          }
          else
          {
            // update decode decision
            if( ( bDecode1stPart = ( cfg.getSwitchPOC() != pcPic->getPOC() )) && ( bDecode1stPart = tryDecodePicture( pcPic, pcPic->getPOC(), cfg.getDecodeBitstream( 0 ), false ) ) )
            {
              decPic = bDecode1stPart;
              return;
            }
            else if( pcPic->getPOC() )
            {
              // reset decoder if used and not required any further
              tryDecodePicture( NULL, 0, std::string( "" ) );
            }
          }
        }
    
        encPic |= cfg.getForceDecodeBitstream1() && !decPic;
        if( cfg.getForceDecodeBitstream1() ) { return; }
      }
    
    
      // check if we should decode a trailing bitstream
      if( ! cfg.getDecodeBitstream(1).empty() )
      {
        const int  iNextKeyPOC    = (1+cfg.getSwitchPOC()  / cfg.getGOPSize())     *cfg.getGOPSize();
        const int  iNextIntraPOC  = (1+(cfg.getSwitchPOC() / cfg.getIntraPeriod()))*cfg.getIntraPeriod();
        const int  iRestartIntraPOC   = iNextIntraPOC + (((iNextKeyPOC == iNextIntraPOC) && cfg.getSwitchDQP() ) ? cfg.getIntraPeriod() : 0);
    
        bool bDecode2ndPart = (pcPic->getPOC() >= iRestartIntraPOC);
        int expectedPoc = pcPic->getPOC();
        Slice slice0;
        if ( cfg.getBs2ModPOCAndType() )
        {
          expectedPoc = pcPic->getPOC() - iRestartIntraPOC;
          slice0.copySliceInfo( pcPic->slices[ 0 ], false );
        }
        if( bDecode2ndPart && (bDecode2ndPart = tryDecodePicture( pcPic, expectedPoc, cfg.getDecodeBitstream(1), true )) )
        {
          decPic = bDecode2ndPart;
          if ( cfg.getBs2ModPOCAndType() )
          {
            for( int i = 0; i < pcPic->slices.size(); i++ )
            {
              pcPic->slices[ i ]->setPOC              ( slice0.getPOC()            );
              if ( pcPic->slices[ i ]->getNalUnitType() != slice0.getNalUnitType()
                  && pcPic->slices[ i ]->getIdrPicFlag()
                  && slice0.getRapPicFlag()
                  && slice0.isIntra() )
              {
                // patch IDR-slice to CRA-Intra-slice
                pcPic->slices[ i ]->setNalUnitType    ( slice0.getNalUnitType()    );
                pcPic->slices[ i ]->setLastIDR        ( slice0.getLastIDR()        );
                pcPic->slices[ i ]->setEnableTMVPFlag ( slice0.getEnableTMVPFlag() );
                if ( slice0.getEnableTMVPFlag() )
                {
                  pcPic->slices[ i ]->setColFromL0Flag( slice0.getColFromL0Flag()  );
                  pcPic->slices[ i ]->setColRefIdx    ( slice0.getColRefIdx()      );
                }
              }
            }
          }
          return;
        }
      }
    
      // leave here if we do not use forward to poc
      if( ! cfg.useFastForwardToPOC() )
      {
        // let's encode
        encPic   = true;
        return;
      }
    
      // this is the forward to poc section
      static bool bHitFastForwardPOC = false; /* TODO: MT */
      if( bHitFastForwardPOC || isPicEncoded( cfg.getFastForwardToPOC(), pcPic->getPOC(), pcPic->layer, cfg.getGOPSize(), cfg.getIntraPeriod() ) )
      {
        bHitFastForwardPOC |= cfg.getFastForwardToPOC() == pcPic->getPOC(); // once we hit the poc we continue encoding
    
        if( bHitFastForwardPOC && cfg.getStopAfterFFtoPOC() && cfg.getFastForwardToPOC() != pcPic->getPOC() )
        {
          return;
        }
    
        //except if FastForwardtoPOC is meant to be a SwitchPOC in thist case drop all preceding pictures
        if( bHitFastForwardPOC && ( cfg.getSwitchPOC() == cfg.getFastForwardToPOC() ) && ( cfg.getFastForwardToPOC() > pcPic->getPOC() ) )
        {
          return;
        }
        // let's encode
        encPic   = true;
      }
    }
    
    // ====================================================================================================================
    // Public member functions
    // ====================================================================================================================
    void EncGOP::compressGOP( int iPOCLast, int iNumPicRcvd, PicList& rcListPic,
                              std::list<PelUnitBuf*>& rcListPicYuvRecOut,
    
                              bool isField, bool isTff, const InputColourSpaceConversion snr_conversion, const bool printFrameMSE
                            , bool isEncodeLtRef
    )
    
    {
      // TODO: Split this function up.
    
      Picture*        pcPic = NULL;
      Slice*      pcSlice;
      OutputBitstream  *pcBitstreamRedirect;
      pcBitstreamRedirect = new OutputBitstream;
      AccessUnit::iterator  itLocationToPushSliceHeaderNALU; // used to store location where NALU containing slice header is to be inserted
    
    
      xInitGOP(iPOCLast, iNumPicRcvd, isField
             , isEncodeLtRef
      );
    
    
      m_iNumPicCoded = 0;
      SEIMessages leadingSeiMessages;
      SEIMessages nestedSeiMessages;
      SEIMessages duInfoSeiMessages;
      SEIMessages trailingSeiMessages;
      std::deque<DUData> duData;
      SEIDecodingUnitInfo decodingUnitInfoSEI;
    
      EfficientFieldIRAPMapping effFieldIRAPMap;
      if (m_pcCfg->getEfficientFieldIRAPEnabled())
      {
        effFieldIRAPMap.initialize(isField, m_iGopSize, iPOCLast, iNumPicRcvd, m_iLastIDR, this, m_pcCfg);
      }
    
      // reset flag indicating whether pictures have been encoded
      for ( int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
      {
        m_pcCfg->setEncodedFlag(iGOPid, false);
      }
    
      for ( int iGOPid=0; iGOPid < m_iGopSize; iGOPid++ )
      {
        if (m_pcCfg->getEfficientFieldIRAPEnabled())
        {
          iGOPid=effFieldIRAPMap.adjustGOPid(iGOPid);
        }
    
        //-- For time output for each slice
        auto beforeTime = std::chrono::steady_clock::now();
    
    #if !X0038_LAMBDA_FROM_QP_CAPABILITY
        uint32_t uiColDir = calculateCollocatedFromL1Flag(m_pcCfg, iGOPid, m_iGopSize);
    #endif
    
        /////////////////////////////////////////////////////////////////////////////////////////////////// Initial to start encoding
        int iTimeOffset;
        int pocCurr;
    
        int multipleFactor = m_pcCfg->getUseCompositeRef() ? 2 : 1;
    
    
        if(iPOCLast == 0) //case first frame or first top field
        {
          pocCurr=0;
    
        }
        else if(iPOCLast == 1 && isField) //case first bottom field, just like the first frame, the poc computation is not right anymore, we set the right value
        {
          pocCurr = 1;
          iTimeOffset = 1;
        }
        else
        {
    
          pocCurr = iPOCLast - iNumPicRcvd * multipleFactor + m_pcCfg->getGOPEntry(iGOPid).m_POC - ((isField && m_iGopSize>1) ? 1 : 0);
    
        if (m_pcCfg->getUseCompositeRef() && isEncodeLtRef)
        {
          pocCurr++;
          iTimeOffset--;
        }
        if (pocCurr / multipleFactor >= m_pcCfg->getFramesToBeEncoded())
    
        {
          if (m_pcCfg->getEfficientFieldIRAPEnabled())
          {
            iGOPid=effFieldIRAPMap.restoreGOPid(iGOPid);
          }
          continue;
        }
    
        if( getNalUnitType(pocCurr, m_iLastIDR, isField) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR, isField) == NAL_UNIT_CODED_SLICE_IDR_N_LP )
        {
          m_iLastIDR = pocCurr;
        }
    
        // start a new access unit: create an entry in the list of output access units
        AccessUnit accessUnit;
        xGetBuffer( rcListPic, rcListPicYuvRecOut,
                    iNumPicRcvd, iTimeOffset, pcPic, pocCurr, isField );
    
        // th this is a hot fix for the choma qp control
        if( m_pcEncLib->getWCGChromaQPControl().isEnabled() && m_pcEncLib->getSwitchPOC() != -1 )
        {
          static int usePPS = 0; /* TODO: MT */
          if( pocCurr == m_pcEncLib->getSwitchPOC() )
          {
            usePPS = 1;
          }
          const PPS *pPPS = m_pcEncLib->getPPS(usePPS);
          // replace the pps with a more appropriated one
          pcPic->cs->pps = pPPS;
        }
    
    #if ENABLE_SPLIT_PARALLELISM && ENABLE_WPP_PARALLELISM
        pcPic->scheduler.init( pcPic->cs->pcv->heightInCtus, pcPic->cs->pcv->widthInCtus, m_pcCfg->getNumWppThreads(), m_pcCfg->getNumWppExtraLines(), m_pcCfg->getNumSplitThreads() );
    #elif ENABLE_SPLIT_PARALLELISM
        pcPic->scheduler.init( pcPic->cs->pcv->heightInCtus, pcPic->cs->pcv->widthInCtus, 1                          , 0                             , m_pcCfg->getNumSplitThreads() );
    #elif ENABLE_WPP_PARALLELISM
        pcPic->scheduler.init( pcPic->cs->pcv->heightInCtus, pcPic->cs->pcv->widthInCtus, m_pcCfg->getNumWppThreads(), m_pcCfg->getNumWppExtraLines(), 1                             );
    #endif
        pcPic->createTempBuffers( pcPic->cs->pps->pcv->maxCUWidth );
        pcPic->cs->createCoeffs();
    
        //  Slice data initialization
        pcPic->clearSliceBuffer();
        pcPic->allocateNewSlice();
        m_pcSliceEncoder->setSliceSegmentIdx(0);
    
    
        m_pcSliceEncoder->initEncSlice(pcPic, iPOCLast, pocCurr, iGOPid, pcSlice, isField
          , isEncodeLtRef
        );
    
    
        DTRACE_UPDATE( g_trace_ctx, ( std::make_pair( "poc", pocCurr ) ) );
        DTRACE_UPDATE( g_trace_ctx, ( std::make_pair( "final", 0 ) ) );
    
    #if !SHARP_LUMA_DELTA_QP
        //Set Frame/Field coding
        pcPic->fieldPic = isField;
    #endif
    
    
        int pocBits = pcSlice->getSPS()->getBitsForPOC();
        int pocMask = (1 << pocBits) - 1;
        pcSlice->setLastIDR(m_iLastIDR & ~pocMask);
    
    #if HEVC_DEPENDENT_SLICES
        pcSlice->setSliceSegmentIdx(0);
    #endif
        pcSlice->setIndependentSliceIdx(0);
        //set default slice level flag to the same as SPS level flag
        pcSlice->setLFCrossSliceBoundaryFlag(  pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag()  );
    
        if(pcSlice->getSliceType()==B_SLICE&&m_pcCfg->getGOPEntry(iGOPid).m_sliceType=='P')
        {
          pcSlice->setSliceType(P_SLICE);
        }
        if(pcSlice->getSliceType()==B_SLICE&&m_pcCfg->getGOPEntry(iGOPid).m_sliceType=='I')
        {
          pcSlice->setSliceType(I_SLICE);
        }
    
    Yu Han's avatar
    Yu Han committed
        if (pcSlice->getSliceType() == I_SLICE && pcSlice->getSPS()->getSpsNext().getIBCMode())
    
    Xiaozhong Xu's avatar
    Xiaozhong Xu committed
        {
          pcSlice->setSliceType(P_SLICE);
        }
    
        // Set the nal unit type
        pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR, isField));
        if(pcSlice->getTemporalLayerNonReferenceFlag())
        {
          if (pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_TRAIL_R &&
              !(m_iGopSize == 1 && pcSlice->getSliceType() == I_SLICE))
            // Add this condition to avoid POC issues with encoder_intra_main.cfg configuration (see #1127 in bug tracker)
          {
            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TRAIL_N);
          }
          if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_RADL_R)
          {
            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_RADL_N);
          }
          if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_RASL_R)
          {
            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_RASL_N);
          }
        }
    
        if (m_pcCfg->getEfficientFieldIRAPEnabled())
        {
          if ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA )  // IRAP picture
          {
            m_associatedIRAPType = pcSlice->getNalUnitType();
            m_associatedIRAPPOC = pocCurr;
          }
          pcSlice->setAssociatedIRAPType(m_associatedIRAPType);
          pcSlice->setAssociatedIRAPPOC(m_associatedIRAPPOC);
        }
    
        pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic, m_pcCfg->getEfficientFieldIRAPEnabled());
    
        if (m_pcCfg->getUseCompositeRef() && isEncodeLtRef)
        {
          setUseLTRef(true);
          setPrepareLTRef(false);
          setNewestBgPOC(pocCurr);
          setLastLTRefPoc(pocCurr);
        }
        else if (pcPic->cs->sps->getSpsNext().getUseCompositeRef() && getLastLTRefPoc() >= 0 && getEncodedLTRef()==false && !getPicBg()->getSpliceFull() && (pocCurr - getLastLTRefPoc()) > (m_pcCfg->getFrameRate() * 2))
        {
          setUseLTRef(false);
          setPrepareLTRef(false);
          setEncodedLTRef(true);
          setNewestBgPOC(-1);
          setLastLTRefPoc(-1);
        }
    
        if (pcPic->cs->sps->getSpsNext().getUseCompositeRef() && m_picBg->getSpliceFull() && getUseLTRef())
        {
          m_pcEncLib->selectReferencePictureSet(pcSlice, pocCurr, iGOPid, m_bgPOC);
        }
        else
        {
          m_pcEncLib->selectReferencePictureSet(pcSlice, pocCurr, iGOPid, -1);
        }
    
        if (!m_pcCfg->getEfficientFieldIRAPEnabled())
        {
          if ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
            || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA )  // IRAP picture
          {
            m_associatedIRAPType = pcSlice->getNalUnitType();
            m_associatedIRAPPOC = pocCurr;
          }
          pcSlice->setAssociatedIRAPType(m_associatedIRAPType);
          pcSlice->setAssociatedIRAPPOC(m_associatedIRAPPOC);
        }
    
        if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false, m_iLastRecoveryPicPOC, m_pcCfg->getDecodingRefreshType() == 3) != 0) || (pcSlice->isIRAP())
          || (m_pcCfg->getEfficientFieldIRAPEnabled() && isField && pcSlice->getAssociatedIRAPType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getAssociatedIRAPType() <= NAL_UNIT_CODED_SLICE_CRA && pcSlice->getAssociatedIRAPPOC() == pcSlice->getPOC()+1)
          )
        {
    
          pcSlice->createExplicitReferencePictureSetFromReference(rcListPic, pcSlice->getRPS(), pcSlice->isIRAP(), m_iLastRecoveryPicPOC, m_pcCfg->getDecodingRefreshType() == 3, m_pcCfg->getEfficientFieldIRAPEnabled()
                                                                , isEncodeLtRef, m_pcCfg->getUseCompositeRef()
          );
    
        }
    
        pcSlice->applyReferencePictureSet(rcListPic, pcSlice->getRPS());
    
        if(pcSlice->getTLayer() > 0
          &&  !( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N     // Check if not a leading picture
              || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_R
              || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N
              || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R )
            )
        {
          if(pcSlice->isTemporalLayerSwitchingPoint(rcListPic) || pcSlice->getSPS()->getTemporalIdNestingFlag())
          {
            if(pcSlice->getTemporalLayerNonReferenceFlag())
            {
              pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_N);
            }
            else
            {
              pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TSA_R);
            }
          }
          else if(pcSlice->isStepwiseTemporalLayerSwitchingPointCandidate(rcListPic))
          {
            bool isSTSA=true;
            for(int ii=iGOPid+1;(ii<m_pcCfg->getGOPSize() && isSTSA==true);ii++)
            {
              int lTid= m_pcCfg->getGOPEntry(ii).m_temporalId;
              if(lTid==pcSlice->getTLayer())
              {
                const ReferencePictureSet* nRPS = pcSlice->getSPS()->getRPSList()->getReferencePictureSet(ii);
                for(int jj=0;jj<nRPS->getNumberOfPictures();jj++)
                {
                  if(nRPS->getUsed(jj))
                  {
                    int tPoc=m_pcCfg->getGOPEntry(ii).m_POC+nRPS->getDeltaPOC(jj);
                    int kk=0;
                    for(kk=0;kk<m_pcCfg->getGOPSize();kk++)
                    {
                      if(m_pcCfg->getGOPEntry(kk).m_POC==tPoc)
                      {
                        break;
                      }
                    }
                    int tTid=m_pcCfg->getGOPEntry(kk).m_temporalId;
                    if(tTid >= pcSlice->getTLayer())
                    {
                      isSTSA=false;
                      break;
                    }
                  }
                }
              }
            }
            if(isSTSA==true)
            {
              if(pcSlice->getTemporalLayerNonReferenceFlag())
              {
                pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_N);
              }
              else
              {
                pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_R);
              }
            }
          }
        }
    
        if (pcSlice->getRPSidx() == -1)
          arrangeLongtermPicturesInRPS(pcSlice, rcListPic);
    
        RefPicListModification* refPicListModification = pcSlice->getRefPicListModification();
        refPicListModification->setRefPicListModificationFlagL0(0);
        refPicListModification->setRefPicListModificationFlagL1(0);
    
    
        if (m_pcCfg->getUseCompositeRef() && getUseLTRef() && (pocCurr > getLastLTRefPoc()))
        {
          pcSlice->setNumRefIdx(REF_PIC_LIST_0, min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive + 1, pcSlice->getRPS()->getNumberOfPictures()));
          pcSlice->setNumRefIdx(REF_PIC_LIST_1, min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive + 1, pcSlice->getRPS()->getNumberOfPictures()));
        }
        else
        {
          pcSlice->setNumRefIdx(REF_PIC_LIST_0, std::min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive, pcSlice->getRPS()->getNumberOfPictures()));
          pcSlice->setNumRefIdx(REF_PIC_LIST_1, std::min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive, pcSlice->getRPS()->getNumberOfPictures()));
        }
        if (pcPic->cs->sps->getSpsNext().getUseCompositeRef() && getPrepareLTRef()) {
          arrangeCompositeReference(pcSlice, rcListPic, pocCurr);
        }
    
    Yu Han's avatar
    Yu Han committed
        if (pcSlice->getSPS()->getSpsNext().getIBCMode())
    
    Xiaozhong Xu's avatar
    Xiaozhong Xu committed
        {
          if (m_pcCfg->getIntraPeriod() > 0 && pcSlice->getPOC() % m_pcCfg->getIntraPeriod() == 0)
          {
            pcSlice->setNumRefIdx(REF_PIC_LIST_0, 0);
            pcSlice->setNumRefIdx(REF_PIC_LIST_1, 0);
          }
    
    Xiaozhong Xu's avatar
    Xiaozhong Xu committed
          pcSlice->setNumRefIdx(REF_PIC_LIST_0, pcSlice->getNumRefIdx(REF_PIC_LIST_0) + 1);
        }
    
        //  Set reference list
        pcSlice->setRefPicList ( rcListPic );
    
        if( m_pcCfg->getUseAMaxBT() )
        {
    
          if( !pcSlice->isIRAP() )
    
          {
            int refLayer = pcSlice->getDepth();
            if( refLayer > 9 ) refLayer = 9; // Max layer is 10
    
            if( m_bInitAMaxBT && pcSlice->getPOC() > m_uiPrevISlicePOC )
            {
              ::memset( m_uiBlkSize, 0, sizeof( m_uiBlkSize ) );
              ::memset( m_uiNumBlk,  0, sizeof( m_uiNumBlk ) );
              m_bInitAMaxBT = false;
            }
    
            if( refLayer >= 0 && m_uiNumBlk[refLayer] != 0 )
            {
    
              pcSlice->setSplitConsOverrideFlag(true);
    
              double dBlkSize = sqrt( ( double ) m_uiBlkSize[refLayer] / m_uiNumBlk[refLayer] );
              if( dBlkSize < AMAXBT_TH32 )
              {
                pcSlice->setMaxBTSize( 32 > MAX_BT_SIZE_INTER ? MAX_BT_SIZE_INTER : 32 );
              }
              else if( dBlkSize < AMAXBT_TH64 )
              {
                pcSlice->setMaxBTSize( 64 > MAX_BT_SIZE_INTER ? MAX_BT_SIZE_INTER : 64 );
              }
              else
              {
                pcSlice->setMaxBTSize( 128 > MAX_BT_SIZE_INTER ? MAX_BT_SIZE_INTER : 128 );
              }
    
              m_uiBlkSize[refLayer] = 0;
              m_uiNumBlk [refLayer] = 0;
            }
          }
          else
          {
            if( m_bInitAMaxBT )
            {
              ::memset( m_uiBlkSize, 0, sizeof( m_uiBlkSize ) );
              ::memset( m_uiNumBlk,  0, sizeof( m_uiNumBlk ) );
            }
    
            m_uiPrevISlicePOC = pcSlice->getPOC();
            m_bInitAMaxBT = true;
          }
        }
    
        //  Slice info. refinement
        if ( (pcSlice->getSliceType() == B_SLICE) && (pcSlice->getNumRefIdx(REF_PIC_LIST_1) == 0) )
        {
          pcSlice->setSliceType ( P_SLICE );
        }
    
    Yu Han's avatar
    Yu Han committed
        if (pcSlice->getSPS()->getSpsNext().getIBCMode() && pcSlice->getNumRefIdx(REF_PIC_LIST_0) == 1)
    
    Xiaozhong Xu's avatar
    Xiaozhong Xu committed
        {
          m_pcSliceEncoder->setEncCABACTableIdx(P_SLICE);
        }
    
        xUpdateRasInit( pcSlice );
    
        // Do decoding refresh marking if any
    #if COM16_C806_ALF_TEMPPRED_NUM
        if ( pcSlice->getPendingRasInit() || pcSlice->isIDRorBLA() )
        {
          m_pcALF->refreshAlfTempPred();
        }
    #endif
    
        if ( pcSlice->getPendingRasInit() )
        {
          // this ensures that independently encoded bitstream chunks can be combined to bit-equal
          pcSlice->setEncCABACTableIdx( pcSlice->getSliceType() );
        }
        else
        {
          pcSlice->setEncCABACTableIdx( m_pcSliceEncoder->getEncCABACTableIdx() );
        }
    
        if (pcSlice->getSliceType() == B_SLICE)
        {
    #if X0038_LAMBDA_FROM_QP_CAPABILITY
          const uint32_t uiColFromL0 = calculateCollocatedFromL0Flag(pcSlice);
          pcSlice->setColFromL0Flag(uiColFromL0);
    #else
          pcSlice->setColFromL0Flag(1-uiColDir);
    #endif
          bool bLowDelay = true;
          int  iCurrPOC  = pcSlice->getPOC();
          int iRefIdx = 0;
    
          for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_0) && bLowDelay; iRefIdx++)
          {
            if ( pcSlice->getRefPic(REF_PIC_LIST_0, iRefIdx)->getPOC() > iCurrPOC )
            {
              bLowDelay = false;
            }
          }
          for (iRefIdx = 0; iRefIdx < pcSlice->getNumRefIdx(REF_PIC_LIST_1) && bLowDelay; iRefIdx++)
          {
            if ( pcSlice->getRefPic(REF_PIC_LIST_1, iRefIdx)->getPOC() > iCurrPOC )
            {
              bLowDelay = false;
            }
          }
    
          pcSlice->setCheckLDC(bLowDelay);
        }
        else
        {
          pcSlice->setCheckLDC(true);
        }
    
    #if !X0038_LAMBDA_FROM_QP_CAPABILITY
        uiColDir = 1-uiColDir;
    #endif
    
        //-------------------------------------------------------------
        pcSlice->setRefPOCList();
    
    
        pcSlice->setList1IdxToList0Idx();
    
        if (m_pcEncLib->getTMVPModeId() == 2)
        {
          if (iGOPid == 0) // first picture in SOP (i.e. forward B)
          {
            pcSlice->setEnableTMVPFlag(0);
          }
          else
          {
            // Note: pcSlice->getColFromL0Flag() is assumed to be always 0 and getcolRefIdx() is always 0.
            pcSlice->setEnableTMVPFlag(1);
          }
        }
        else if (m_pcEncLib->getTMVPModeId() == 1)
        {
          pcSlice->setEnableTMVPFlag(1);
        }
        else
        {
          pcSlice->setEnableTMVPFlag(0);
        }
    
    
        // disable TMVP when current picture is the only ref picture
    
    Yu Han's avatar
    Yu Han committed
        if (pcSlice->isIRAP() && pcSlice->getSPS()->getSpsNext().getIBCMode())
    
        // set adaptive search range for non-intra-slices
    
        if (m_pcCfg->getUseASR() && !pcSlice->isIRAP())
    
        {
          m_pcSliceEncoder->setSearchRange(pcSlice);
        }
    
        bool bGPBcheck=false;
        if ( pcSlice->getSliceType() == B_SLICE)
        {
    
    Yu Han's avatar
    Yu Han committed
          if (pcSlice->getSPS()->getSpsNext().getIBCMode())
    
    Xiaozhong Xu's avatar
    Xiaozhong Xu committed
          {
            if (pcSlice->getNumRefIdx(RefPicList(0)) - 1 == pcSlice->getNumRefIdx(RefPicList(1)))
            {
              bGPBcheck = true;
              for (int i = 0; i < pcSlice->getNumRefIdx(RefPicList(1)); i++)
              {
                if (pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i))
                {
                  bGPBcheck = false;
                  break;
                }
              }
            }
          }
          else
    
          if ( pcSlice->getNumRefIdx(RefPicList( 0 ) ) == pcSlice->getNumRefIdx(RefPicList( 1 ) ) )
          {
            bGPBcheck=true;
            int i;
            for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
            {
              if ( pcSlice->getRefPOC(RefPicList(1), i) != pcSlice->getRefPOC(RefPicList(0), i) )
              {
                bGPBcheck=false;
                break;
              }
            }
          }
        }
        if(bGPBcheck)
        {
          pcSlice->setMvdL1ZeroFlag(true);
        }
        else
        {
          pcSlice->setMvdL1ZeroFlag(false);
        }
    #if HEVC_DEPENDENT_SLICES
        pcPic->slices[pcSlice->getSliceSegmentIdx()]->setMvdL1ZeroFlag(pcSlice->getMvdL1ZeroFlag());
    #endif
    
    
    #if JVET_M0444_SMVD
        if ( pcSlice->getCheckLDC() == false && pcSlice->getMvdL1ZeroFlag() == false )
        {
          int currPOC = pcSlice->getPOC();
    
          int forwardPOC = currPOC;
    
    Daniel's avatar
    Daniel committed
          int backwardPOC = currPOC;
    
          int ref = 0, refIdx0 = -1, refIdx1 = -1;
    
          // search nearest forward POC in List 0
          for ( ref = 0; ref < pcSlice->getNumRefIdx( REF_PIC_LIST_0 ); ref++ )
          {
            int poc = pcSlice->getRefPic( REF_PIC_LIST_0, ref )->getPOC();
            if ( poc < currPOC && (poc > forwardPOC || refIdx0 == -1) )
            {
              forwardPOC = poc;
              refIdx0 = ref;
            }
          }
    
          // search nearest backward POC in List 1
          for ( ref = 0; ref < pcSlice->getNumRefIdx( REF_PIC_LIST_1 ); ref++ )
          {
            int poc = pcSlice->getRefPic( REF_PIC_LIST_1, ref )->getPOC();
    
    Daniel's avatar
    Daniel committed
            if ( poc > currPOC && (poc < backwardPOC || refIdx1 == -1) )
    
    Daniel's avatar
    Daniel committed
              backwardPOC = poc;
    
    Daniel's avatar
    Daniel committed
          if ( !(forwardPOC < currPOC && backwardPOC > currPOC) )
    
          {
            forwardPOC = currPOC;
    
    Daniel's avatar
    Daniel committed
            backwardPOC = currPOC;
    
            refIdx0 = -1;
            refIdx1 = -1;
    
            // search nearest backward POC in List 0
            for ( ref = 0; ref < pcSlice->getNumRefIdx( REF_PIC_LIST_0 ); ref++ )
            {
              int poc = pcSlice->getRefPic( REF_PIC_LIST_0, ref )->getPOC();
    
    Daniel's avatar
    Daniel committed
              if ( poc > currPOC && (poc < backwardPOC || refIdx0 == -1) )
    
    Daniel's avatar
    Daniel committed
                backwardPOC = poc;
    
                refIdx0 = ref;
              }
            }
    
            // search nearest forward POC in List 1
            for ( ref = 0; ref < pcSlice->getNumRefIdx( REF_PIC_LIST_1 ); ref++ )
            {
              int poc = pcSlice->getRefPic( REF_PIC_LIST_1, ref )->getPOC();
              if ( poc < currPOC && (poc > forwardPOC || refIdx1 == -1) )
              {
                forwardPOC = poc;
                refIdx1 = ref;
              }
            }
          }
    
    
    Daniel's avatar
    Daniel committed
          if ( forwardPOC < currPOC && backwardPOC > currPOC )
    
          {
            pcSlice->setBiDirPred( true, refIdx0, refIdx1 );
          }
          else
          {
            pcSlice->setBiDirPred( false, -1, -1 );
          }
        }
        else
        {
          pcSlice->setBiDirPred( false, -1, -1 );
        }
    #endif
    
    
        double lambda            = 0.0;
        int actualHeadBits       = 0;
        int actualTotalBits      = 0;
        int estimatedBits        = 0;
        int tmpBitsBeforeWriting = 0;
        if ( m_pcCfg->getUseRateCtrl() ) // TODO: does this work with multiple slices and slice-segments?
        {
          int frameLevel = m_pcRateCtrl->getRCSeq()->getGOPID2Level( iGOPid );
    
          if ( pcPic->slices[0]->isIRAP() )
    
          {
            frameLevel = 0;
          }
          m_pcRateCtrl->initRCPic( frameLevel );
          estimatedBits = m_pcRateCtrl->getRCPic()->getTargetBits();
    
    #if U0132_TARGET_BITS_SATURATION
          if (m_pcRateCtrl->getCpbSaturationEnabled() && frameLevel != 0)
          {
            int estimatedCpbFullness = m_pcRateCtrl->getCpbState() + m_pcRateCtrl->getBufferingRate();
    
            // prevent overflow
            if (estimatedCpbFullness - estimatedBits > (int)(m_pcRateCtrl->getCpbSize()*0.9f))
            {
              estimatedBits = estimatedCpbFullness - (int)(m_pcRateCtrl->getCpbSize()*0.9f);
            }
    
            estimatedCpbFullness -= m_pcRateCtrl->getBufferingRate();
            // prevent underflow
    #if V0078_ADAPTIVE_LOWER_BOUND
            if (estimatedCpbFullness - estimatedBits < m_pcRateCtrl->getRCPic()->getLowerBound())
            {
    
              estimatedBits = std::max(200, estimatedCpbFullness - m_pcRateCtrl->getRCPic()->getLowerBound());
    
            }
    #else
            if (estimatedCpbFullness - estimatedBits < (int)(m_pcRateCtrl->getCpbSize()*0.1f))
            {
    
              estimatedBits = std::max(200, estimatedCpbFullness - (int)(m_pcRateCtrl->getCpbSize()*0.1f));
    
            }
    #endif
    
            m_pcRateCtrl->getRCPic()->setTargetBits(estimatedBits);
          }
    #endif
    
          int sliceQP = m_pcCfg->getInitialQP();
          if ( ( pcSlice->getPOC() == 0 && m_pcCfg->getInitialQP() > 0 ) || ( frameLevel == 0 && m_pcCfg->getForceIntraQP() ) ) // QP is specified
          {
            int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
            double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(double)NumberBFrames );
            double dQPFactor     = 0.57*dLambda_scale;
            int    SHIFT_QP      = 12;
            int bitdepth_luma_qp_scale =
              6
              * (pcSlice->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) - 8
                 - DISTORTION_PRECISION_ADJUSTMENT(pcSlice->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA)));
            double qp_temp = (double) sliceQP + bitdepth_luma_qp_scale - SHIFT_QP;
            lambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
          }