Changeset 125 in SHVCSoftware for trunk/source/Lib/TLibEncoder/TEncGOP.cpp


Ignore:
Timestamp:
16 Apr 2013, 06:39:31 (12 years ago)
Author:
seregin
Message:

copy from HM-10.0-dev-SHM

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/source/Lib/TLibEncoder/TEncGOP.cpp

    r55 r125  
    44 * granted under this license. 
    55 *
    6  * Copyright (c) 2010-2012, ITU/ISO/IEC
     6 * Copyright (c) 2010-2013, ITU/ISO/IEC
    77 * All rights reserved.
    88 *
     
    8989  m_bRefreshPending     = 0;
    9090  m_pocCRA            = 0;
    91 #if LTRP_IN_SPS
    9291  m_numLongTermRefPicSPS = 0;
    9392  ::memset(m_ltRefPicPocLsbSps, 0, sizeof(m_ltRefPicPocLsbSps));
    9493  ::memset(m_ltRefPicUsedByCurrPicFlag, 0, sizeof(m_ltRefPicUsedByCurrPicFlag));
    95 #endif
    96 #if BUFFERING_PERIOD_AND_TIMING_SEI
    9794  m_cpbRemovalDelay   = 0;
    9895  m_lastBPSEI         = 0;
    99 #endif
    100 
     96#if L0045_NON_NESTED_SEI_RESTRICTIONS
     97  xResetNonNestedSEIPresentFlags();
     98#endif
    10199#if SVC_UPSAMPLING
    102100  m_pcPredSearch        = NULL;
     
    110108
    111109/** Create list to contain pointers to LCU start addresses of slice.
    112  * \param iWidth, iHeight are picture width, height. iMaxCUWidth, iMaxCUHeight are LCU width, height.
    113110 */
    114111#if SVC_EXTENSION
    115 Void  TEncGOP::create( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight, UInt layerId )
    116 #else
    117 Void  TEncGOP::create( Int iWidth, Int iHeight, UInt iMaxCUWidth, UInt iMaxCUHeight )
    118 #endif
     112Void  TEncGOP::create( UInt layerId )
    119113{
    120114  m_bLongtermTestPictureHasBeenCoded = 0;
    121115  m_bLongtermTestPictureHasBeenCoded2 = 0;
    122 
    123 #if SVC_EXTENSION
    124116  m_layerId = layerId;
    125 #endif
    126117}
     118#else
     119Void  TEncGOP::create()
     120{
     121  m_bLongtermTestPictureHasBeenCoded = 0;
     122  m_bLongtermTestPictureHasBeenCoded2 = 0;
     123}
     124#endif
    127125
    128126Void  TEncGOP::destroy()
     
    135133  m_pcCfg                = pcTEncTop;
    136134  m_pcSliceEncoder       = pcTEncTop->getSliceEncoder();
    137   m_pcListPic            = pcTEncTop->getListPic();
    138 
    139 #if SVC_EXTENSION
    140   m_ppcTEncTop           = pcTEncTop->getLayerEnc();
    141 #endif
    142  
     135  m_pcListPic            = pcTEncTop->getListPic(); 
    143136  m_pcEntropyCoder       = pcTEncTop->getEntropyCoder();
    144137  m_pcCavlcCoder         = pcTEncTop->getCavlcCoder();
     
    148141  m_pcBitCounter         = pcTEncTop->getBitCounter();
    149142 
    150 #if !REMOVE_ALF
    151   // Adaptive Loop filter
    152   m_pcAdaptiveLoopFilter = pcTEncTop->getAdaptiveLoopFilter();
    153 #endif
    154143  //--Adaptive Loop filter
    155144  m_pcSAO                = pcTEncTop->getSAO();
    156145  m_pcRateCtrl           = pcTEncTop->getRateCtrl();
    157 #if BUFFERING_PERIOD_AND_TIMING_SEI
    158146  m_lastBPSEI          = 0;
    159147  m_totalCoded         = 0;
    160 #endif
    161 
     148
     149#if SVC_EXTENSION
     150  m_ppcTEncTop           = pcTEncTop->getLayerEnc();
     151#endif
    162152#if SVC_UPSAMPLING
    163153  m_pcPredSearch         = pcTEncTop->getPredSearch();                       ///< encoder search class
    164154#endif
     155}
     156
     157SEIActiveParameterSets* TEncGOP::xCreateSEIActiveParameterSets (TComSPS *sps)
     158{
     159  SEIActiveParameterSets *seiActiveParameterSets = new SEIActiveParameterSets();
     160  seiActiveParameterSets->activeVPSId = m_pcCfg->getVPS()->getVPSId();
     161#if L0047_APS_FLAGS
     162  seiActiveParameterSets->m_fullRandomAccessFlag = false;
     163  seiActiveParameterSets->m_noParamSetUpdateFlag = false;
     164#endif
     165  seiActiveParameterSets->numSpsIdsMinus1 = 0;
     166  seiActiveParameterSets->activeSeqParamSetId.resize(seiActiveParameterSets->numSpsIdsMinus1 + 1);
     167  seiActiveParameterSets->activeSeqParamSetId[0] = sps->getSPSId();
     168  return seiActiveParameterSets;
     169}
     170
     171SEIFramePacking* TEncGOP::xCreateSEIFramePacking()
     172{
     173  SEIFramePacking *seiFramePacking = new SEIFramePacking();
     174  seiFramePacking->m_arrangementId = m_pcCfg->getFramePackingArrangementSEIId();
     175  seiFramePacking->m_arrangementCancelFlag = 0;
     176  seiFramePacking->m_arrangementType = m_pcCfg->getFramePackingArrangementSEIType();
     177#if L0444_FPA_TYPE
     178  assert((seiFramePacking->m_arrangementType > 2) && (seiFramePacking->m_arrangementType < 6) );
     179#endif
     180  seiFramePacking->m_quincunxSamplingFlag = m_pcCfg->getFramePackingArrangementSEIQuincunx();
     181  seiFramePacking->m_contentInterpretationType = m_pcCfg->getFramePackingArrangementSEIInterpretation();
     182  seiFramePacking->m_spatialFlippingFlag = 0;
     183  seiFramePacking->m_frame0FlippedFlag = 0;
     184  seiFramePacking->m_fieldViewsFlag = (seiFramePacking->m_arrangementType == 2);
     185  seiFramePacking->m_currentFrameIsFrame0Flag = ((seiFramePacking->m_arrangementType == 5) && m_iNumPicCoded&1);
     186  seiFramePacking->m_frame0SelfContainedFlag = 0;
     187  seiFramePacking->m_frame1SelfContainedFlag = 0;
     188  seiFramePacking->m_frame0GridPositionX = 0;
     189  seiFramePacking->m_frame0GridPositionY = 0;
     190  seiFramePacking->m_frame1GridPositionX = 0;
     191  seiFramePacking->m_frame1GridPositionY = 0;
     192  seiFramePacking->m_arrangementReservedByte = 0;
     193#if L0045_PERSISTENCE_FLAGS
     194  seiFramePacking->m_arrangementPersistenceFlag = true;
     195#else
     196  seiFramePacking->m_arrangementRepetetionPeriod = 1;
     197#endif
     198  seiFramePacking->m_upsampledAspectRatio = 0;
     199  return seiFramePacking;
     200}
     201
     202SEIDisplayOrientation* TEncGOP::xCreateSEIDisplayOrientation()
     203{
     204  SEIDisplayOrientation *seiDisplayOrientation = new SEIDisplayOrientation();
     205  seiDisplayOrientation->cancelFlag = false;
     206  seiDisplayOrientation->horFlip = false;
     207  seiDisplayOrientation->verFlip = false;
     208  seiDisplayOrientation->anticlockwiseRotation = m_pcCfg->getDisplayOrientationSEIAngle();
     209  return seiDisplayOrientation;
     210}
     211
     212Void TEncGOP::xCreateLeadingSEIMessages (/*SEIMessages seiMessages,*/ AccessUnit &accessUnit, TComSPS *sps)
     213{
     214  OutputNALUnit nalu(NAL_UNIT_SEI);
     215
     216  if(m_pcCfg->getActiveParameterSetsSEIEnabled())
     217  {
     218    SEIActiveParameterSets *sei = xCreateSEIActiveParameterSets (sps);
     219
     220    //nalu = NALUnit(NAL_UNIT_SEI);
     221    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
     222    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps);
     223    writeRBSPTrailingBits(nalu.m_Bitstream);
     224    accessUnit.push_back(new NALUnitEBSP(nalu));
     225    delete sei;
     226#if L0045_NON_NESTED_SEI_RESTRICTIONS
     227    m_activeParameterSetSEIPresentInAU = true;
     228#endif
     229  }
     230
     231  if(m_pcCfg->getFramePackingArrangementSEIEnabled())
     232  {
     233    SEIFramePacking *sei = xCreateSEIFramePacking ();
     234
     235    nalu = NALUnit(NAL_UNIT_SEI);
     236    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
     237    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps);
     238    writeRBSPTrailingBits(nalu.m_Bitstream);
     239    accessUnit.push_back(new NALUnitEBSP(nalu));
     240    delete sei;
     241  }
     242  if (m_pcCfg->getDisplayOrientationSEIAngle())
     243  {
     244    SEIDisplayOrientation *sei = xCreateSEIDisplayOrientation();
     245
     246    nalu = NALUnit(NAL_UNIT_SEI);
     247    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
     248    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps);
     249    writeRBSPTrailingBits(nalu.m_Bitstream);
     250    accessUnit.push_back(new NALUnitEBSP(nalu));
     251    delete sei;
     252  }
    165253}
    166254
     
    187275
    188276  m_iNumPicCoded = 0;
    189 #if BUFFERING_PERIOD_AND_TIMING_SEI
    190277  SEIPictureTiming pictureTimingSEI;
     278#if L0044_DU_DPB_OUTPUT_DELAY_HRD
     279  Int picSptDpbOutputDuDelay = 0;
     280#endif
    191281  UInt *accumBitsDU = NULL;
    192282  UInt *accumNalsDU = NULL;
    193 #endif
     283  SEIDecodingUnitInfo decodingUnitInfoSEI;
    194284#if SVC_EXTENSION
    195285  for ( Int iGOPid=iPicIdInGOP; iGOPid < iPicIdInGOP+1; iGOPid++ )
     
    246336
    247337    /////////////////////////////////////////////////////////////////////////////////////////////////// Initial to start encoding
    248     UInt uiPOCCurr = iPOCLast -iNumPicRcvd+ m_pcCfg->getGOPEntry(iGOPid).m_POC;
     338    Int pocCurr = iPOCLast -iNumPicRcvd+ m_pcCfg->getGOPEntry(iGOPid).m_POC;
    249339    Int iTimeOffset = m_pcCfg->getGOPEntry(iGOPid).m_POC;
    250340    if(iPOCLast == 0)
    251341    {
    252       uiPOCCurr=0;
     342      pocCurr=0;
    253343      iTimeOffset = 1;
    254344    }
    255     if(uiPOCCurr>=m_pcCfg->getFrameToBeEncoded())
     345    if(pocCurr>=m_pcCfg->getFramesToBeEncoded())
    256346    {
    257347      continue;
    258348    }
    259349
    260 #if SUPPORT_FOR_RAP_N_LP
    261     if( getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDR || getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDR_N_LP )
    262 #else
    263     if(getNalUnitType(uiPOCCurr) == NAL_UNIT_CODED_SLICE_IDR)
    264 #endif
    265     {
    266       m_iLastIDR = uiPOCCurr;
     350    if( getNalUnitType(pocCurr) == NAL_UNIT_CODED_SLICE_IDR || getNalUnitType(pocCurr) == NAL_UNIT_CODED_SLICE_IDR_N_LP )
     351    {
     352      m_iLastIDR = pocCurr;
    267353    }       
    268354    // start a new access unit: create an entry in the list of output access units
    269355    accessUnitsInGOP.push_back(AccessUnit());
    270356    AccessUnit& accessUnit = accessUnitsInGOP.back();
    271     xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, uiPOCCurr );
     357    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr );
    272358
    273359    //  Slice data initialization
     
    277363    pcPic->setCurrSliceIdx(0);
    278364#if SVC_EXTENSION
    279       pcPic->setLayerId( m_layerId );
    280 #endif
    281 
    282 #if !REMOVE_APS
    283     std::vector<TComAPS>& vAPS = m_pcEncTop->getAPS();
    284 #endif
    285     m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, uiPOCCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS() );
     365    pcPic->setLayerId( m_layerId );
     366#endif
     367
     368    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS() );
    286369    pcSlice->setLastIDR(m_iLastIDR);
    287370    pcSlice->setSliceIdx(0);
    288371    //set default slice level flag to the same as SPS level flag
    289 #if MOVE_LOOP_FILTER_SLICES_FLAG
    290372    pcSlice->setLFCrossSliceBoundaryFlag(  pcSlice->getPPS()->getLoopFilterAcrossSlicesEnabledFlag()  );
    291 #else
    292     pcSlice->setLFCrossSliceBoundaryFlag(  pcSlice->getSPS()->getLFCrossSliceBoundaryFlag()  );
    293 #endif
    294373    pcSlice->setScalingList ( m_pcEncTop->getScalingList()  );
    295 #if TS_FLAT_QUANTIZATION_MATRIX
    296374    pcSlice->getScalingList()->setUseTransformSkip(m_pcEncTop->getPPS()->getUseTransformSkip());
    297 #endif
    298375    if(m_pcEncTop->getUseScalingListId() == SCALING_LIST_OFF)
    299376    {
     
    333410      pcSlice->setSliceType(P_SLICE);
    334411    }
    335 
    336412    // Set the nal unit type
    337     pcSlice->setNalUnitType(getNalUnitType(uiPOCCurr));
     413    pcSlice->setNalUnitType(getNalUnitType(pocCurr));
     414#if IDR_ALIGNMENT
     415    if (m_layerId > 0)
     416    {
     417      TComList<TComPic*> *cListPic = m_ppcTEncTop[m_layerId-1]->getListPic();
     418      pcSlice->setBaseColPic (*cListPic, m_layerId );
     419    }
     420#endif
    338421#if REF_IDX_FRAMEWORK
    339     if( m_layerId > 0 && (uiPOCCurr % m_pcCfg->getIntraPeriod() == 0) )
    340     {
     422
     423    if( m_layerId > 0 && (pocCurr % m_pcCfg->getIntraPeriod() == 0) )
     424    {
     425#if IDR_ALIGNMENT
     426      if( pcSlice->getBaseColPic()->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR )
     427      {
     428        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_IDR);
     429      }
     430      else
     431#endif
    341432      pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_CRA);
    342433    }
     
    351442    }
    352443#endif
    353 #if TEMPORAL_LAYER_NON_REFERENCE
    354444    if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_TRAIL_R)
    355445    {
     
    359449      }
    360450    }
    361 #endif
    362451
    363452    // Do decoding refresh marking if any
    364453    pcSlice->decodingRefreshMarking(m_pocCRA, m_bRefreshPending, rcListPic);
    365     m_pcEncTop->selectReferencePictureSet(pcSlice, uiPOCCurr, iGOPid,rcListPic);
     454    m_pcEncTop->selectReferencePictureSet(pcSlice, pocCurr, iGOPid);
    366455    pcSlice->getRPS()->setNumberOfLongtermPictures(0);
    367456
     
    374463    if(pcSlice->getTLayer() > 0)
    375464    {
    376       if(pcSlice->isTemporalLayerSwitchingPoint(rcListPic, pcSlice->getRPS()) || pcSlice->getSPS()->getTemporalIdNestingFlag())
    377       {
    378 #if TEMPORAL_LAYER_NON_REFERENCE
     465      if(pcSlice->isTemporalLayerSwitchingPoint(rcListPic) || pcSlice->getSPS()->getTemporalIdNestingFlag())
     466      {
    379467        if(pcSlice->getTemporalLayerNonReferenceFlag())
    380468        {
     
    385473          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA);
    386474        }
    387 #else
    388         pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA);
    389 #endif
    390       }
    391 #if STSA
    392       else if(pcSlice->isStepwiseTemporalLayerSwitchingPointCandidate(rcListPic, pcSlice->getRPS()))
    393       {
    394           Bool isSTSA=true;
    395           for(Int ii=iGOPid+1;(ii<m_pcCfg->getGOPSize() && isSTSA==true);ii++)
    396           {
    397               Int lTid= m_pcCfg->getGOPEntry(ii).m_temporalId;
    398               if(lTid==pcSlice->getTLayer())
     475      }
     476      else if(pcSlice->isStepwiseTemporalLayerSwitchingPointCandidate(rcListPic))
     477      {
     478        Bool isSTSA=true;
     479        for(Int ii=iGOPid+1;(ii<m_pcCfg->getGOPSize() && isSTSA==true);ii++)
     480        {
     481          Int lTid= m_pcCfg->getGOPEntry(ii).m_temporalId;
     482          if(lTid==pcSlice->getTLayer())
     483          {
     484            TComReferencePictureSet* nRPS = pcSlice->getSPS()->getRPSList()->getReferencePictureSet(ii);
     485            for(Int jj=0;jj<nRPS->getNumberOfPictures();jj++)
     486            {
     487              if(nRPS->getUsed(jj))
    399488              {
    400                   TComReferencePictureSet* nRPS = pcSlice->getSPS()->getRPSList()->getReferencePictureSet(ii);
    401                   for(Int jj=0;jj<nRPS->getNumberOfPictures();jj++)
    402                   {
    403                       if(nRPS->getUsed(jj)) {
    404                           Int tPoc=m_pcCfg->getGOPEntry(ii).m_POC+nRPS->getDeltaPOC(jj);
    405                           Int kk=0;
    406                           for(kk=0;kk<m_pcCfg->getGOPSize();kk++)
    407                           {
    408                               if(m_pcCfg->getGOPEntry(kk).m_POC==tPoc)
    409                                   break;
    410                           }
    411                           Int tTid=m_pcCfg->getGOPEntry(kk).m_temporalId;
    412                           if(tTid >= pcSlice->getTLayer())
    413                           {
    414                               isSTSA=false;
    415                               break;
    416                           }
    417                          
    418                       }
    419                   }
     489                Int tPoc=m_pcCfg->getGOPEntry(ii).m_POC+nRPS->getDeltaPOC(jj);
     490                Int kk=0;
     491                for(kk=0;kk<m_pcCfg->getGOPSize();kk++)
     492                {
     493                  if(m_pcCfg->getGOPEntry(kk).m_POC==tPoc)
     494                    break;
     495                }
     496                Int tTid=m_pcCfg->getGOPEntry(kk).m_temporalId;
     497                if(tTid >= pcSlice->getTLayer())
     498                {
     499                  isSTSA=false;
     500                  break;
     501                }
    420502              }
    421           }
    422           if(isSTSA==true)
    423           {   
    424 #if TEMPORAL_LAYER_NON_REFERENCE
    425             if(pcSlice->getTemporalLayerNonReferenceFlag())
    426             {
    427               pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_N);
    428503            }
    429             else
    430             {
    431               pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_R);
    432             }
    433 #else
     504          }
     505        }
     506        if(isSTSA==true)
     507        {   
     508          if(pcSlice->getTemporalLayerNonReferenceFlag())
     509          {
     510            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_N);
     511          }
     512          else
     513          {
    434514            pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_STSA_R);
    435 #endif
    436           }
    437       }
    438 #endif
    439 
     515          }
     516        }
     517      }
    440518    }
    441519    arrangeLongtermPicturesInRPS(pcSlice, rcListPic);
     
    446524    pcSlice->setNumRefIdx(REF_PIC_LIST_1,min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive,pcSlice->getRPS()->getNumberOfPictures()));
    447525
     526#if REF_LIST_BUGFIX
     527    if(m_layerId > 0)
     528    {
     529      if( pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA )
     530      {
     531        pcSlice->setNumRefIdx(REF_PIC_LIST_0, pcSlice->getNumILRRefIdx());
     532        pcSlice->setNumRefIdx(REF_PIC_LIST_1, pcSlice->getNumILRRefIdx());
     533      }
     534      else
     535      {
     536        pcSlice->setNumRefIdx(REF_PIC_LIST_0, pcSlice->getNumRefIdx(REF_PIC_LIST_0)+pcSlice->getNumILRRefIdx());
     537        pcSlice->setNumRefIdx(REF_PIC_LIST_1, pcSlice->getNumRefIdx(REF_PIC_LIST_1)+pcSlice->getNumILRRefIdx());
     538      }
     539    }
     540#endif
     541
    448542#if ADAPTIVE_QP_SELECTION
    449543    pcSlice->setTrQuant( m_pcEncTop->getTrQuant() );
     
    451545
    452546#if SVC_EXTENSION     
    453       if(m_layerId > 0)
    454       {
    455         TComList<TComPic*> *cListPic = m_ppcTEncTop[m_layerId-1]->getListPic();
    456         pcSlice->setBaseColPic (*cListPic, m_layerId );
     547    if(m_layerId > 0)
     548    {
     549#if !IDR_ALIGNMENT
     550      TComList<TComPic*> *cListPic = m_ppcTEncTop[m_layerId-1]->getListPic();
     551      pcSlice->setBaseColPic (*cListPic, m_layerId );
     552#endif
    457553#if SVC_UPSAMPLING
    458         if ( pcPic->isSpatialEnhLayer())
    459         {   
    460           m_pcPredSearch->upsampleBasePic( pcPic->getFullPelBaseRec(), pcSlice->getBaseColPic()->getPicYuvRec(), pcPic->getPicYuvRec() );
    461         }
    462         else
    463         {
     554      if ( pcPic->isSpatialEnhLayer())
     555      {   
     556        m_pcPredSearch->upsampleBasePic( pcPic->getFullPelBaseRec(), pcSlice->getBaseColPic()->getPicYuvRec(), pcPic->getPicYuvRec() );
     557      }
     558      else
     559      {
    464560        pcPic->setFullPelBaseRec( pcSlice->getBaseColPic()->getPicYuvRec() );
    465         }
    466         pcSlice->setFullPelBaseRec ( pcPic->getFullPelBaseRec() );
    467 #endif
    468       }
     561      }
     562      pcSlice->setFullPelBaseRec ( pcPic->getFullPelBaseRec() );
     563#endif
     564    }
    469565#endif
    470566
     
    477573
    478574    //  Set reference list
     575#if REF_LIST_BUGFIX
     576    if(m_layerId ==  0)
     577    {
     578      pcSlice->setRefPicList( rcListPic);
     579    }
     580#else
    479581    pcSlice->setRefPicList ( rcListPic );
     582#endif
    480583#if REF_IDX_FRAMEWORK
    481584    if(m_layerId > 0)
     
    484587
    485588#if REF_IDX_MFM
    486       pcSlice->setRefPOCListILP(m_pcEncTop->getIlpList(), pcSlice->getBaseColPic());
    487 #endif
     589      if( pcSlice->getSPS()->getMFMEnabledFlag() )
     590      {
     591        pcSlice->setRefPOCListILP(m_pcEncTop->getIlpList(), pcSlice->getBaseColPic());
     592      }
     593#endif
     594#if REF_LIST_BUGFIX
     595      pcSlice->setRefPicListModificationSvc();
     596      pcSlice->setRefPicListSvc( rcListPic, m_pcEncTop->getIlpList() );
     597#else
    488598      pcSlice->addRefPicList ( m_pcEncTop->getIlpList(), 1);
     599#endif
    489600
    490601#if REF_IDX_MFM
    491       Bool found         = false;
    492       UInt ColFromL0Flag = pcSlice->getColFromL0Flag();
    493       UInt ColRefIdx     = pcSlice->getColRefIdx();
    494       for(Int colIdx = 0; colIdx < pcSlice->getNumRefIdx( RefPicList(1 - ColFromL0Flag) ); colIdx++)
    495       {
    496         if( pcSlice->getRefPic( RefPicList(1 - ColFromL0Flag), colIdx)->getIsILR() )
    497         {
    498           ColRefIdx = colIdx;
    499           found = true;
    500           break;
    501         }
    502       }
    503 
    504       if( found == false )
    505       {
    506         ColFromL0Flag = 1 - ColFromL0Flag;
     602      if( pcSlice->getSPS()->getMFMEnabledFlag() )
     603      {
     604        Bool found         = false;
     605        UInt ColFromL0Flag = pcSlice->getColFromL0Flag();
     606        UInt ColRefIdx     = pcSlice->getColRefIdx();
    507607        for(Int colIdx = 0; colIdx < pcSlice->getNumRefIdx( RefPicList(1 - ColFromL0Flag) ); colIdx++)
    508608        {
    509           if( pcSlice->getRefPic( RefPicList(1 - ColFromL0Flag), colIdx)->getIsILR() )
     609          if( pcSlice->getRefPic( RefPicList(1 - ColFromL0Flag), colIdx)->isILR() )
    510610          {
    511611            ColRefIdx = colIdx;
    512             found = true; 
     612            found = true;
    513613            break;
    514           }
    515         }
    516       }
    517 
    518       if(found == true)
    519       {
    520         pcSlice->setColFromL0Flag(ColFromL0Flag);
    521         pcSlice->setColRefIdx(ColRefIdx);
     614          }
     615        }
     616
     617        if( found == false )
     618        {
     619          ColFromL0Flag = 1 - ColFromL0Flag;
     620          for(Int colIdx = 0; colIdx < pcSlice->getNumRefIdx( RefPicList(1 - ColFromL0Flag) ); colIdx++)
     621          {
     622            if( pcSlice->getRefPic( RefPicList(1 - ColFromL0Flag), colIdx)->isILR() )
     623            {
     624              ColRefIdx = colIdx;
     625              found = true;
     626              break;
     627            }
     628          }
     629        }
     630
     631        if(found == true)
     632        {
     633          pcSlice->setColFromL0Flag(ColFromL0Flag);
     634          pcSlice->setColRefIdx(ColRefIdx);
     635        }
    522636      }
    523637#endif
     
    581695      {
    582696        pcSlice->setNoBackPredFlag( true );
    583         int i;
     697        Int i;
    584698        for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
    585699        {
     
    635749      {
    636750        bGPBcheck=true;
    637         int i;
     751        Int i;
    638752        for ( i=0; i < pcSlice->getNumRefIdx(RefPicList( 1 ) ); i++ )
    639753        {
     
    655769    }
    656770    pcPic->getSlice(pcSlice->getSliceIdx())->setMvdL1ZeroFlag(pcSlice->getMvdL1ZeroFlag());
     771
     772#if RATE_CONTROL_LAMBDA_DOMAIN
     773    Int sliceQP              = pcSlice->getSliceQp();
     774    Double lambda            = 0.0;
     775    Int actualHeadBits       = 0;
     776    Int actualTotalBits      = 0;
     777    Int estimatedBits        = 0;
     778    Int tmpBitsBeforeWriting = 0;
     779    if ( m_pcCfg->getUseRateCtrl() )
     780    {
     781      Int frameLevel = m_pcRateCtrl->getRCSeq()->getGOPID2Level( iGOPid );
     782      if ( pcPic->getSlice(0)->getSliceType() == I_SLICE )
     783      {
     784        frameLevel = 0;
     785      }
     786      m_pcRateCtrl->initRCPic( frameLevel );
     787      estimatedBits = m_pcRateCtrl->getRCPic()->getTargetBits();
     788
     789      if ( ( pcSlice->getPOC() == 0 && m_pcCfg->getInitialQP() > 0 ) || ( frameLevel == 0 && m_pcCfg->getForceIntraQP() ) ) // QP is specified
     790      {
     791        sliceQP              = m_pcCfg->getInitialQP();
     792        Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
     793        Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)NumberBFrames );
     794        Double dQPFactor     = 0.57*dLambda_scale;
     795        Int    SHIFT_QP      = 12;
     796        Int    bitdepth_luma_qp_scale = 0;
     797        Double qp_temp = (Double) sliceQP + bitdepth_luma_qp_scale - SHIFT_QP;
     798        lambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
     799      }
     800      else if ( frameLevel == 0 )   // intra case, but use the model
     801      {
     802        if ( m_pcCfg->getIntraPeriod() != 1 )   // do not refine allocated bits for all intra case
     803        {
     804          Int bits = m_pcRateCtrl->getRCSeq()->getLeftAverageBits();
     805          bits = m_pcRateCtrl->getRCSeq()->getRefineBitsForIntra( bits );
     806          if ( bits < 200 )
     807          {
     808            bits = 200;
     809          }
     810          m_pcRateCtrl->getRCPic()->setTargetBits( bits );
     811        }
     812
     813        list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
     814        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture );
     815        sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
     816      }
     817      else    // normal case
     818      {
     819        list<TEncRCPic*> listPreviousPicture = m_pcRateCtrl->getPicList();
     820        lambda  = m_pcRateCtrl->getRCPic()->estimatePicLambda( listPreviousPicture );
     821        sliceQP = m_pcRateCtrl->getRCPic()->estimatePicQP( lambda, listPreviousPicture );
     822      }
     823
     824      sliceQP = Clip3( -pcSlice->getSPS()->getQpBDOffsetY(), MAX_QP, sliceQP );
     825      m_pcRateCtrl->getRCPic()->setPicEstQP( sliceQP );
     826
     827      m_pcSliceEncoder->resetQP( pcPic, sliceQP, lambda );
     828    }
     829#endif
    657830
    658831    UInt uiNumSlices = 1;
     
    760933    pcSubstreamsOut = new TComOutputBitstream[iNumSubstreams];
    761934
    762     UInt uiStartCUAddrSliceIdx = 0; // used to index "m_uiStoredStartCUAddrForEncodingSlice" containing locations of slice boundaries
    763     UInt uiStartCUAddrSlice    = 0; // used to keep track of current slice's starting CU addr.
    764     pcSlice->setSliceCurStartCUAddr( uiStartCUAddrSlice ); // Setting "start CU addr" for current slice
     935    UInt startCUAddrSliceIdx = 0; // used to index "m_uiStoredStartCUAddrForEncodingSlice" containing locations of slice boundaries
     936    UInt startCUAddrSlice    = 0; // used to keep track of current slice's starting CU addr.
     937    pcSlice->setSliceCurStartCUAddr( startCUAddrSlice ); // Setting "start CU addr" for current slice
    765938    m_storedStartCUAddrForEncodingSlice.clear();
    766939
    767     UInt uiStartCUAddrDependentSliceIdx = 0; // used to index "m_uiStoredStartCUAddrForEntropyEncodingSlice" containing locations of slice boundaries
    768     UInt uiStartCUAddrDependentSlice    = 0; // used to keep track of current Dependent slice's starting CU addr.
    769     pcSlice->setDependentSliceCurStartCUAddr( uiStartCUAddrDependentSlice ); // Setting "start CU addr" for current Dependent slice
    770 
    771     m_storedStartCUAddrForEncodingDependentSlice.clear();
    772     UInt uiNextCUAddr = 0;
    773     m_storedStartCUAddrForEncodingSlice.push_back (uiNextCUAddr);
    774     uiStartCUAddrSliceIdx++;
    775     m_storedStartCUAddrForEncodingDependentSlice.push_back(uiNextCUAddr);
    776     uiStartCUAddrDependentSliceIdx++;
    777 
     940    UInt startCUAddrSliceSegmentIdx = 0; // used to index "m_uiStoredStartCUAddrForEntropyEncodingSlice" containing locations of slice boundaries
     941    UInt startCUAddrSliceSegment    = 0; // used to keep track of current Dependent slice's starting CU addr.
     942    pcSlice->setSliceSegmentCurStartCUAddr( startCUAddrSliceSegment ); // Setting "start CU addr" for current Dependent slice
     943
     944    m_storedStartCUAddrForEncodingSliceSegment.clear();
     945    UInt nextCUAddr = 0;
     946    m_storedStartCUAddrForEncodingSlice.push_back (nextCUAddr);
     947    startCUAddrSliceIdx++;
     948    m_storedStartCUAddrForEncodingSliceSegment.push_back(nextCUAddr);
     949    startCUAddrSliceSegmentIdx++;
    778950#if AVC_BASE
    779951    if( m_layerId == 0 )
     
    787959#endif
    788960
    789     while(uiNextCUAddr<uiRealEndAddress) // determine slice boundaries
     961    while(nextCUAddr<uiRealEndAddress) // determine slice boundaries
    790962    {
    791963      pcSlice->setNextSlice       ( false );
    792       pcSlice->setNextDependentSlice( false );
    793       assert(pcPic->getNumAllocatedSlice() == uiStartCUAddrSliceIdx);
     964      pcSlice->setNextSliceSegment( false );
     965      assert(pcPic->getNumAllocatedSlice() == startCUAddrSliceIdx);
    794966      m_pcSliceEncoder->precompressSlice( pcPic );
    795967      m_pcSliceEncoder->compressSlice   ( pcPic );
    796968
    797       Bool bNoBinBitConstraintViolated = (!pcSlice->isNextSlice() && !pcSlice->isNextDependentSlice());
    798       if (pcSlice->isNextSlice() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceMode()==AD_HOC_SLICES_FIXED_NUMBER_OF_LCU_IN_SLICE))
    799       {
    800         uiStartCUAddrSlice = pcSlice->getSliceCurEndCUAddr();
     969      Bool bNoBinBitConstraintViolated = (!pcSlice->isNextSlice() && !pcSlice->isNextSliceSegment());
     970      if (pcSlice->isNextSlice() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_LCU))
     971      {
     972        startCUAddrSlice = pcSlice->getSliceCurEndCUAddr();
    801973        // Reconstruction slice
    802         m_storedStartCUAddrForEncodingSlice.push_back(uiStartCUAddrSlice);
    803         uiStartCUAddrSliceIdx++;
     974        m_storedStartCUAddrForEncodingSlice.push_back(startCUAddrSlice);
     975        startCUAddrSliceIdx++;
    804976        // Dependent slice
    805         if (uiStartCUAddrDependentSliceIdx>0 && m_storedStartCUAddrForEncodingDependentSlice[uiStartCUAddrDependentSliceIdx-1] != uiStartCUAddrSlice)
    806         {
    807           m_storedStartCUAddrForEncodingDependentSlice.push_back(uiStartCUAddrSlice);
    808           uiStartCUAddrDependentSliceIdx++;
    809         }
    810 
    811         if (uiStartCUAddrSlice < uiRealEndAddress)
     977        if (startCUAddrSliceSegmentIdx>0 && m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx-1] != startCUAddrSlice)
     978        {
     979          m_storedStartCUAddrForEncodingSliceSegment.push_back(startCUAddrSlice);
     980          startCUAddrSliceSegmentIdx++;
     981        }
     982
     983        if (startCUAddrSlice < uiRealEndAddress)
    812984        {
    813985          pcPic->allocateNewSlice();         
    814           pcPic->setCurrSliceIdx                  ( uiStartCUAddrSliceIdx-1 );
    815           m_pcSliceEncoder->setSliceIdx           ( uiStartCUAddrSliceIdx-1 );
    816           pcSlice = pcPic->getSlice               ( uiStartCUAddrSliceIdx-1 );
     986          pcPic->setCurrSliceIdx                  ( startCUAddrSliceIdx-1 );
     987          m_pcSliceEncoder->setSliceIdx           ( startCUAddrSliceIdx-1 );
     988          pcSlice = pcPic->getSlice               ( startCUAddrSliceIdx-1 );
    817989          pcSlice->copySliceInfo                  ( pcPic->getSlice(0)      );
    818           pcSlice->setSliceIdx                    ( uiStartCUAddrSliceIdx-1 );
    819           pcSlice->setSliceCurStartCUAddr         ( uiStartCUAddrSlice      );
    820           pcSlice->setDependentSliceCurStartCUAddr  ( uiStartCUAddrSlice      );
     990          pcSlice->setSliceIdx                    ( startCUAddrSliceIdx-1 );
     991          pcSlice->setSliceCurStartCUAddr         ( startCUAddrSlice      );
     992          pcSlice->setSliceSegmentCurStartCUAddr  ( startCUAddrSlice      );
    821993          pcSlice->setSliceBits(0);
    822994          uiNumSlices ++;
    823995        }
    824996      }
    825       else if (pcSlice->isNextDependentSlice() || (bNoBinBitConstraintViolated && m_pcCfg->getDependentSliceMode()==SHARP_FIXED_NUMBER_OF_LCU_IN_DEPENDENT_SLICE))
    826       {
    827         uiStartCUAddrDependentSlice                                                     = pcSlice->getDependentSliceCurEndCUAddr();
    828         m_storedStartCUAddrForEncodingDependentSlice.push_back(uiStartCUAddrDependentSlice);
    829         uiStartCUAddrDependentSliceIdx++;
    830         pcSlice->setDependentSliceCurStartCUAddr( uiStartCUAddrDependentSlice );
     997      else if (pcSlice->isNextSliceSegment() || (bNoBinBitConstraintViolated && m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_LCU))
     998      {
     999        startCUAddrSliceSegment                                                     = pcSlice->getSliceSegmentCurEndCUAddr();
     1000        m_storedStartCUAddrForEncodingSliceSegment.push_back(startCUAddrSliceSegment);
     1001        startCUAddrSliceSegmentIdx++;
     1002        pcSlice->setSliceSegmentCurStartCUAddr( startCUAddrSliceSegment );
    8311003      }
    8321004      else
    8331005      {
    834         uiStartCUAddrSlice                                                            = pcSlice->getSliceCurEndCUAddr();
    835         uiStartCUAddrDependentSlice                                                     = pcSlice->getDependentSliceCurEndCUAddr();
     1006        startCUAddrSlice                                                            = pcSlice->getSliceCurEndCUAddr();
     1007        startCUAddrSliceSegment                                                     = pcSlice->getSliceSegmentCurEndCUAddr();
    8361008      }       
    8371009
    838       uiNextCUAddr = (uiStartCUAddrSlice > uiStartCUAddrDependentSlice) ? uiStartCUAddrSlice : uiStartCUAddrDependentSlice;
     1010      nextCUAddr = (startCUAddrSlice > startCUAddrSliceSegment) ? startCUAddrSlice : startCUAddrSliceSegment;
    8391011    }
    8401012    m_storedStartCUAddrForEncodingSlice.push_back( pcSlice->getSliceCurEndCUAddr());
    841     uiStartCUAddrSliceIdx++;
    842     m_storedStartCUAddrForEncodingDependentSlice.push_back(pcSlice->getSliceCurEndCUAddr());
    843     uiStartCUAddrDependentSliceIdx++;
     1013    startCUAddrSliceIdx++;
     1014    m_storedStartCUAddrForEncodingSliceSegment.push_back(pcSlice->getSliceCurEndCUAddr());
     1015    startCUAddrSliceSegmentIdx++;
    8441016
    8451017    pcSlice = pcPic->getSlice(0);
    8461018
    847 #if SAO_LCU_BOUNDARY
    8481019    // SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
    8491020    if( m_pcCfg->getSaoLcuBasedOptimization() && m_pcCfg->getSaoLcuBoundary() )
     
    8521023      m_pcSAO->calcSaoStatsCu_BeforeDblk( pcPic );
    8531024    }
    854 #endif
    8551025
    8561026    //-- Loop filter
    8571027    Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
    858     m_pcLoopFilter->setCfg(pcSlice->getPPS()->getDeblockingFilterControlPresentFlag(), pcSlice->getDeblockingFilterDisable(), pcSlice->getDeblockingFilterBetaOffsetDiv2(), pcSlice->getDeblockingFilterTcOffsetDiv2(), bLFCrossTileBoundary);
     1028    m_pcLoopFilter->setCfg(bLFCrossTileBoundary);
    8591029    m_pcLoopFilter->loopFilterPic( pcPic );
    8601030
    8611031    pcSlice = pcPic->getSlice(0);
    862 #if REMOVE_ALF
    8631032    if(pcSlice->getSPS()->getUseSAO())
    864 #else
    865     if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
    866 #endif
    867     {
    868 #if !REMOVE_FGS
    869       Int sliceGranularity = pcSlice->getPPS()->getSliceGranularity();
    870 #endif
     1033    {
    8711034      std::vector<Bool> LFCrossSliceBoundaryFlag;
    8721035      for(Int s=0; s< uiNumSlices; s++)
     
    8751038      }
    8761039      m_storedStartCUAddrForEncodingSlice.resize(uiNumSlices+1);
    877 #if REMOVE_FGS
    8781040      pcPic->createNonDBFilterInfo(m_storedStartCUAddrForEncodingSlice, 0, &LFCrossSliceBoundaryFlag ,pcPic->getPicSym()->getNumTiles() ,bLFCrossTileBoundary);
    879 #else
    880       pcPic->createNonDBFilterInfo(m_storedStartCUAddrForEncodingSlice, sliceGranularity, &LFCrossSliceBoundaryFlag ,pcPic->getPicSym()->getNumTiles() ,bLFCrossTileBoundary);
    881 #endif
    8821041    }
    8831042
     
    8871046    if(pcSlice->getSPS()->getUseSAO())
    8881047    {
    889       m_pcSAO->createPicSaoInfo(pcPic, uiNumSlices);
    890     }
    891 
    892 #if !REMOVE_ALF
    893     pcSlice = pcPic->getSlice(0);
    894 
    895     if(pcSlice->getSPS()->getUseALF())
    896     {
    897       m_pcAdaptiveLoopFilter->createPicAlfInfo(pcPic, uiNumSlices);
    898     }
    899 #endif
     1048      m_pcSAO->createPicSaoInfo(pcPic);
     1049    }
     1050
    9001051    /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
    9011052    // Set entropy coder
     
    9061057    {
    9071058#if SVC_EXTENSION
    908 #if REMOVE_NAL_REF_FLAG
    9091059      OutputNALUnit nalu(NAL_UNIT_VPS, 0, m_layerId);
     1060#if AVC_BASE
     1061      if( m_layerId == 1 )
    9101062#else
    911       OutputNALUnit nalu(NAL_UNIT_VPS, true, 0, m_layerId);
    912 #endif
     1063      if( m_layerId == 0 )
     1064#endif
     1065      {
    9131066#else
    914 #if REMOVE_NAL_REF_FLAG
    9151067      OutputNALUnit nalu(NAL_UNIT_VPS);
    916 #else
    917       OutputNALUnit nalu(NAL_UNIT_VPS, true);
    918 #endif
    9191068#endif
    9201069      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
     
    9221071      writeRBSPTrailingBits(nalu.m_Bitstream);
    9231072      accessUnit.push_back(new NALUnitEBSP(nalu));
    924 
     1073#if RATE_CONTROL_LAMBDA_DOMAIN
     1074      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
     1075#endif
    9251076#if SVC_EXTENSION
    926 #if REMOVE_NAL_REF_FLAG
     1077      }
     1078#endif
     1079
     1080#if SVC_EXTENSION
    9271081      nalu = NALUnit(NAL_UNIT_SPS, 0, m_layerId);
    9281082#else
    929       nalu = NALUnit(NAL_UNIT_SPS, true, 0, m_layerId);
    930 #endif
    931 #else
    932 #if REMOVE_NAL_REF_FLAG
    9331083      nalu = NALUnit(NAL_UNIT_SPS);
    934 #else
    935       nalu = NALUnit(NAL_UNIT_SPS, true);
    936 #endif
    9371084#endif
    9381085      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
    939 #if LTRP_IN_SPS
    9401086      if (m_bSeqFirst)
    9411087      {
     
    9471093        }
    9481094      }
    949 #endif
    950 #if BUFFERING_PERIOD_AND_TIMING_SEI
    951       if( m_pcCfg->getPictureTimingSEIEnabled() )
     1095      if( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() )
    9521096      {
    9531097        UInt maxCU = m_pcCfg->getSliceArgument() >> ( pcSlice->getSPS()->getMaxCUDepth() << 1);
     
    9571101          numDU ++;
    9581102        }
    959         pcSlice->getSPS()->getVuiParameters()->setNumDU( numDU );
     1103        pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->setNumDU( numDU );
    9601104        pcSlice->getSPS()->setHrdParameters( m_pcCfg->getFrameRate(), numDU, m_pcCfg->getTargetBitrate(), ( m_pcCfg->getIntraPeriod() > 0 ) );
    9611105      }
    962       if( m_pcCfg->getBufferingPeriodSEIEnabled() || m_pcCfg->getPictureTimingSEIEnabled() )
     1106      if( m_pcCfg->getBufferingPeriodSEIEnabled() || m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() )
    9631107      {
    9641108        pcSlice->getSPS()->getVuiParameters()->setHrdParametersPresentFlag( true );
    9651109      }
    966 #endif
    9671110      m_pcEntropyCoder->encodeSPS(pcSlice->getSPS());
    9681111      writeRBSPTrailingBits(nalu.m_Bitstream);
    9691112      accessUnit.push_back(new NALUnitEBSP(nalu));
     1113#if RATE_CONTROL_LAMBDA_DOMAIN
     1114      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
     1115#endif
    9701116
    9711117#if SVC_EXTENSION
    972 #if REMOVE_NAL_REF_FLAG
    9731118      nalu = NALUnit(NAL_UNIT_PPS, 0, m_layerId);
    9741119#else
    975       nalu = NALUnit(NAL_UNIT_PPS, true, 0, m_layerId);
    976 #endif
    977 #else
    978 #if REMOVE_NAL_REF_FLAG
    9791120      nalu = NALUnit(NAL_UNIT_PPS);
    980 #else
    981       nalu = NALUnit(NAL_UNIT_PPS, true);
    982 #endif
    9831121#endif
    9841122      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
     
    9861124      writeRBSPTrailingBits(nalu.m_Bitstream);
    9871125      accessUnit.push_back(new NALUnitEBSP(nalu));
    988 
    989 #if ACTIVE_PARAMETER_SETS_SEI_MESSAGE 
    990       if(m_pcCfg->getActiveParameterSetsSEIEnabled())
    991       {
    992         SEIActiveParameterSets sei_active_parameter_sets;
    993         sei_active_parameter_sets.activeVPSId = m_pcCfg->getVPS()->getVPSId();
    994         sei_active_parameter_sets.activeSPSIdPresentFlag = m_pcCfg->getActiveParameterSetsSEIEnabled()==2 ? 1 : 0;
    995         if(sei_active_parameter_sets.activeSPSIdPresentFlag)
    996         {
    997           sei_active_parameter_sets.activeSeqParamSetId = pcSlice->getSPS()->getSPSId();
    998         }
    999         sei_active_parameter_sets.activeParamSetSEIExtensionFlag = 0;
    1000 
    1001         nalu = NALUnit(NAL_UNIT_SEI);
    1002         m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
    1003         m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_active_parameter_sets);
    1004         writeRBSPTrailingBits(nalu.m_Bitstream);
    1005         accessUnit.push_back(new NALUnitEBSP(nalu));
    1006       }
    1007 #endif
     1126#if RATE_CONTROL_LAMBDA_DOMAIN
     1127      actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
     1128#endif
     1129
     1130      xCreateLeadingSEIMessages(accessUnit, pcSlice->getSPS());
    10081131
    10091132      m_bSeqFirst = false;
    10101133    }
    10111134
    1012 #if BUFFERING_PERIOD_AND_TIMING_SEI
    1013     if( ( m_pcCfg->getPictureTimingSEIEnabled() ) &&
    1014         ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
    1015         ( ( pcSlice->getSPS()->getVuiParameters()->getNalHrdParametersPresentFlag() ) || ( pcSlice->getSPS()->getVuiParameters()->getVclHrdParametersPresentFlag() ) ) )
    1016     {
    1017       if( pcSlice->getSPS()->getVuiParameters()->getSubPicCpbParamsPresentFlag() )
    1018       {
    1019         UInt numDU = pcSlice->getSPS()->getVuiParameters()->getNumDU();
     1135    if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
     1136        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
     1137        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() )
     1138       || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
     1139    {
     1140      if( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() )
     1141      {
     1142        UInt numDU = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNumDU();
    10201143        pictureTimingSEI.m_numDecodingUnitsMinus1     = ( numDU - 1 );
    1021         pictureTimingSEI.m_duCommonCpbRemovalDelayFlag = 0;
     1144        pictureTimingSEI.m_duCommonCpbRemovalDelayFlag = false;
    10221145
    10231146        if( pictureTimingSEI.m_numNalusInDuMinus1 == NULL )
     
    10381161        }
    10391162      }
    1040       pictureTimingSEI.m_auCpbRemovalDelay = m_totalCoded - m_lastBPSEI;
     1163      pictureTimingSEI.m_auCpbRemovalDelay = std::max<Int>(1, m_totalCoded - m_lastBPSEI); // Syntax element signalled as minus, hence the .
    10411164      pictureTimingSEI.m_picDpbOutputDelay = pcSlice->getSPS()->getNumReorderPics(0) + pcSlice->getPOC() - m_totalCoded;
    1042     }
     1165#if L0044_DU_DPB_OUTPUT_DELAY_HRD
     1166      Int factor = pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2;
     1167      pictureTimingSEI.m_picDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
     1168      if( m_pcCfg->getDecodingUnitInfoSEIEnabled() )
     1169      {
     1170        picSptDpbOutputDuDelay = factor * pictureTimingSEI.m_picDpbOutputDelay;
     1171      }
     1172#endif
     1173    }
     1174
    10431175    if( ( m_pcCfg->getBufferingPeriodSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) &&
    10441176        ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
    1045         ( ( pcSlice->getSPS()->getVuiParameters()->getNalHrdParametersPresentFlag() ) || ( pcSlice->getSPS()->getVuiParameters()->getVclHrdParametersPresentFlag() ) ) )
     1177        ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() )
     1178       || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
    10461179    {
    10471180      OutputNALUnit nalu(NAL_UNIT_SEI);
     
    10571190      sei_buffering_period.m_initialCpbRemovalDelayOffset[0][1]     = uiInitialCpbRemovalDelay;
    10581191
    1059       Double dTmp = (Double)pcSlice->getSPS()->getVuiParameters()->getNumUnitsInTick() / (Double)pcSlice->getSPS()->getVuiParameters()->getTimeScale();
     1192#if L0043_TIMING_INFO
     1193      Double dTmp = (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getNumUnitsInTick() / (Double)pcSlice->getSPS()->getVuiParameters()->getTimingInfo()->getTimeScale();
     1194#else
     1195      Double dTmp = (Double)pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNumUnitsInTick() / (Double)pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTimeScale();
     1196#endif
    10601197
    10611198      UInt uiTmp = (UInt)( dTmp * 90000.0 );
    10621199      uiInitialCpbRemovalDelay -= uiTmp;
    1063       uiInitialCpbRemovalDelay -= uiTmp / ( pcSlice->getSPS()->getVuiParameters()->getTickDivisorMinus2() + 2 );
     1200      uiInitialCpbRemovalDelay -= uiTmp / ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2 );
    10641201      sei_buffering_period.m_initialAltCpbRemovalDelay      [0][0]  = uiInitialCpbRemovalDelay;
    10651202      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][0]  = uiInitialCpbRemovalDelay;
     
    10671204      sei_buffering_period.m_initialAltCpbRemovalDelayOffset[0][1]  = uiInitialCpbRemovalDelay;
    10681205
    1069       sei_buffering_period.m_altCpbParamsPresentFlag              = 0;
    1070       sei_buffering_period.m_sps                                  = pcSlice->getSPS();
    1071 
    1072       m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_buffering_period );
     1206      sei_buffering_period.m_rapCpbParamsPresentFlag              = 0;
     1207#if L0328_SPLICING
     1208      //for the concatenation, it can be set to one during splicing.
     1209      sei_buffering_period.m_concatenationFlag = 0;
     1210      //since the temporal layer HRD is not ready, we assumed it is fixed
     1211      sei_buffering_period.m_auCpbRemovalDelayDelta = 1;
     1212#endif
     1213#if L0044_CPB_DPB_DELAY_OFFSET
     1214      sei_buffering_period.m_cpbDelayOffset = 0;
     1215      sei_buffering_period.m_dpbDelayOffset = 0;
     1216#endif
     1217
     1218      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_buffering_period, pcSlice->getSPS());
    10731219      writeRBSPTrailingBits(nalu.m_Bitstream);
     1220#if L0045_NON_NESTED_SEI_RESTRICTIONS
     1221      UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
     1222      UInt offsetPosition = m_activeParameterSetSEIPresentInAU;   // Insert BP SEI after APS SEI
     1223      AccessUnit::iterator it;
     1224      for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
     1225      {
     1226        it++;
     1227      }
     1228      accessUnit.insert(it, new NALUnitEBSP(nalu));
     1229      m_bufferingPeriodSEIPresentInAU = true;
     1230#else
    10741231      accessUnit.push_back(new NALUnitEBSP(nalu));
     1232#endif
    10751233
    10761234      m_lastBPSEI = m_totalCoded;
     
    10781236    }
    10791237    m_cpbRemovalDelay ++;
    1080 #endif
    1081 #if RECOVERY_POINT_SEI
    10821238    if( ( m_pcEncTop->getRecoveryPointSEIEnabled() ) && ( pcSlice->getSliceType() == I_SLICE ) )
    10831239    {
    1084       // Recovery point SEI
     1240      if( m_pcEncTop->getGradualDecodingRefreshInfoEnabled() && !pcSlice->getRapPicFlag() )
     1241      {
     1242        // Gradual decoding refresh SEI
     1243        OutputNALUnit nalu(NAL_UNIT_SEI);
     1244        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
     1245        m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
     1246
     1247        SEIGradualDecodingRefreshInfo seiGradualDecodingRefreshInfo;
     1248        seiGradualDecodingRefreshInfo.m_gdrForegroundFlag = true; // Indicating all "foreground"
     1249
     1250        m_seiWriter.writeSEImessage( nalu.m_Bitstream, seiGradualDecodingRefreshInfo, pcSlice->getSPS() );
     1251        writeRBSPTrailingBits(nalu.m_Bitstream);
     1252        accessUnit.push_back(new NALUnitEBSP(nalu));
     1253      }
     1254    // Recovery point SEI
    10851255      OutputNALUnit nalu(NAL_UNIT_SEI);
    10861256      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
     
    10921262      sei_recovery_point.m_brokenLinkFlag    = false;
    10931263
    1094       m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_recovery_point );
     1264      m_seiWriter.writeSEImessage( nalu.m_Bitstream, sei_recovery_point, pcSlice->getSPS() );
    10951265      writeRBSPTrailingBits(nalu.m_Bitstream);
    10961266      accessUnit.push_back(new NALUnitEBSP(nalu));
    10971267    }
    1098 #endif
     1268
    10991269    /* use the main bitstream buffer for storing the marshalled picture */
    11001270    m_pcEntropyCoder->setBitstream(NULL);
    11011271
    1102     uiStartCUAddrSliceIdx = 0;
    1103     uiStartCUAddrSlice    = 0;
    1104 
    1105     uiStartCUAddrDependentSliceIdx = 0;
    1106     uiStartCUAddrDependentSlice    = 0;
    1107     uiNextCUAddr                 = 0;
    1108     pcSlice = pcPic->getSlice(uiStartCUAddrSliceIdx);
    1109 
    1110 #if REMOVE_ALF
     1272    startCUAddrSliceIdx = 0;
     1273    startCUAddrSlice    = 0;
     1274
     1275    startCUAddrSliceSegmentIdx = 0;
     1276    startCUAddrSliceSegment    = 0;
     1277    nextCUAddr                 = 0;
     1278    pcSlice = pcPic->getSlice(startCUAddrSliceIdx);
     1279
    11111280    Int processingState = (pcSlice->getSPS()->getUseSAO())?(EXECUTE_INLOOPFILTER):(ENCODE_SLICE);
    1112 #else
    1113     Int processingState = (pcSlice->getSPS()->getUseALF() || pcSlice->getSPS()->getUseSAO())?(EXECUTE_INLOOPFILTER):(ENCODE_SLICE);
    1114 #endif
    1115 #if !REMOVE_APS
    1116     static Int iCurrAPSIdx = 0;
    1117     Int iCodedAPSIdx = 0;
    1118     TComSlice* pcSliceForAPS = NULL;
    1119 #endif
    1120     bool skippedSlice=false;
    1121     while (uiNextCUAddr < uiRealEndAddress) // Iterate over all slices
     1281    Bool skippedSlice=false;
     1282    while (nextCUAddr < uiRealEndAddress) // Iterate over all slices
    11221283    {
    11231284      switch(processingState)
     
    11261287        {
    11271288          pcSlice->setNextSlice       ( false );
    1128           pcSlice->setNextDependentSlice( false );
    1129           if (uiNextCUAddr == m_storedStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx])
    1130           {
    1131             pcSlice = pcPic->getSlice(uiStartCUAddrSliceIdx);
    1132             if(uiStartCUAddrSliceIdx > 0 && pcSlice->getSliceType()!= I_SLICE)
     1289          pcSlice->setNextSliceSegment( false );
     1290          if (nextCUAddr == m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx])
     1291          {
     1292            pcSlice = pcPic->getSlice(startCUAddrSliceIdx);
     1293            if(startCUAddrSliceIdx > 0 && pcSlice->getSliceType()!= I_SLICE)
    11331294            {
    1134               pcSlice->checkColRefIdx(uiStartCUAddrSliceIdx, pcPic);
     1295              pcSlice->checkColRefIdx(startCUAddrSliceIdx, pcPic);
    11351296            }
    1136             pcPic->setCurrSliceIdx(uiStartCUAddrSliceIdx);
    1137             m_pcSliceEncoder->setSliceIdx(uiStartCUAddrSliceIdx);
    1138             assert(uiStartCUAddrSliceIdx == pcSlice->getSliceIdx());
     1297            pcPic->setCurrSliceIdx(startCUAddrSliceIdx);
     1298            m_pcSliceEncoder->setSliceIdx(startCUAddrSliceIdx);
     1299            assert(startCUAddrSliceIdx == pcSlice->getSliceIdx());
    11391300            // Reconstruction slice
    1140             pcSlice->setSliceCurStartCUAddr( uiNextCUAddr );  // to be used in encodeSlice() + context restriction
    1141             pcSlice->setSliceCurEndCUAddr  ( m_storedStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx+1 ] );
     1301            pcSlice->setSliceCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
     1302            pcSlice->setSliceCurEndCUAddr  ( m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx+1 ] );
    11421303            // Dependent slice
    1143             pcSlice->setDependentSliceCurStartCUAddr( uiNextCUAddr );  // to be used in encodeSlice() + context restriction
    1144             pcSlice->setDependentSliceCurEndCUAddr  ( m_storedStartCUAddrForEncodingDependentSlice[uiStartCUAddrDependentSliceIdx+1 ] );
     1304            pcSlice->setSliceSegmentCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
     1305            pcSlice->setSliceSegmentCurEndCUAddr  ( m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx+1 ] );
    11451306
    11461307            pcSlice->setNextSlice       ( true );
    11471308
    1148             uiStartCUAddrSliceIdx++;
    1149             uiStartCUAddrDependentSliceIdx++;
     1309            startCUAddrSliceIdx++;
     1310            startCUAddrSliceSegmentIdx++;
    11501311          }
    1151           else if (uiNextCUAddr == m_storedStartCUAddrForEncodingDependentSlice[uiStartCUAddrDependentSliceIdx])
     1312          else if (nextCUAddr == m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx])
    11521313          {
    11531314            // Dependent slice
    1154             pcSlice->setDependentSliceCurStartCUAddr( uiNextCUAddr );  // to be used in encodeSlice() + context restriction
    1155             pcSlice->setDependentSliceCurEndCUAddr  ( m_storedStartCUAddrForEncodingDependentSlice[uiStartCUAddrDependentSliceIdx+1 ] );
    1156 
    1157             pcSlice->setNextDependentSlice( true );
    1158 
    1159             uiStartCUAddrDependentSliceIdx++;
     1315            pcSlice->setSliceSegmentCurStartCUAddr( nextCUAddr );  // to be used in encodeSlice() + context restriction
     1316            pcSlice->setSliceSegmentCurEndCUAddr  ( m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx+1 ] );
     1317
     1318            pcSlice->setNextSliceSegment( true );
     1319
     1320            startCUAddrSliceSegmentIdx++;
    11601321          }
    11611322
     
    11661327          m_pcSliceEncoder->xDetermineStartAndBoundingCUAddr(uiDummyStartCUAddr,uiDummyBoundingCUAddr,pcPic,true);
    11671328
    1168           uiInternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getDependentSliceCurEndCUAddr()-1) % pcPic->getNumPartInCU();
    1169           uiExternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getDependentSliceCurEndCUAddr()-1) / pcPic->getNumPartInCU();
     1329          uiInternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) % pcPic->getNumPartInCU();
     1330          uiExternalAddress = pcPic->getPicSym()->getPicSCUAddr(pcSlice->getSliceSegmentCurEndCUAddr()-1) / pcPic->getNumPartInCU();
    11701331          uiPosX = ( uiExternalAddress % pcPic->getFrameWidthInCU() ) * g_uiMaxCUWidth+ g_auiRasterToPelX[ g_auiZscanToRaster[uiInternalAddress] ];
    11711332          uiPosY = ( uiExternalAddress / pcPic->getFrameWidthInCU() ) * g_uiMaxCUHeight+ g_auiRasterToPelY[ g_auiZscanToRaster[uiInternalAddress] ];
     
    11841345            uiExternalAddress = pcPic->getPicSym()->getCUOrderMap(pcPic->getPicSym()->getInverseCUOrderMap(uiExternalAddress)+1);
    11851346          }
    1186           UInt uiEndAddress = pcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress);
    1187           if(uiEndAddress<=pcSlice->getDependentSliceCurStartCUAddr()) {
    1188             UInt uiBoundingAddrSlice, uiBoundingAddrDependentSlice;
    1189             uiBoundingAddrSlice          = m_storedStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx];         
    1190             uiBoundingAddrDependentSlice = m_storedStartCUAddrForEncodingDependentSlice[uiStartCUAddrDependentSliceIdx];         
    1191             uiNextCUAddr               = min(uiBoundingAddrSlice, uiBoundingAddrDependentSlice);
     1347          UInt endAddress = pcPic->getPicSym()->getPicSCUEncOrder(uiExternalAddress*pcPic->getNumPartInCU()+uiInternalAddress);
     1348          if(endAddress<=pcSlice->getSliceSegmentCurStartCUAddr())
     1349          {
     1350            UInt boundingAddrSlice, boundingAddrSliceSegment;
     1351            boundingAddrSlice          = m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx];         
     1352            boundingAddrSliceSegment = m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx];         
     1353            nextCUAddr               = min(boundingAddrSlice, boundingAddrSliceSegment);
    11921354            if(pcSlice->isNextSlice())
    11931355            {
     
    11991361          {
    12001362            pcSlice->setNextSlice       ( true );
    1201             pcSlice->setNextDependentSlice( false );
     1363            pcSlice->setNextSliceSegment( false );
    12021364          }
    12031365          skippedSlice=false;
     
    12121374          /* start slice NALunit */
    12131375#if SVC_EXTENSION
    1214 #if REMOVE_NAL_REF_FLAG
    12151376          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer(), m_layerId );
    12161377#else
    1217           OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->isReferenced(), pcSlice->getTLayer(), m_layerId );
    1218 #endif
    1219 #else
    1220 #if REMOVE_NAL_REF_FLAG
    12211378          OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->getTLayer() );
    1222 #else
    1223           OutputNALUnit nalu( pcSlice->getNalUnitType(), pcSlice->isReferenced(), pcSlice->getTLayer() );
    1224 #endif
    1225 #endif
    1226           Bool bDependentSlice = (!pcSlice->isNextSlice());
    1227           if (!bDependentSlice)
     1379#endif
     1380          Bool sliceSegment = (!pcSlice->isNextSlice());
     1381          if (!sliceSegment)
    12281382          {
    12291383            uiOneBitstreamPerSliceLength = 0; // start of a new slice
    12301384          }
    12311385          m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
     1386#if RATE_CONTROL_LAMBDA_DOMAIN
     1387          tmpBitsBeforeWriting = m_pcEntropyCoder->getNumberOfWrittenBits();
     1388#endif
    12321389          m_pcEntropyCoder->encodeSliceHeader(pcSlice);
     1390#if RATE_CONTROL_LAMBDA_DOMAIN
     1391          actualHeadBits += ( m_pcEntropyCoder->getNumberOfWrittenBits() - tmpBitsBeforeWriting );
     1392#endif
    12331393
    12341394          // is it needed?
    12351395          {
    1236             if (!bDependentSlice)
     1396            if (!sliceSegment)
    12371397            {
    12381398              pcBitstreamRedirect->writeAlignOne();
     
    12671427            m_pcEntropyCoder->resetEntropy    ();
    12681428            // File writing
    1269             if (!bDependentSlice)
     1429            if (!sliceSegment)
    12701430            {
    12711431              m_pcEntropyCoder->setBitstream(pcBitstreamRedirect);
     
    12841444
    12851445          pcSlice->setTileOffstForMultES( uiOneBitstreamPerSliceLength );
    1286           if (!bDependentSlice)
     1446          if (!sliceSegment)
    12871447          {
    12881448            pcSlice->setTileLocationCount ( 0 );
     
    13131473              m_pcEntropyCoder->encodeSliceFinish();
    13141474
    1315 #if BYTE_ALIGNMENT 
    13161475              pcSubstreamsOut[ui].writeByteAlignment();   // Byte-alignment in slice_data() at end of sub-stream
    1317 #else
    1318               //!KS: The following writes trailing_bits. Should use proper function call to writeRBSPTrailingBits()
    1319               pcSubstreamsOut[ui].write( 1, 1 ); // stop bit.
    1320               pcSubstreamsOut[ui].writeAlignZero();
    1321 #endif
    13221476              // Byte alignment is necessary between tiles when tiles are independent.
    13231477              uiTotalCodedSize += pcSubstreamsOut[ui].getNumberOfWrittenBits();
    13241478
     1479              Bool bNextSubstreamInNewTile = ((ui+1) < iNumSubstreams)&& ((ui+1)%uiNumSubstreamsPerTile == 0);
     1480              if (bNextSubstreamInNewTile)
    13251481              {
    1326                 Bool bNextSubstreamInNewTile = ((ui+1) < iNumSubstreams)
    1327                   && ((ui+1)%uiNumSubstreamsPerTile == 0);
    1328                 if (bNextSubstreamInNewTile)
    1329                 {
    1330                   // byte align.
    1331                   while (uiTotalCodedSize&0x7)
    1332                   {
    1333                     pcSubstreamsOut[ui].write(0, 1);
    1334                     uiTotalCodedSize++;
    1335                   }
    1336                 }
    1337                 Bool bRecordOffsetNext = bNextSubstreamInNewTile;
    1338                 if (bRecordOffsetNext)
    1339                   pcSlice->setTileLocation(ui/uiNumSubstreamsPerTile, pcSlice->getTileOffstForMultES()+(uiTotalCodedSize>>3));
     1482                pcSlice->setTileLocation(ui/uiNumSubstreamsPerTile, pcSlice->getTileOffstForMultES()+(uiTotalCodedSize>>3));
    13401483              }
    13411484              if (ui+1 < pcSlice->getPPS()->getNumSubstreams())
     1485              {
    13421486                puiSubstreamSizes[ui] = pcSubstreamsOut[ui].getNumberOfWrittenBits();
     1487              }
    13431488            }
    13441489
     
    13501495            // Substreams...
    13511496            TComOutputBitstream *pcOut = pcBitstreamRedirect;
    1352 #if !BYTE_ALIGNMENT
    1353             // xWriteTileLocation will perform byte-alignment...
    1354             {
    1355               if (bDependentSlice)
    1356               {
    1357                 // In these cases, padding is necessary here.
    1358                 pcOut = &nalu.m_Bitstream;
    1359                 pcOut->writeAlignOne();
    1360               }
    1361             }
    1362 #endif
    13631497          Int offs = 0;
    13641498          Int nss = pcSlice->getPPS()->getNumSubstreams();
    1365 #if TILES_WPP_ENTROPYSLICES_FLAGS
    13661499          if (pcSlice->getPPS()->getEntropyCodingSyncEnabledFlag())
    1367 #else
    1368           if (pcSlice->getPPS()->getTilesOrEntropyCodingSyncIdc() == 2)
    1369 #endif
    13701500          {
    13711501            // 1st line present for WPP.
    1372 #if DEPENDENT_SLICES
    1373             offs = pcSlice->getDependentSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU()/pcSlice->getPic()->getFrameWidthInCU();
    1374 #else
    1375             offs = pcSlice->getSliceCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU()/pcSlice->getPic()->getFrameWidthInCU();
    1376 #endif
     1502            offs = pcSlice->getSliceSegmentCurStartCUAddr()/pcSlice->getPic()->getNumPartInCU()/pcSlice->getPic()->getFrameWidthInCU();
    13771503            nss  = pcSlice->getNumEntryPointOffsets()+1;
    13781504          }
     
    13831509          }
    13841510
    1385           UInt uiBoundingAddrSlice, uiBoundingAddrDependentSlice;
    1386           uiBoundingAddrSlice          = m_storedStartCUAddrForEncodingSlice[uiStartCUAddrSliceIdx];         
    1387           uiBoundingAddrDependentSlice = m_storedStartCUAddrForEncodingDependentSlice[uiStartCUAddrDependentSliceIdx];         
    1388           uiNextCUAddr               = min(uiBoundingAddrSlice, uiBoundingAddrDependentSlice);
     1511          UInt boundingAddrSlice, boundingAddrSliceSegment;
     1512          boundingAddrSlice        = m_storedStartCUAddrForEncodingSlice[startCUAddrSliceIdx];         
     1513          boundingAddrSliceSegment = m_storedStartCUAddrForEncodingSliceSegment[startCUAddrSliceSegmentIdx];         
     1514          nextCUAddr               = min(boundingAddrSlice, boundingAddrSliceSegment);
    13891515          // If current NALU is the first NALU of slice (containing slice header) and more NALUs exist (due to multiple dependent slices) then buffer it.
    13901516          // If current NALU is the last NALU of slice and a NALU was buffered, then (a) Write current NALU (b) Update an write buffered NALU at approproate location in NALU list.
     
    13921518          xWriteTileLocationToSliceHeader(nalu, pcBitstreamRedirect, pcSlice);
    13931519          accessUnit.push_back(new NALUnitEBSP(nalu));
     1520#if RATE_CONTROL_LAMBDA_DOMAIN
     1521          actualTotalBits += UInt(accessUnit.back()->m_nalUnitData.str().size()) * 8;
     1522#endif
    13941523          bNALUAlignedWrittenToList = true;
    13951524          uiOneBitstreamPerSliceLength += nalu.m_Bitstream.getNumberOfWrittenBits(); // length of bitstream after byte-alignment
     
    14041533          }
    14051534
    1406 #if BUFFERING_PERIOD_AND_TIMING_SEI
    1407           if( ( m_pcCfg->getPictureTimingSEIEnabled() ) &&
    1408               ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
    1409               ( ( pcSlice->getSPS()->getVuiParameters()->getNalHrdParametersPresentFlag() ) || ( pcSlice->getSPS()->getVuiParameters()->getVclHrdParametersPresentFlag() ) ) &&
    1410               ( pcSlice->getSPS()->getVuiParameters()->getSubPicCpbParamsPresentFlag() ) )
    1411           {
     1535          if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
     1536              ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
     1537              ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() )
     1538             || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) &&
     1539              ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getSubPicCpbParamsPresentFlag() ) )
     1540          {
     1541              UInt numNalus = 0;
    14121542            UInt numRBSPBytes = 0;
    14131543            for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
    14141544            {
    14151545              UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
    1416               if ((*it)->m_nalUnitType != NAL_UNIT_SEI)
     1546              if ((*it)->m_nalUnitType != NAL_UNIT_SEI && (*it)->m_nalUnitType != NAL_UNIT_SEI_SUFFIX)
    14171547              {
    14181548                numRBSPBytes += numRBSPBytes_nal;
     1549                numNalus ++;
    14191550              }
    14201551            }
    14211552            accumBitsDU[ pcSlice->getSliceIdx() ] = ( numRBSPBytes << 3 );
    1422             accumNalsDU[ pcSlice->getSliceIdx() ] = (UInt)accessUnit.size();
    1423           }
    1424 #endif
     1553            accumNalsDU[ pcSlice->getSliceIdx() ] = numNalus;   // SEI not counted for bit count; hence shouldn't be counted for # of NALUs - only for consistency
     1554          }
    14251555          processingState = ENCODE_SLICE;
    14261556          }
     
    14281558        case EXECUTE_INLOOPFILTER:
    14291559          {
    1430 #if !REMOVE_APS
    1431             TComAPS cAPS;
    1432             allocAPS(&cAPS, pcSlice->getSPS());
    1433 #endif
    14341560            // set entropy coder for RD
    14351561            m_pcEntropyCoder->setEntropyCoder ( m_pcSbacCoder, pcSlice );
     
    14391565              m_pcEntropyCoder->setBitstream( m_pcBitCounter );
    14401566              m_pcSAO->startSaoEnc(pcPic, m_pcEntropyCoder, m_pcEncTop->getRDSbacCoder(), m_pcEncTop->getRDGoOnSbacCoder());
    1441 #if REMOVE_APS
    14421567              SAOParam& cSaoParam = *pcSlice->getPic()->getPicSym()->getSaoParam();
    1443 #else
    1444               SAOParam& cSaoParam = *(cAPS.getSaoParam());
    1445 #endif
    14461568
    14471569#if SAO_CHROMA_LAMBDA
     
    14521574#endif
    14531575#else
    1454 #if ALF_CHROMA_LAMBDA
    1455               m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma());
    1456 #else
    14571576              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambda());
    14581577#endif
    1459 #endif
    14601578              m_pcSAO->endSaoEnc();
    1461 #if !REMOVE_ALF
    1462               m_pcAdaptiveLoopFilter->PCMLFDisableProcess(pcPic);
    1463 #else
    14641579              m_pcSAO->PCMLFDisableProcess(pcPic);
    1465 #endif
    14661580            }
    14671581#if SAO_RDO
    14681582            m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
    14691583#endif
    1470             // adaptive loop filter
    1471 #if !REMOVE_ALF
    1472             if ( pcSlice->getSPS()->getUseALF())
    1473             {
    1474 #if ALF_CHROMA_LAMBDA
    1475               m_pcAdaptiveLoopFilter->ALFProcess(cAPS.getAlfParam(), pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma() );
    1476 #else
    1477 #if SAO_CHROMA_LAMBDA
    1478               m_pcAdaptiveLoopFilter->ALFProcess(cAPS.getAlfParam(), pcPic->getSlice(0)->getLambdaLuma());
    1479 #else
    1480               m_pcAdaptiveLoopFilter->ALFProcess(cAPS.getAlfParam(), pcPic->getSlice(0)->getLambda());
    1481 #endif
    1482 #endif
    1483               m_pcAdaptiveLoopFilter->PCMLFDisableProcess(pcPic);
    1484             }
    1485 #endif
    1486 #if !REMOVE_APS
    1487             iCodedAPSIdx = iCurrAPSIdx;
    1488             pcSliceForAPS = pcSlice;
    1489 
    1490             assignNewAPS(cAPS, iCodedAPSIdx, vAPS, pcSliceForAPS);
    1491             iCurrAPSIdx = (iCurrAPSIdx +1)%MAX_NUM_SUPPORTED_APS;
    1492 #endif
    1493             processingState = ENCODE_APS;
    1494 
    1495             //set APS link to the slices
     1584            processingState = ENCODE_SLICE;
     1585
    14961586            for(Int s=0; s< uiNumSlices; s++)
    14971587            {
    1498 #if !REMOVE_ALF
    1499               if (pcSlice->getSPS()->getUseALF())
    1500               {
    1501                 for(Int compIdx =0; compIdx< 3; compIdx++)
    1502                 {
    1503                   pcPic->getSlice(s)->setAlfEnabledFlag( cAPS.getAlfEnabled(compIdx), compIdx);
    1504                 }
    1505               }
    1506 #endif
    15071588              if (pcSlice->getSPS()->getUseSAO())
    15081589              {
    1509 #if REMOVE_APS
    15101590                pcPic->getSlice(s)->setSaoEnabledFlag((pcSlice->getPic()->getPicSym()->getSaoParam()->bSaoFlag[0]==1)?true:false);
    1511 #else
    1512                 pcPic->getSlice(s)->setSaoEnabledFlag((cAPS.getSaoParam()->bSaoFlag[0]==1)?true:false);
    1513 #endif
    15141591              }
    1515 #if !REMOVE_APS
    1516               pcPic->getSlice(s)->setAPS(&(vAPS[iCodedAPSIdx]));
    1517               pcPic->getSlice(s)->setAPSId(iCodedAPSIdx);
    1518 #endif
    15191592            }
    1520 
    1521             /* The destructor of cAPS that is about to be called will free
    1522              * the resource held by cAPS, which will cause problems since it
    1523              * has been aliased elsewhere.
    1524              *   Hint: never ever write an assignment operator that copies
    1525              *         pointers without the use of smart pointers.
    1526              * The following will clear the saved state before the destructor.
    1527              */
    1528 #if !REMOVE_APS
    1529             cAPS = TComAPS();
    1530 #endif
    1531           }
    1532           break;
    1533         case ENCODE_APS:
    1534           {
    1535 #if !REMOVE_APS
    1536             OutputNALUnit nalu(NAL_UNIT_APS, true);
    1537             encodeAPS(&(vAPS[iCodedAPSIdx]), nalu.m_Bitstream, pcSliceForAPS);
    1538             accessUnit.push_back(new NALUnitEBSP(nalu));
    1539 #endif
    1540             processingState = ENCODE_SLICE;
    15411593          }
    15421594          break;
     
    15501602      } // end iteration over slices
    15511603
    1552 #if REMOVE_ALF
    15531604      if(pcSlice->getSPS()->getUseSAO())
    1554 #else
    1555       if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
    1556 #endif
    15571605      {
    15581606        if(pcSlice->getSPS()->getUseSAO())
     
    15601608          m_pcSAO->destroyPicSaoInfo();
    15611609        }
    1562 #if !REMOVE_ALF
    1563         if(pcSlice->getSPS()->getUseALF())
    1564         {
    1565           m_pcAdaptiveLoopFilter->destroyPicAlfInfo();
    1566         }
    1567 #endif
    15681610        pcPic->destroyNonDBFilterInfo();
    15691611      }
     
    15721614     
    15731615      //-- For time output for each slice
    1574       Double dEncTime = (double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
    1575 
    1576       const char* digestStr = NULL;
     1616      Double dEncTime = (Double)(clock()-iBeforeTime) / CLOCKS_PER_SEC;
     1617
     1618      const Char* digestStr = NULL;
    15771619      if (m_pcCfg->getDecodedPictureHashSEIEnabled())
    15781620      {
     
    15981640        }
    15991641#if SVC_EXTENSION
    1600 #if REMOVE_NAL_REF_FLAG
    1601         OutputNALUnit nalu(NAL_UNIT_SEI, pcSlice->getTLayer(), m_layerId);
     1642        OutputNALUnit nalu(NAL_UNIT_SEI_SUFFIX, pcSlice->getTLayer(), m_layerId);
    16021643#else
    1603         OutputNALUnit nalu(NAL_UNIT_SEI, false, pcSlice->getTLayer(), m_layerId);
    1604 #endif
    1605 #else
    1606 #if REMOVE_NAL_REF_FLAG
    1607         OutputNALUnit nalu(NAL_UNIT_SEI, pcSlice->getTLayer());
    1608 #else
    1609         OutputNALUnit nalu(NAL_UNIT_SEI, false, pcSlice->getTLayer());
    1610 #endif
     1644        OutputNALUnit nalu(NAL_UNIT_SEI_SUFFIX, pcSlice->getTLayer());
    16111645#endif
    16121646
    16131647        /* write the SEI messages */
    16141648        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
    1615         m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_recon_picture_digest);
     1649        m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_recon_picture_digest, pcSlice->getSPS());
     1650        writeRBSPTrailingBits(nalu.m_Bitstream);
     1651
     1652        accessUnit.insert(accessUnit.end(), new NALUnitEBSP(nalu));
     1653      }
     1654      if (m_pcCfg->getTemporalLevel0IndexSEIEnabled())
     1655      {
     1656        SEITemporalLevel0Index sei_temporal_level0_index;
     1657        if (pcSlice->getRapPicFlag())
     1658        {
     1659          m_tl0Idx = 0;
     1660          m_rapIdx = (m_rapIdx + 1) & 0xFF;
     1661        }
     1662        else
     1663        {
     1664          m_tl0Idx = (m_tl0Idx + (pcSlice->getTLayer() ? 0 : 1)) & 0xFF;
     1665        }
     1666        sei_temporal_level0_index.tl0Idx = m_tl0Idx;
     1667        sei_temporal_level0_index.rapIdx = m_rapIdx;
     1668
     1669        OutputNALUnit nalu(NAL_UNIT_SEI);
     1670
     1671        /* write the SEI messages */
     1672        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
     1673        m_seiWriter.writeSEImessage(nalu.m_Bitstream, sei_temporal_level0_index, pcSlice->getSPS());
    16161674        writeRBSPTrailingBits(nalu.m_Bitstream);
    16171675
     
    16381696        }
    16391697      }
     1698#if RATE_CONTROL_LAMBDA_DOMAIN
     1699      if ( m_pcCfg->getUseRateCtrl() )
     1700      {
     1701        Double effectivePercentage = m_pcRateCtrl->getRCPic()->getEffectivePercentage();
     1702        Double avgQP     = m_pcRateCtrl->getRCPic()->calAverageQP();
     1703        Double avgLambda = m_pcRateCtrl->getRCPic()->calAverageLambda();
     1704        if ( avgLambda < 0.0 )
     1705        {
     1706          avgLambda = lambda;
     1707        }
     1708        m_pcRateCtrl->getRCPic()->updateAfterPicture( actualHeadBits, actualTotalBits, avgQP, avgLambda, effectivePercentage );
     1709        m_pcRateCtrl->getRCPic()->addToPictureLsit( m_pcRateCtrl->getPicList() );
     1710
     1711        m_pcRateCtrl->getRCSeq()->updateAfterPic( actualTotalBits );
     1712        if ( pcSlice->getSliceType() != I_SLICE )
     1713        {
     1714          m_pcRateCtrl->getRCGOP()->updateAfterPicture( actualTotalBits );
     1715        }
     1716        else    // for intra picture, the estimated bits are used to update the current status in the GOP
     1717        {
     1718          m_pcRateCtrl->getRCGOP()->updateAfterPicture( estimatedBits );
     1719        }
     1720      }
     1721#else
    16401722      if(m_pcCfg->getUseRateCtrl())
    16411723      {
    1642         unsigned  frameBits = m_vRVM_RP[m_vRVM_RP.size()-1];
     1724        UInt  frameBits = m_vRVM_RP[m_vRVM_RP.size()-1];
    16431725        m_pcRateCtrl->updataRCFrameStatus((Int)frameBits, pcSlice->getSliceType());
    16441726      }
    1645 #if BUFFERING_PERIOD_AND_TIMING_SEI
    1646       if( ( m_pcCfg->getPictureTimingSEIEnabled() ) &&
    1647           ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) && 
    1648           ( ( pcSlice->getSPS()->getVuiParameters()->getNalHrdParametersPresentFlag() ) || ( pcSlice->getSPS()->getVuiParameters()->getVclHrdParametersPresentFlag() ) ) )
    1649       {
    1650         OutputNALUnit nalu(NAL_UNIT_SEI, pcSlice->getTLayer());
     1727#endif
     1728      if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
     1729          ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
     1730          ( ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getNalHrdParametersPresentFlag() )
     1731         || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
     1732      {
    16511733        TComVUI *vui = pcSlice->getSPS()->getVuiParameters();
    1652 
    1653         if( vui->getSubPicCpbParamsPresentFlag() )
     1734        TComHRD *hrd = vui->getHrdParameters();
     1735
     1736        if( hrd->getSubPicCpbParamsPresentFlag() )
    16541737        {
    16551738          Int i;
    16561739          UInt64 ui64Tmp;
    1657           UInt uiTmp, uiPrev, uiCurr;
    1658 
    1659           uiPrev = 0;
    1660           for( i = 0; i < ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 ); i ++ )
    1661           {
    1662             pictureTimingSEI.m_numNalusInDuMinus1[ i ]       = ( i == 0 ) ? ( accumNalsDU[ i ] ) : ( accumNalsDU[ i ] - accumNalsDU[ i - 1] - 1 );
    1663             ui64Tmp = ( ( ( accumBitsDU[ pictureTimingSEI.m_numDecodingUnitsMinus1 ] - accumBitsDU[ i ] ) * ( vui->getTimeScale() / vui->getNumUnitsInTick() ) * ( vui->getTickDivisorMinus2() + 2 ) )
    1664                         / ( m_pcCfg->getTargetBitrate() << 10 ) );
    1665 
    1666             uiTmp = (UInt)ui64Tmp;
    1667             if( uiTmp >= ( vui->getTickDivisorMinus2() + 2 ) )      uiCurr = 0;
    1668             else                                                     uiCurr = ( vui->getTickDivisorMinus2() + 2 ) - uiTmp;
    1669 
    1670             if( i == pictureTimingSEI.m_numDecodingUnitsMinus1 ) uiCurr = vui->getTickDivisorMinus2() + 2;
    1671             if( uiCurr <= uiPrev )                                   uiCurr = uiPrev + 1;
    1672 
    1673             pictureTimingSEI.m_duCpbRemovalDelayMinus1[ i ]              = (uiCurr - uiPrev) - 1;
    1674             uiPrev = uiCurr;
    1675           }
    1676         }
    1677         m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
    1678         pictureTimingSEI.m_sps = pcSlice->getSPS();
    1679         m_seiWriter.writeSEImessage(nalu.m_Bitstream, pictureTimingSEI);
    1680         writeRBSPTrailingBits(nalu.m_Bitstream);
    1681 
    1682         AccessUnit::iterator it = find_if(accessUnit.begin(), accessUnit.end(), mem_fun(&NALUnit::isSlice));
    1683         accessUnit.insert(it, new NALUnitEBSP(nalu));
    1684       }
    1685 #endif
    1686 #if FIXED_ROUNDING_FRAME_MEMORY
    1687       /* TODO: this should happen after copyToPic(pcPicYuvRecOut) */
    1688       pcPic->getPicYuvRec()->xFixedRoundingPic();
     1740          UInt uiPrev = 0;
     1741          UInt numDU = ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 );
     1742          UInt *pCRD = &pictureTimingSEI.m_duCpbRemovalDelayMinus1[0];
     1743          UInt maxDiff = ( hrd->getTickDivisorMinus2() + 2 ) - 1;
     1744
     1745          for( i = 0; i < numDU; i ++ )
     1746          {
     1747            pictureTimingSEI.m_numNalusInDuMinus1[ i ]       = ( i == 0 ) ? ( accumNalsDU[ i ] - 1 ) : ( accumNalsDU[ i ] - accumNalsDU[ i - 1] - 1 );
     1748          }
     1749
     1750          if( numDU == 1 )
     1751          {
     1752            pCRD[ 0 ] = 0; /* don't care */
     1753          }
     1754          else
     1755          {
     1756            pCRD[ numDU - 1 ] = 0;/* by definition */
     1757            UInt tmp = 0;
     1758            UInt accum = 0;
     1759
     1760            for( i = ( numDU - 2 ); i >= 0; i -- )
     1761            {
     1762#if L0043_TIMING_INFO
     1763              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
     1764#else
     1765              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( hrd->getTimeScale() / hrd->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
     1766#endif
     1767              if( (UInt)ui64Tmp > maxDiff )
     1768              {
     1769                tmp ++;
     1770              }
     1771            }
     1772            uiPrev = 0;
     1773
     1774            UInt flag = 0;
     1775            for( i = ( numDU - 2 ); i >= 0; i -- )
     1776            {
     1777              flag = 0;
     1778#if L0043_TIMING_INFO
     1779              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( vui->getTimingInfo()->getTimeScale() / vui->getTimingInfo()->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
     1780#else
     1781              ui64Tmp = ( ( ( accumBitsDU[ numDU - 1 ]  - accumBitsDU[ i ] ) * ( hrd->getTimeScale() / hrd->getNumUnitsInTick() ) * ( hrd->getTickDivisorMinus2() + 2 ) ) / ( m_pcCfg->getTargetBitrate() ) );
     1782#endif
     1783
     1784              if( (UInt)ui64Tmp > maxDiff )
     1785              {
     1786                if(uiPrev >= maxDiff - tmp)
     1787                {
     1788                  ui64Tmp = uiPrev + 1;
     1789                  flag = 1;
     1790                }
     1791                else                            ui64Tmp = maxDiff - tmp + 1;
     1792              }
     1793              pCRD[ i ] = (UInt)ui64Tmp - uiPrev - 1;
     1794              if( (Int)pCRD[ i ] < 0 )
     1795              {
     1796                pCRD[ i ] = 0;
     1797              }
     1798              else if (tmp > 0 && flag == 1)
     1799              {
     1800                tmp --;
     1801              }
     1802              accum += pCRD[ i ] + 1;
     1803              uiPrev = accum;
     1804            }
     1805          }
     1806        }
     1807        if( m_pcCfg->getPictureTimingSEIEnabled() )
     1808        {
     1809          OutputNALUnit nalu(NAL_UNIT_SEI, pcSlice->getTLayer());
     1810          m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
     1811          m_seiWriter.writeSEImessage(nalu.m_Bitstream, pictureTimingSEI, pcSlice->getSPS());
     1812          writeRBSPTrailingBits(nalu.m_Bitstream);
     1813#if L0045_NON_NESTED_SEI_RESTRICTIONS
     1814          UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
     1815          UInt offsetPosition = m_activeParameterSetSEIPresentInAU
     1816                                    + m_bufferingPeriodSEIPresentInAU;    // Insert PT SEI after APS and BP SEI
     1817          AccessUnit::iterator it;
     1818          for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
     1819          {
     1820            it++;
     1821          }
     1822          accessUnit.insert(it, new NALUnitEBSP(nalu));
     1823          m_pictureTimingSEIPresentInAU = true;
     1824#else
     1825          AccessUnit::iterator it = find_if(accessUnit.begin(), accessUnit.end(), mem_fun(&NALUnit::isSlice));
     1826          accessUnit.insert(it, new NALUnitEBSP(nalu));
     1827#endif
     1828        }
     1829        if( m_pcCfg->getDecodingUnitInfoSEIEnabled() && hrd->getSubPicCpbParamsPresentFlag() )
     1830        {             
     1831          m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
     1832          for( Int i = 0; i < ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 ); i ++ )
     1833          {
     1834            OutputNALUnit nalu(NAL_UNIT_SEI, pcSlice->getTLayer());
     1835
     1836            SEIDecodingUnitInfo tempSEI;
     1837            tempSEI.m_decodingUnitIdx = i;
     1838            tempSEI.m_duSptCpbRemovalDelay = pictureTimingSEI.m_duCpbRemovalDelayMinus1[i] + 1;
     1839#if L0044_DU_DPB_OUTPUT_DELAY_HRD
     1840            tempSEI.m_dpbOutputDuDelayPresentFlag = false;
     1841            tempSEI.m_picSptDpbOutputDuDelay = picSptDpbOutputDuDelay;
     1842#endif
     1843
     1844            AccessUnit::iterator it;
     1845            // Insert the first one in the right location, before the first slice
     1846            if(i == 0)
     1847            {
     1848              // Insert before the first slice.
     1849              m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, pcSlice->getSPS());
     1850              writeRBSPTrailingBits(nalu.m_Bitstream);
     1851
     1852#if L0045_NON_NESTED_SEI_RESTRICTIONS
     1853              UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
     1854              UInt offsetPosition = m_activeParameterSetSEIPresentInAU
     1855                                    + m_bufferingPeriodSEIPresentInAU
     1856                                    + m_pictureTimingSEIPresentInAU;  // Insert DU info SEI after APS, BP and PT SEI
     1857              for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
     1858              {
     1859                it++;
     1860              }
     1861              accessUnit.insert(it, new NALUnitEBSP(nalu));
     1862#else
     1863              it = find_if(accessUnit.begin(), accessUnit.end(), mem_fun(&NALUnit::isSlice));
     1864              accessUnit.insert(it, new NALUnitEBSP(nalu));
     1865#endif
     1866            }
     1867            else
     1868            {
     1869              Int ctr;
     1870              // For the second decoding unit onwards we know how many NALUs are present
     1871              for (ctr = 0, it = accessUnit.begin(); it != accessUnit.end(); it++)
     1872              {           
     1873                if(ctr == accumNalsDU[ i - 1 ])
     1874                {
     1875                  // Insert before the first slice.
     1876                  m_seiWriter.writeSEImessage(nalu.m_Bitstream, tempSEI, pcSlice->getSPS());
     1877                  writeRBSPTrailingBits(nalu.m_Bitstream);
     1878
     1879                  accessUnit.insert(it, new NALUnitEBSP(nalu));
     1880                  break;
     1881                }
     1882                if ((*it)->m_nalUnitType != NAL_UNIT_SEI && (*it)->m_nalUnitType != NAL_UNIT_SEI_SUFFIX)
     1883                {
     1884                  ctr++;
     1885                }
     1886              }
     1887            }           
     1888          }
     1889        }
     1890      }
     1891#if L0045_NON_NESTED_SEI_RESTRICTIONS
     1892      xResetNonNestedSEIPresentFlags();
    16891893#endif
    16901894      pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
     
    16931897      m_bFirst = false;
    16941898      m_iNumPicCoded++;
    1695 #if BUFFERING_PERIOD_AND_TIMING_SEI
    16961899      m_totalCoded ++;
    1697 #endif
    16981900      /* logging: insert a newline at end of picture period */
    16991901      printf("\n");
     
    17021904      delete[] pcSubstreamsOut;
    17031905  }
     1906#if !RATE_CONTROL_LAMBDA_DOMAIN
    17041907  if(m_pcCfg->getUseRateCtrl())
    17051908  {
    17061909    m_pcRateCtrl->updateRCGOPStatus();
    17071910  }
     1911#endif
    17081912  delete pcBitstreamRedirect;
    17091913
    1710 #if BUFFERING_PERIOD_AND_TIMING_SEI
    17111914  if( accumBitsDU != NULL) delete accumBitsDU;
    17121915  if( accumNalsDU != NULL) delete accumNalsDU;
    1713 #endif
    17141916
    17151917#if SVC_EXTENSION
     
    17191921#endif
    17201922}
    1721 
    1722 #if !REMOVE_APS
    1723 /** Memory allocation for APS
    1724   * \param [out] pAPS APS pointer
    1725   * \param [in] pSPS SPS pointer
    1726   */
    1727 Void TEncGOP::allocAPS (TComAPS* pAPS, TComSPS* pSPS)
    1728 {
    1729   if(pSPS->getUseSAO())
    1730   {
    1731     pAPS->createSaoParam();
    1732     m_pcSAO->allocSaoParam(pAPS->getSaoParam());
    1733   }
    1734 #if !REMOVE_ALF
    1735   pAPS->createAlfParam();
    1736 #endif
    1737 }
    1738 
    1739 /** Memory deallocation for APS
    1740   * \param [out] pAPS APS pointer
    1741   * \param [in] pSPS SPS pointer
    1742   */
    1743 Void TEncGOP::freeAPS (TComAPS* pAPS, TComSPS* pSPS)
    1744 {
    1745   if(pSPS->getUseSAO())
    1746   {
    1747     if(pAPS->getSaoParam() != NULL)
    1748     {
    1749       m_pcSAO->freeSaoParam(pAPS->getSaoParam());
    1750       pAPS->destroySaoParam();
    1751 
    1752     }
    1753   }
    1754 #if !REMOVE_ALF
    1755   pAPS->destroyAlfParam();
    1756 #endif
    1757 }
    1758 
    1759 /** Assign APS object into APS container according to APS ID
    1760   * \param [in] cAPS APS object
    1761   * \param [in] apsID APS ID
    1762   * \param [in,out] vAPS APS container
    1763   * \param [in] pcSlice pointer to slice
    1764   */
    1765 Void TEncGOP::assignNewAPS(TComAPS& cAPS, Int apsID, std::vector<TComAPS>& vAPS, TComSlice* pcSlice)
    1766 {
    1767 
    1768   cAPS.setAPSID(apsID);
    1769 
    1770   //assign new APS into APS container
    1771   Int apsBufSize= (Int)vAPS.size();
    1772 
    1773   if(apsID >= apsBufSize)
    1774   {
    1775     vAPS.resize(apsID +1);
    1776   }
    1777 
    1778   freeAPS(&(vAPS[apsID]), pcSlice->getSPS());
    1779   vAPS[apsID] = cAPS;
    1780 }
    1781 
    1782 /** encode APS syntax elements
    1783   * \param [in] pcAPS APS pointer
    1784   * \param [in, out] APSbs bitstream
    1785   * \param [in] pointer to slice (just used for entropy coder initialization)
    1786   */
    1787 Void TEncGOP::encodeAPS(TComAPS* pcAPS, TComOutputBitstream& APSbs, TComSlice* pcSlice)
    1788 {
    1789   m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder, pcSlice);
    1790   m_pcEntropyCoder->resetEntropy      ();
    1791   m_pcEntropyCoder->setBitstream(&APSbs);
    1792 
    1793   m_pcEntropyCoder->encodeAPSInitInfo(pcAPS);
    1794 #if !REMOVE_ALF
    1795   for(Int compIdx=0; compIdx < 3; compIdx++)
    1796   {
    1797     m_pcEntropyCoder->encodeAlfParam( (pcAPS->getAlfParam())[compIdx]);
    1798   }
    1799 #endif
    1800   m_pcEntropyCoder->encodeApsExtensionFlag();
    1801   //neither SAO and ALF is enabled
    1802   writeRBSPTrailingBits(APSbs);
    1803 }
    1804 #endif
    18051923
    18061924#if !SVC_EXTENSION
     
    18461964  TComSlice* pcSlice = pcPic->getSlice(pcPic->getCurrSliceIdx());
    18471965  Bool bCalcDist = false;
    1848   m_pcLoopFilter->setCfg(pcSlice->getPPS()->getDeblockingFilterControlPresentFlag(), pcSlice->getDeblockingFilterDisable(), m_pcCfg->getLoopFilterBetaOffset(), m_pcCfg->getLoopFilterTcOffset(), m_pcCfg->getLFCrossTileBoundaryFlag());
     1966  m_pcLoopFilter->setCfg(m_pcCfg->getLFCrossTileBoundaryFlag());
    18491967  m_pcLoopFilter->loopFilterPic( pcPic );
    18501968 
     
    18531971  m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
    18541972  pcSlice = pcPic->getSlice(0);
    1855 #if REMOVE_ALF
    18561973  if(pcSlice->getSPS()->getUseSAO())
    1857 #else
    1858   if(pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
    1859 #endif
    18601974  {
    18611975    std::vector<Bool> LFCrossSliceBoundaryFlag(1, true);
     
    18661980  }
    18671981 
    1868 #if !REMOVE_ALF
    1869   // Adaptive Loop filter
    1870   if( pcSlice->getSPS()->getUseALF() )
    1871   {
    1872     m_pcAdaptiveLoopFilter->createPicAlfInfo(pcPic);
    1873 
    1874     ALFParam* alfPicParam[3];
    1875     for(Int compIdx=0; compIdx < 3; compIdx++)
    1876     {
    1877       alfPicParam[compIdx] = new ALFParam(compIdx);
    1878     }
    1879 
    1880 #if ALF_CHROMA_LAMBDA
    1881     m_pcAdaptiveLoopFilter->ALFProcess(alfPicParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma() );
    1882 #else
    1883 #if SAO_CHROMA_LAMBDA
    1884     m_pcAdaptiveLoopFilter->ALFProcess(alfPicParam, pcPic->getSlice(0)->getLambdaLuma());
    1885 #else
    1886     m_pcAdaptiveLoopFilter->ALFProcess(alfPicParam, pcPic->getSlice(0)->getLambda());
    1887 #endif
    1888 #endif
    1889     for(Int compIdx=0; compIdx < 3; compIdx++)
    1890     {
    1891       delete alfPicParam[compIdx]; alfPicParam[compIdx] = NULL;
    1892     }
    1893     m_pcAdaptiveLoopFilter->PCMLFDisableProcess(pcPic);
    1894     m_pcAdaptiveLoopFilter->destroyPicAlfInfo();
    1895   }
    1896 #endif
    1897 #if REMOVE_ALF
    18981982  if( pcSlice->getSPS()->getUseSAO())
    1899 #else
    1900   if( pcSlice->getSPS()->getUseSAO() || pcSlice->getSPS()->getUseALF())
    1901 #endif
    19021983  {
    19031984    pcPic->destroyNonDBFilterInfo();
     
    19312012}
    19322013
    1933 Void TEncGOP::xGetBuffer( TComList<TComPic*>&       rcListPic,
     2014Void TEncGOP::xGetBuffer( TComList<TComPic*>&      rcListPic,
    19342015                         TComList<TComPicYuv*>&    rcListPicYuvRecOut,
    19352016                         Int                       iNumPicRcvd,
     
    19372018                         TComPic*&                 rpcPic,
    19382019                         TComPicYuv*&              rpcPicYuvRecOut,
    1939                          UInt                      uiPOCCurr )
     2020                         Int                       pocCurr )
    19402021{
    19412022  Int i;
     
    19552036    rpcPic = *(iterPic);
    19562037    rpcPic->setCurrSliceIdx(0);
    1957     if (rpcPic->getPOC() == (Int)uiPOCCurr)
     2038    if (rpcPic->getPOC() == pocCurr)
    19582039    {
    19592040      break;
     
    19622043  }
    19632044 
    1964   assert (rpcPic->getPOC() == (Int)uiPOCCurr);
     2045  assert (rpcPic->getPOC() == pocCurr);
    19652046 
    19662047  return;
     
    19722053  Pel*  pSrc0   = pcPic0 ->getLumaAddr();
    19732054  Pel*  pSrc1   = pcPic1 ->getLumaAddr();
    1974 #if IBDI_DISTORTION
    1975   Int  iShift = g_uiBitIncrement;
    1976   Int  iOffset = 1<<(g_uiBitIncrement-1);
    1977 #else
    1978   UInt  uiShift = g_uiBitIncrement<<1;
    1979 #endif
     2055  UInt  uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthY-8);
    19802056  Int   iTemp;
    19812057 
     
    19902066    for( x = 0; x < iWidth; x++ )
    19912067    {
    1992 #if IBDI_DISTORTION
    1993       iTemp = ((pSrc0[x]+iOffset)>>iShift) - ((pSrc1[x]+iOffset)>>iShift); uiTotalDiff += iTemp * iTemp;
    1994 #else
    19952068      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
    1996 #endif
    19972069    }
    19982070    pSrc0 += iStride;
     
    20002072  }
    20012073 
     2074  uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthC-8);
    20022075  iHeight >>= 1;
    20032076  iWidth  >>= 1;
     
    20112084    for( x = 0; x < iWidth; x++ )
    20122085    {
    2013 #if IBDI_DISTORTION
    2014       iTemp = ((pSrc0[x]+iOffset)>>iShift) - ((pSrc1[x]+iOffset)>>iShift); uiTotalDiff += iTemp * iTemp;
    2015 #else
    20162086      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
    2017 #endif
    20182087    }
    20192088    pSrc0 += iStride;
     
    20282097    for( x = 0; x < iWidth; x++ )
    20292098    {
    2030 #if IBDI_DISTORTION
    2031       iTemp = ((pSrc0[x]+iOffset)>>iShift) - ((pSrc1[x]+iOffset)>>iShift); uiTotalDiff += iTemp * iTemp;
    2032 #else
    20332099      iTemp = pSrc0[x] - pSrc1[x]; uiTotalDiff += (iTemp*iTemp) >> uiShift;
    2034 #endif
    20352100    }
    20362101    pSrc0 += iStride;
     
    20422107
    20432108#if VERBOSE_RATE
    2044 static const char* nalUnitTypeToString(NalUnitType type)
     2109static const Char* nalUnitTypeToString(NalUnitType type)
    20452110{
    20462111  switch (type)
    20472112  {
    2048 #if NAL_UNIT_TYPES_J1003_D7
    20492113    case NAL_UNIT_CODED_SLICE_TRAIL_R: return "TRAIL_R";
    20502114    case NAL_UNIT_CODED_SLICE_TRAIL_N: return "TRAIL_N";
     
    20612125    case NAL_UNIT_CODED_SLICE_DLP: return "DLP";
    20622126    case NAL_UNIT_CODED_SLICE_TFD: return "TFD";
    2063 #else
    2064     case NAL_UNIT_CODED_SLICE: return "SLICE";
    2065     case NAL_UNIT_CODED_SLICE_TFD: return "TFD";
    2066     case NAL_UNIT_CODED_SLICE_TLA: return "TLA";
    2067     case NAL_UNIT_CODED_SLICE_CRA: return "CRA";
    2068     case NAL_UNIT_CODED_SLICE_CRANT: return "CRANT";
    2069     case NAL_UNIT_CODED_SLICE_BLA: return "BLA";
    2070     case NAL_UNIT_CODED_SLICE_BLANT: return "BLANT";
    2071     case NAL_UNIT_CODED_SLICE_IDR: return "IDR";
    2072 #endif
    20732127    case NAL_UNIT_VPS: return "VPS";
    20742128    case NAL_UNIT_SPS: return "SPS";
    20752129    case NAL_UNIT_PPS: return "PPS";
    2076 #if NAL_UNIT_TYPES_J1003_D7
    20772130    case NAL_UNIT_ACCESS_UNIT_DELIMITER: return "AUD";
    20782131    case NAL_UNIT_EOS: return "EOS";
     
    20802133    case NAL_UNIT_FILLER_DATA: return "FILLER";
    20812134    case NAL_UNIT_SEI: return "SEI";
    2082 #else
    2083     case NAL_UNIT_APS: return "APS";
    2084     case NAL_UNIT_ACCESS_UNIT_DELIMITER: return "AUD";
    2085     case NAL_UNIT_FILLER_DATA: return "FILLER";
    2086     case NAL_UNIT_SEI: return "SEI";
    2087 #endif
    20882135    default: return "UNK";
    20892136  }
     
    21572204  }
    21582205 
    2159   unsigned int maxval = 255 * (1<<(g_uiBitDepth + g_uiBitIncrement -8));
    2160   Double fRefValueY = (double) maxval * maxval * iSize;
    2161   Double fRefValueC = fRefValueY / 4.0;
     2206  Int maxvalY = 255 << (g_bitDepthY-8);
     2207  Int maxvalC = 255 << (g_bitDepthC-8);
     2208  Double fRefValueY = (Double) maxvalY * maxvalY * iSize;
     2209  Double fRefValueC = (Double) maxvalC * maxvalC * iSize / 4.0;
    21622210  dYPSNR            = ( uiSSDY ? 10.0 * log10( fRefValueY / (Double)uiSSDY ) : 99.99 );
    21632211  dUPSNR            = ( uiSSDU ? 10.0 * log10( fRefValueC / (Double)uiSSDU ) : 99.99 );
     
    21682216   *  - SEI NAL units
    21692217   */
    2170   unsigned numRBSPBytes = 0;
     2218  UInt numRBSPBytes = 0;
    21712219  for (AccessUnit::const_iterator it = accessUnit.begin(); it != accessUnit.end(); it++)
    21722220  {
    2173     unsigned numRBSPBytes_nal = unsigned((*it)->m_nalUnitData.str().size());
     2221    UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
    21742222#if VERBOSE_RATE
    21752223    printf("*** %6s numBytesInNALunit: %u\n", nalUnitTypeToString((*it)->m_nalUnitType), numRBSPBytes_nal);
    21762224#endif
    2177     if ((*it)->m_nalUnitType != NAL_UNIT_SEI)
     2225    if ((*it)->m_nalUnitType != NAL_UNIT_SEI && (*it)->m_nalUnitType != NAL_UNIT_SEI_SUFFIX)
     2226    {
    21782227      numRBSPBytes += numRBSPBytes_nal;
    2179   }
    2180 
    2181   unsigned uibits = numRBSPBytes * 8;
     2228    }
     2229  }
     2230
     2231  UInt uibits = numRBSPBytes * 8;
    21822232  m_vRVM_RP.push_back( uibits );
    21832233
     
    22712321
    22722322/** Function for deciding the nal_unit_type.
    2273  * \param uiPOCCurr POC of the current picture
    2274  * \returns the nal_unit type of the picture
     2323 * \param pocCurr POC of the current picture
     2324 * \returns the nal unit type of the picture
    22752325 * This function checks the configuration and returns the appropriate nal_unit_type for the picture.
    22762326 */
    2277 NalUnitType TEncGOP::getNalUnitType(UInt uiPOCCurr)
     2327NalUnitType TEncGOP::getNalUnitType(Int pocCurr)
    22782328{
    2279   if (uiPOCCurr == 0)
     2329  if (pocCurr == 0)
    22802330  {
    22812331    return NAL_UNIT_CODED_SLICE_IDR;
    22822332  }
    2283   if (uiPOCCurr % m_pcCfg->getIntraPeriod() == 0)
     2333  if (pocCurr % m_pcCfg->getIntraPeriod() == 0)
    22842334  {
    22852335    if (m_pcCfg->getDecodingRefreshType() == 1)
     
    22942344  if(m_pocCRA>0)
    22952345  {
    2296     if(uiPOCCurr<m_pocCRA)
     2346    if(pocCurr<m_pocCRA)
    22972347    {
    22982348      // All leading pictures are being marked as TFD pictures here since current encoder uses all
     
    23042354    }
    23052355  }
    2306 #if NAL_UNIT_TYPES_J1003_D7
    23072356  return NAL_UNIT_CODED_SLICE_TRAIL_R;
    2308 #else
    2309   return NAL_UNIT_CODED_SLICE;
    2310 #endif
    23112357}
    23122358
     
    23152361  Double dRVM = 0;
    23162362 
    2317   if( m_pcCfg->getGOPSize() == 1 && m_pcCfg->getIntraPeriod() != 1 && m_pcCfg->getFrameToBeEncoded() > RVM_VCEGAM10_M * 2 )
     2363  if( m_pcCfg->getGOPSize() == 1 && m_pcCfg->getIntraPeriod() != 1 && m_pcCfg->getFramesToBeEncoded() > RVM_VCEGAM10_M * 2 )
    23182364  {
    23192365    // calculate RVM only for lowdelay configurations
     
    23402386    dBavg /= ( N - 2 * RVM_VCEGAM10_M );
    23412387   
    2342     double dSigamB = 0;
     2388    Double dSigamB = 0;
    23432389    for( i = RVM_VCEGAM10_M + 1 ; i < N - RVM_VCEGAM10_M + 1 ; i++ )
    23442390    {
     
    23482394    dSigamB = sqrt( dSigamB / ( N - 2 * RVM_VCEGAM10_M ) );
    23492395   
    2350     double f = sqrt( 12.0 * ( RVM_VCEGAM10_M - 1 ) / ( RVM_VCEGAM10_M + 1 ) );
     2396    Double f = sqrt( 12.0 * ( RVM_VCEGAM10_M - 1 ) / ( RVM_VCEGAM10_M + 1 ) );
    23512397   
    23522398    dRVM = dSigamB / dRavg * f;
     
    23632409{
    23642410  // Byte-align
    2365 #if BYTE_ALIGNMENT
    23662411  rNalu.m_Bitstream.writeByteAlignment();   // Slice header byte-alignment
    2367 #else
    2368   rNalu.m_Bitstream.writeAlignOne();
    2369 #endif
    23702412
    23712413  // Perform bitstream concatenation
     
    24112453  // and assign values for pocLSBLT and MSB present flag
    24122454  Int longtermPicsPoc[MAX_NUM_REF_PICS], longtermPicsLSB[MAX_NUM_REF_PICS], indices[MAX_NUM_REF_PICS];
     2455  Int longtermPicsMSB[MAX_NUM_REF_PICS];
    24132456  Bool mSBPresentFlag[MAX_NUM_REF_PICS];
    24142457  ::memset(longtermPicsPoc, 0, sizeof(longtermPicsPoc));    // Store POC values of LTRP
    24152458  ::memset(longtermPicsLSB, 0, sizeof(longtermPicsLSB));    // Store POC LSB values of LTRP
     2459  ::memset(longtermPicsMSB, 0, sizeof(longtermPicsMSB));    // Store POC LSB values of LTRP
    24162460  ::memset(indices        , 0, sizeof(indices));            // Indices to aid in tracking sorted LTRPs
    24172461  ::memset(mSBPresentFlag , 0, sizeof(mSBPresentFlag));     // Indicate if MSB needs to be present
     
    24262470    longtermPicsLSB[ctr] = getLSB(longtermPicsPoc[ctr], maxPicOrderCntLSB); // LTRP POC LSB
    24272471    indices[ctr]      = i;
     2472    longtermPicsMSB[ctr] = longtermPicsPoc[ctr] - longtermPicsLSB[ctr];
    24282473  }
    24292474  Int numLongPics = rps->getNumberOfLongtermPictures();
    24302475  assert(ctr == numLongPics);
    24312476
    2432   // Arrange LTR pictures in decreasing order of LSB
     2477  // Arrange pictures in decreasing order of MSB;
    24332478  for(i = 0; i < numLongPics; i++)
    24342479  {
    24352480    for(Int j = 0; j < numLongPics - 1; j++)
    24362481    {
    2437       if(longtermPicsLSB[j] < longtermPicsLSB[j+1])
     2482      if(longtermPicsMSB[j] < longtermPicsMSB[j+1])
    24382483      {
    24392484        std::swap(longtermPicsPoc[j], longtermPicsPoc[j+1]);
    24402485        std::swap(longtermPicsLSB[j], longtermPicsLSB[j+1]);
     2486        std::swap(longtermPicsMSB[j], longtermPicsMSB[j+1]);
    24412487        std::swap(indices[j]        , indices[j+1]        );
    24422488      }
    24432489    }
    24442490  }
    2445   // Now for those pictures that have the same LSB, arrange them
    2446   // in increasing MSB cycle, or equivalently decreasing MSB
    2447   for(i = 0; i < numLongPics;)    // i incremented using j
    2448   {
    2449     Int j = i + 1;
    2450     Int pocLSB = longtermPicsLSB[i];
    2451     for(; j < numLongPics; j++)
    2452     {
    2453       if(pocLSB != longtermPicsLSB[j])
    2454       {
    2455         break;
    2456       }
    2457     }
    2458     // Last index upto which lsb equals pocLSB is j - 1
    2459     // Now sort based on the MSB values
    2460     Int sta, end;
    2461     for(sta = i; sta < j; sta++)
    2462     {
    2463       for(end = i; end < j - 1; end++)
    2464       {
    2465       // longtermPicsMSB = longtermPicsPoc - longtermPicsLSB
    2466         if(longtermPicsPoc[end] - longtermPicsLSB[end] < longtermPicsPoc[end+1] - longtermPicsLSB[end+1])
    2467         {
    2468           std::swap(longtermPicsPoc[end], longtermPicsPoc[end+1]);
    2469           std::swap(longtermPicsLSB[end], longtermPicsLSB[end+1]);
    2470           std::swap(indices[end]        , indices[end+1]        );
    2471         }
    2472       }
    2473     }
    2474     i = j;
    2475   }
     2491
    24762492  for(i = 0; i < numLongPics; i++)
    24772493  {
     
    24842500      pcPic = *iterPic;
    24852501      if( (getLSB(pcPic->getPOC(), maxPicOrderCntLSB) == longtermPicsLSB[i])   &&     // Same LSB
    2486 #if REFERENCE_PICTURE_DEFN
    24872502                                      (pcPic->getSlice(0)->isReferenced())     &&    // Reference picture
    2488 #else
    2489                                       (pcPic->getSlice(0)->getNalRefFlag())     &&    // Reference picture
    2490 #endif
    24912503                                        (pcPic->getPOC() != longtermPicsPoc[i])    )  // Not the LTRP itself
    24922504      {
     
    25222534    assert(rps->getDeltaPocMSBCycleLT(i) >= 0);   // Non-negative value
    25232535  }
     2536  for(i = rps->getNumberOfPictures() - 1, ctr = 1; i >= offset; i--, ctr++)
     2537  {
     2538    for(Int j = rps->getNumberOfPictures() - 1 - ctr; j >= offset; j--)
     2539    {
     2540      // Here at the encoder we know that we have set the full POC value for the LTRPs, hence we
     2541      // don't have to check the MSB present flag values for this constraint.
     2542      assert( rps->getPOC(i) != rps->getPOC(j) ); // If assert fails, LTRP entry repeated in RPS!!!
     2543    }
     2544  }
    25242545}
     2546
     2547#if L0045_NON_NESTED_SEI_RESTRICTIONS
     2548/** Function for finding the position to insert the first of APS and non-nested BP, PT, DU info SEI messages.
     2549 * \param accessUnit Access Unit of the current picture
     2550 * This function finds the position to insert the first of APS and non-nested BP, PT, DU info SEI messages.
     2551 */
     2552Int TEncGOP::xGetFirstSeiLocation(AccessUnit &accessUnit)
     2553{
     2554  // Find the location of the first SEI message
     2555  AccessUnit::iterator it;
     2556  Int seiStartPos = 0;
     2557  for(it = accessUnit.begin(); it != accessUnit.end(); it++, seiStartPos++)
     2558  {
     2559     if ((*it)->isSei() || (*it)->isVcl())
     2560     {
     2561       break;
     2562     }               
     2563  }
     2564  assert(it != accessUnit.end());
     2565  return seiStartPos;
     2566}
     2567#endif
    25252568//! \}
Note: See TracChangeset for help on using the changeset viewer.