Index: trunk/source/Lib/TLibEncoder/SEIwrite.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 125)
+++ trunk/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 189)
@@ -84,4 +84,19 @@
     fprintf( g_hTrace, "=========== Decoding Unit Information SEI message ===========\n");
     break;
+#if J0149_TONE_MAPPING_SEI
+  case SEI::TONE_MAPPING_INFO:
+    fprintf( g_hTrace, "=========== Tone Mapping Info SEI message ===========\n");
+    break;
+#endif
+#if L0208_SOP_DESCRIPTION_SEI
+  case SEI::SOP_DESCRIPTION:
+    fprintf( g_hTrace, "=========== SOP Description SEI message ===========\n");
+    break;
+#endif
+#if K0180_SCALABLE_NESTING_SEI
+  case SEI::SCALABLE_NESTING:
+    fprintf( g_hTrace, "=========== Scalable Nesting SEI message ===========\n");
+    break;
+#endif
   default:
     fprintf( g_hTrace, "=========== Unknown SEI message ===========\n");
@@ -91,5 +106,9 @@
 #endif
 
+#if K0180_SCALABLE_NESTING_SEI
+void SEIWriter::xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, TComSPS *sps)
+#else
 void SEIWriter::xWriteSEIpayloadData(const SEI& sei, TComSPS *sps)
+#endif
 {
   switch (sei.payloadType())
@@ -128,4 +147,19 @@
     xWriteSEIGradualDecodingRefreshInfo(*static_cast<const SEIGradualDecodingRefreshInfo*>(&sei));
     break;
+#if J0149_TONE_MAPPING_SEI
+  case SEI::TONE_MAPPING_INFO:
+    xWriteSEIToneMappingInfo(*static_cast<const SEIToneMappingInfo*>(&sei));
+    break;
+#endif
+#if L0208_SOP_DESCRIPTION_SEI
+  case SEI::SOP_DESCRIPTION:
+    xWriteSEISOPDescription(*static_cast<const SEISOPDescription*>(&sei));
+    break;
+#endif
+#if K0180_SCALABLE_NESTING_SEI
+  case SEI::SCALABLE_NESTING:
+    xWriteSEIScalableNesting(bs, *static_cast<const SEIScalableNesting*>(&sei), sps);
+    break;
+#endif
   default:
     assert(!"Unhandled SEI message");
@@ -145,4 +179,18 @@
   setBitstream(&bs_count);
 
+
+#if K0180_SCALABLE_NESTING_SEI
+
+#if ENC_DEC_TRACE
+  Bool traceEnable = g_HLSTraceEnable;
+  g_HLSTraceEnable = false;
+#endif
+  xWriteSEIpayloadData(bs_count, sei, sps);
+#if ENC_DEC_TRACE
+  g_HLSTraceEnable = traceEnable;
+#endif
+
+#else
+
 #if ENC_DEC_TRACE
   g_HLSTraceEnable = false;
@@ -152,4 +200,7 @@
   g_HLSTraceEnable = true;
 #endif
+
+#endif
+
   UInt payload_data_num_bits = bs_count.getNumberOfWrittenBits();
   assert(0 == payload_data_num_bits % 8);
@@ -158,4 +209,7 @@
 
 #if ENC_DEC_TRACE
+#if K0180_SCALABLE_NESTING_SEI
+  if (g_HLSTraceEnable)
+#endif
   xTraceSEIHeader();
 #endif
@@ -177,8 +231,15 @@
   /* payloadData */
 #if ENC_DEC_TRACE
+#if K0180_SCALABLE_NESTING_SEI
+  if (g_HLSTraceEnable)
+#endif
   xTraceSEIMessageType(sei.payloadType());
 #endif
 
+#if K0180_SCALABLE_NESTING_SEI
+  xWriteSEIpayloadData(bs, sei, sps);
+#else
   xWriteSEIpayloadData(sei, sps);
+#endif
 }
 
@@ -421,4 +482,79 @@
   xWriteByteAlign();
 }
+
+#if J0149_TONE_MAPPING_SEI
+Void SEIWriter::xWriteSEIToneMappingInfo(const SEIToneMappingInfo& sei)
+{
+  Int i;
+  WRITE_UVLC( sei.m_toneMapId,                    "tone_map_id" );
+  WRITE_FLAG( sei.m_toneMapCancelFlag,            "tone_map_cancel_flag" );
+  if( !sei.m_toneMapCancelFlag ) 
+  {
+    WRITE_FLAG( sei.m_toneMapPersistenceFlag,     "tone_map_persistence_flag" );
+    WRITE_CODE( sei.m_codedDataBitDepth,    8,    "coded_data_bit_depth" );
+    WRITE_CODE( sei.m_targetBitDepth,       8,    "target_bit_depth" );
+    WRITE_UVLC( sei.m_modelId,                    "model_id" );
+    switch(sei.m_modelId)
+    {
+    case 0:
+      {
+        WRITE_CODE( sei.m_minValue,  32,        "min_value" );
+        WRITE_CODE( sei.m_maxValue, 32,         "max_value" );
+        break;
+      }
+    case 1:
+      {
+        WRITE_CODE( sei.m_sigmoidMidpoint, 32,  "sigmoid_midpoint" );
+        WRITE_CODE( sei.m_sigmoidWidth,    32,  "sigmoid_width"    );
+        break;
+      }
+    case 2:
+      {
+        UInt num = 1u << sei.m_targetBitDepth;
+        for(i = 0; i < num; i++)
+        {
+          WRITE_CODE( sei.m_startOfCodedInterval[i], (( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3,  "start_of_coded_interval" );
+        }
+        break;
+      }
+    case 3:
+      {
+        WRITE_CODE( sei.m_numPivots, 16,          "num_pivots" );
+        for(i = 0; i < sei.m_numPivots; i++ )
+        {
+          WRITE_CODE( sei.m_codedPivotValue[i], (( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3,       "coded_pivot_value" );
+          WRITE_CODE( sei.m_targetPivotValue[i], (( sei.m_targetBitDepth + 7 ) >> 3 ) << 3,         "target_pivot_value");
+        }
+        break;
+      }
+    case 4:
+      {
+        WRITE_CODE( sei.m_cameraIsoSpeedIdc,    8,    "camera_iso_speed_idc" );
+        if( sei.m_cameraIsoSpeedIdc == 255) //Extended_ISO
+        {
+          WRITE_CODE( sei.m_cameraIsoSpeedValue,    32,    "camera_iso_speed_value" );
+        }
+        WRITE_FLAG( sei.m_exposureCompensationValueSignFlag,           "exposure_compensation_value_sign_flag" );
+        WRITE_CODE( sei.m_exposureCompensationValueNumerator,     16,  "exposure_compensation_value_numerator" );
+        WRITE_CODE( sei.m_exposureCompensationValueDenomIdc,      16,  "exposure_compensation_value_denom_idc" );
+        WRITE_CODE( sei.m_refScreenLuminanceWhite,                32,  "ref_screen_luminance_white" );
+        WRITE_CODE( sei.m_extendedRangeWhiteLevel,                32,  "extended_range_white_level" );
+        WRITE_CODE( sei.m_nominalBlackLevelLumaCodeValue,         16,  "nominal_black_level_luma_code_value" );
+        WRITE_CODE( sei.m_nominalWhiteLevelLumaCodeValue,         16,  "nominal_white_level_luma_code_value" );
+        WRITE_CODE( sei.m_extendedWhiteLevelLumaCodeValue,        16,  "extended_white_level_luma_code_value" );
+        break;
+      }
+    default:
+      {
+        assert(!"Undefined SEIToneMapModelId");
+        break;
+      }
+    }//switch m_modelId
+  }//if(!sei.m_toneMapCancelFlag)
+
+  xWriteByteAlign();
+}
+#endif
+
 Void SEIWriter::xWriteSEIDisplayOrientation(const SEIDisplayOrientation &sei)
 {
@@ -455,4 +591,71 @@
 }
 
+#if L0208_SOP_DESCRIPTION_SEI
+Void SEIWriter::xWriteSEISOPDescription(const SEISOPDescription& sei)
+{
+  WRITE_UVLC( sei.m_sopSeqParameterSetId,           "sop_seq_parameter_set_id"               );
+  WRITE_UVLC( sei.m_numPicsInSopMinus1,             "num_pics_in_sop_minus1"               );
+  for (UInt i = 0; i <= sei.m_numPicsInSopMinus1; i++)
+  {
+    WRITE_CODE( sei.m_sopDescVclNaluType[i], 6, "sop_desc_vcl_nalu_type" );
+    WRITE_CODE( sei.m_sopDescTemporalId[i],  3, "sop_desc_temporal_id" );
+    if (sei.m_sopDescVclNaluType[i] != NAL_UNIT_CODED_SLICE_IDR_W_RADL && sei.m_sopDescVclNaluType[i] != NAL_UNIT_CODED_SLICE_IDR_N_LP)
+    {
+      WRITE_UVLC( sei.m_sopDescStRpsIdx[i],           "sop_desc_st_rps_idx"               );
+    }
+    if (i > 0)
+    {
+      WRITE_SVLC( sei.m_sopDescPocDelta[i],           "sop_desc_poc_delta"               );
+    }
+  }
+
+  xWriteByteAlign();
+}
+#endif
+
+#if K0180_SCALABLE_NESTING_SEI
+Void SEIWriter::xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, TComSPS *sps)
+{
+  WRITE_FLAG( sei.m_bitStreamSubsetFlag,             "bitstream_subset_flag"         );
+  WRITE_FLAG( sei.m_nestingOpFlag,                   "nesting_op_flag      "         );
+  if (sei.m_nestingOpFlag)
+  {
+    WRITE_FLAG( sei.m_defaultOpFlag,                 "default_op_flag"               );
+    WRITE_UVLC( sei.m_nestingNumOpsMinus1,           "nesting_num_ops"               );
+    for (UInt i = (sei.m_defaultOpFlag ? 1 : 0); i <= sei.m_nestingNumOpsMinus1; i++)
+    {
+      WRITE_CODE( sei.m_nestingNoOpMaxTemporalIdPlus1, 3, "nesting_no_op_max_temporal_id" );
+      WRITE_CODE( sei.m_nestingMaxTemporalIdPlus1[i], 3,  "nesting_max_temporal_id"       );
+      WRITE_UVLC( sei.m_nestingOpIdx[i],                  "nesting_op_idx"                );
+    }
+  }
+  else
+  {
+    WRITE_FLAG( sei.m_allLayersFlag,                      "all_layers_flag"               );
+    if (!sei.m_allLayersFlag)
+    {
+      WRITE_CODE( sei.m_nestingNoOpMaxTemporalIdPlus1, 3, "nesting_no_op_max_temporal_id" );
+      WRITE_UVLC( sei.m_nestingNumLayersMinus1,           "nesting_num_layers"            );
+      for (UInt i = 0; i <= sei.m_nestingNumLayersMinus1; i++)
+      {
+        WRITE_CODE( sei.m_nestingLayerId[i], 6,           "nesting_layer_id"              );
+      }
+    }
+  }
+ 
+  // byte alignment
+  while ( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
+  {
+    WRITE_FLAG( 0, "nesting_zero_bit" );
+  }
+
+  // write nested SEI messages
+  for (SEIMessages::const_iterator it = sei.m_nestedSEIs.begin(); it != sei.m_nestedSEIs.end(); it++)
+  {
+    writeSEImessage(bs, *(*it), sps);
+  }
+}
+#endif
+
 Void SEIWriter::xWriteByteAlign()
 {
Index: trunk/source/Lib/TLibEncoder/SEIwrite.h
===================================================================
--- trunk/source/Lib/TLibEncoder/SEIwrite.h	(revision 125)
+++ trunk/source/Lib/TLibEncoder/SEIwrite.h	(revision 189)
@@ -50,5 +50,9 @@
 
 protected:
+#if K0180_SCALABLE_NESTING_SEI
+  Void xWriteSEIpayloadData(TComBitIf& bs, const SEI& sei, TComSPS *sps);
+#else
   Void xWriteSEIpayloadData(const SEI& sei, TComSPS *sps);
+#endif
   Void xWriteSEIuserDataUnregistered(const SEIuserDataUnregistered &sei);
   Void xWriteSEIActiveParameterSets(const SEIActiveParameterSets& sei);
@@ -63,4 +67,13 @@
   Void xWriteSEITemporalLevel0Index(const SEITemporalLevel0Index &sei);
   Void xWriteSEIGradualDecodingRefreshInfo(const SEIGradualDecodingRefreshInfo &sei);
+#if J0149_TONE_MAPPING_SEI
+  Void xWriteSEIToneMappingInfo(const SEIToneMappingInfo& sei);
+#endif
+#if L0208_SOP_DESCRIPTION_SEI
+  Void xWriteSEISOPDescription(const SEISOPDescription& sei);
+#endif
+#if K0180_SCALABLE_NESTING_SEI
+  Void xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, TComSPS *sps);
+#endif
   Void xWriteByteAlign();
 };
Index: trunk/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 125)
+++ trunk/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 189)
@@ -39,5 +39,5 @@
 #include "TEncCavlc.h"
 #include "SEIwrite.h"
-
+#include <iostream>
 //! \ingroup TLibEncoder
 //! \{
@@ -285,5 +285,4 @@
   WRITE_FLAG(pcVUI->getNeutralChromaIndicationFlag(),           "neutral_chroma_indication_flag");
   WRITE_FLAG(pcVUI->getFieldSeqFlag(),                          "field_seq_flag");
-  assert(pcVUI->getFieldSeqFlag() == 0);                        // not currently supported
   WRITE_FLAG(pcVUI->getFrameFieldInfoPresentFlag(),             "frame_field_info_present_flag");
 
@@ -474,5 +473,9 @@
   for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
   {
+#if L0323_DPB
+    WRITE_UVLC( pcSPS->getMaxDecPicBuffering(i) - 1,       "sps_max_dec_pic_buffering_minus1[i]" );
+#else
     WRITE_UVLC( pcSPS->getMaxDecPicBuffering(i),           "sps_max_dec_pic_buffering[i]" );
+#endif
     WRITE_UVLC( pcSPS->getNumReorderPics(i),               "sps_num_reorder_pics[i]" );
     WRITE_UVLC( pcSPS->getMaxLatencyIncrease(i),           "sps_max_latency_increase[i]" );
@@ -484,14 +487,6 @@
   assert( pcSPS->getMaxCUWidth() == pcSPS->getMaxCUHeight() );
   
-  UInt MinCUSize = pcSPS->getMaxCUWidth() >> ( pcSPS->getMaxCUDepth()-g_uiAddCUDepth );
-  UInt log2MinCUSize = 0;
-  while(MinCUSize > 1)
-  {
-    MinCUSize >>= 1;
-    log2MinCUSize++;
-  }
-
-  WRITE_UVLC( log2MinCUSize - 3,                                                     "log2_min_coding_block_size_minus3" );
-  WRITE_UVLC( pcSPS->getMaxCUDepth()-g_uiAddCUDepth,                                 "log2_diff_max_min_coding_block_size" );
+  WRITE_UVLC( pcSPS->getLog2MinCodingBlockSize() - 3,                                "log2_min_coding_block_size_minus3" );
+  WRITE_UVLC( pcSPS->getLog2DiffMaxMinCodingBlockSize(),                             "log2_diff_max_min_coding_block_size" );
   WRITE_UVLC( pcSPS->getQuadtreeTULog2MinSize() - 2,                                 "log2_min_transform_block_size_minus2" );
   WRITE_UVLC( pcSPS->getQuadtreeTULog2MaxSize() - pcSPS->getQuadtreeTULog2MinSize(), "log2_diff_max_min_transform_block_size" );
@@ -558,4 +553,14 @@
       codeVUI(pcSPS->getVuiParameters(), pcSPS);
   }
+#if SCALED_REF_LAYER_OFFSETS
+  if( pcSPS->getLayerId() > 0 )
+  {
+    Window scaledWindow = pcSPS->getScaledRefLayerWindow();
+    WRITE_SVLC( scaledWindow.getWindowLeftOffset()   >> 1, "scaled_ref_layer_left_offset" );
+    WRITE_SVLC( scaledWindow.getWindowTopOffset()    >> 1, "scaled_ref_layer_top_offset" );
+    WRITE_SVLC( scaledWindow.getWindowRightOffset()  >> 1, "scaled_ref_layer_right_offset" );
+    WRITE_SVLC( scaledWindow.getWindowBottomOffset() >> 1, "scaled_ref_layer_bottom_offset" );
+  }
+#endif
 
   WRITE_FLAG( 0, "sps_extension_flag" );
@@ -583,5 +588,9 @@
   for(UInt i=0; i <= pcVPS->getMaxTLayers()-1; i++)
   {
+#if L0323_DPB
+    WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i) - 1,       "vps_max_dec_pic_buffering_minus1[i]" );
+#else
     WRITE_UVLC( pcVPS->getMaxDecPicBuffering(i),           "vps_max_dec_pic_buffering[i]" );
+#endif
     WRITE_UVLC( pcVPS->getNumReorderPics(i),               "vps_num_reorder_pics[i]" );
     WRITE_UVLC( pcVPS->getMaxLatencyIncrease(i),           "vps_max_latency_increase[i]" );
@@ -623,4 +632,7 @@
     }
   }
+#if DERIVE_LAYER_ID_LIST_VARIABLES
+  pcVPS->deriveLayerIdListVariables();
+#endif
 #if L0043_TIMING_INFO
   TimingInfo *timingInfo = pcVPS->getTimingInfo();
@@ -703,16 +715,74 @@
   }
 #endif
+#if VPS_MOVE_DIR_DEPENDENCY_FLAG
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  for( Int layerCtr = 1; layerCtr <= vps->getMaxLayers() - 1; layerCtr++)
+  {
+    for( Int refLayerCtr = 0; refLayerCtr < layerCtr; refLayerCtr++)
+    {
+      WRITE_FLAG(vps->getDirectDependencyFlag(layerCtr, refLayerCtr), "direct_dependency_flag[i][j]" );
+    }
+  }
+#endif
+#endif
 #if VPS_EXTN_PROFILE_INFO
   // Profile-tier-level signalling
+#if VPS_PROFILE_OUTPUT_LAYERS
+  WRITE_CODE( vps->getNumLayerSets() - 1   , 10, "vps_number_layer_sets_minus1" );     
+  WRITE_CODE( vps->getNumProfileTierLevel() - 1,  6, "vps_num_profile_tier_level_minus1"); 
+  for(Int idx = 1; idx <= vps->getNumProfileTierLevel() - 1; idx++)
+#else
   for(Int idx = 1; idx <= vps->getNumLayerSets() - 1; idx++)
+#endif
   {
     WRITE_FLAG( vps->getProfilePresentFlag(idx),       "vps_profile_present_flag[i]" );
     if( !vps->getProfilePresentFlag(idx) )
     {
+#if VPS_PROFILE_OUTPUT_LAYERS
+      WRITE_CODE( vps->getProfileLayerSetRef(idx) - 1, 6, "profile_ref_minus1[i]" );
+#else
       WRITE_UVLC( vps->getProfileLayerSetRef(idx) - 1, "vps_profile_layer_set_ref_minus1[i]" );
+#endif
     }
     codePTL( vps->getPTLForExtn(idx), vps->getProfilePresentFlag(idx), vps->getMaxTLayers() - 1 );
   }
 #endif
+
+#if VPS_PROFILE_OUTPUT_LAYERS
+  Int numOutputLayerSets = vps->getNumOutputLayerSets() ;
+  WRITE_FLAG(  (numOutputLayerSets > vps->getNumLayerSets()), "more_output_layer_sets_than_default_flag" ); 
+  if(numOutputLayerSets > vps->getNumLayerSets())
+  {
+    WRITE_CODE( numOutputLayerSets - vps->getNumLayerSets(), 10, "num_add_output_layer_sets" );
+  }
+  if( numOutputLayerSets > 1 )
+  {
+    WRITE_FLAG( vps->getDefaultOneTargetOutputLayerFlag(), "default_one_target_output_layer_flag" );   
+  }
+
+  for(i = 1; i < numOutputLayerSets; i++)
+  {
+    if( i > (vps->getNumLayerSets() - 1) )
+    {
+      Int numBits = 1;
+      while ((1 << numBits) < (vps->getNumLayerSets() - 1))
+      {
+        numBits++;
+      }
+      WRITE_CODE( vps->getOutputLayerSetIdx(i) - 1, numBits, "output_layer_set_idx_minus1");  
+      Int lsIdx = vps->getOutputLayerSetIdx(i);
+      for(j = 0; j < vps->getNumLayersInIdList(lsIdx) - 1; j++)
+      {
+        WRITE_FLAG( vps->getOutputLayerFlag(i,j), "output_layer_flag[i][j]");
+      }
+    }
+    Int numBits = 1;
+    while ((1 << numBits) < (vps->getNumProfileTierLevel()))
+    {
+      numBits++;
+    }
+    WRITE_CODE( vps->getProfileLevelTierIdx(i), numBits, "profile_level_tier_idx[i]" );     
+  }
+#else
 #if VPS_EXTN_OP_LAYER_SETS
   // Target output layer signalling
@@ -720,5 +790,10 @@
   for(i = 0; i < vps->getNumOutputLayerSets(); i++)
   {
+#if VPS_OUTPUT_LAYER_SET_IDX
+    assert(vps->getOutputLayerSetIdx(i) > 0);
+    WRITE_UVLC( vps->getOutputLayerSetIdx(i) - 1,           "vps_output_layer_set_idx_minus1[i]");
+#else
     WRITE_UVLC( vps->getOutputLayerSetIdx(i),           "vps_output_layer_set_idx[i]");
+#endif
     Int lsIdx = vps->getOutputLayerSetIdx(i);
     for(j = 0; j <= vps->getMaxLayerId(); j++)
@@ -731,4 +806,9 @@
   }
 #endif
+#endif
+#if JCTVC_M0458_INTERLAYER_RPS_SIG
+      WRITE_FLAG(vps->getMaxOneActiveRefLayerFlag(), "max_one_active_ref_layer_flag");
+#endif 
+#if !VPS_MOVE_DIR_DEPENDENCY_FLAG
 #if VPS_EXTN_DIRECT_REF_LAYERS
   for( Int layerCtr = 1; layerCtr <= vps->getMaxLayers() - 1; layerCtr++)
@@ -739,4 +819,5 @@
     }
   }
+#endif
 #endif
 }
@@ -810,5 +891,35 @@
       WRITE_CODE( picOrderCntLSB, pcSlice->getSPS()->getBitsForPOC(), "pic_order_cnt_lsb");
       TComReferencePictureSet* rps = pcSlice->getRPS();
+      
+#if FIX1071
+      // Deal with bitstream restriction stating that:
+      // – If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
+      // Ideally this process should not be repeated for each slice in a picture
+      TComReferencePictureSet altRps;
+      Bool useAltRps = false;
+#if SVC_EXTENSION
+      if( pcSlice->getLayerId() == 0 )
+#endif
+      if (pcSlice->getRapPicFlag())
+      {
+        for (Int picIdx = 0; !useAltRps && picIdx < rps->getNumberOfPictures(); picIdx++)
+        {
+          useAltRps = rps->getUsed(picIdx);
+        }
+        if (useAltRps)
+        {
+          memcpy(&altRps, rps, sizeof(TComReferencePictureSet));
+          rps = &altRps;
+          for (Int picIdx = 0; picIdx < rps->getNumberOfPictures(); picIdx++)
+          {
+            rps->setUsed(picIdx, false);
+          }
+        }
+      }
+
+      if(pcSlice->getRPSidx() < 0 || useAltRps)
+#else
       if(pcSlice->getRPSidx() < 0)
+#endif
       {
         WRITE_FLAG( 0, "short_term_ref_pic_set_sps_flag");
@@ -902,4 +1013,5 @@
         }
       }
+
       if (pcSlice->getSPS()->getTMVPFlagsPresent())
       {
@@ -907,4 +1019,29 @@
       }
     }
+
+#if JCTVC_M0458_INTERLAYER_RPS_SIG    
+    if((pcSlice->getSPS()->getLayerId() > 0)  &&  (pcSlice->getNumILRRefIdx() > 0) ) 
+    {
+      WRITE_FLAG(pcSlice->getInterLayerPredEnabledFlag(),"inter_layer_pred_enabled_flag");
+      if( pcSlice->getInterLayerPredEnabledFlag())
+      {
+        if(pcSlice->getNumILRRefIdx() > 1)
+        {
+          Int numBits = 1;
+          while ((1 << numBits) < pcSlice->getNumILRRefIdx())
+          {
+            numBits++;
+          }
+          if( !pcSlice->getVPS()->getMaxOneActiveRefLayerFlag()) 
+          {
+            WRITE_CODE(pcSlice->getNumInterLayerRefPics(), numBits,"num_inter_layer_ref_pics_minus1");
+          }       
+          for(Int i = 0; i < pcSlice->getActiveNumILRRefIdx(); i++ ) 
+            WRITE_CODE(pcSlice->getInterLayerPredLayerIdc(i),numBits,"inter_layer_pred_layer_idc[i]");   
+        }
+      }
+    }     
+#endif 
+
     if(pcSlice->getSPS()->getUseSAO())
     {
@@ -1065,4 +1202,5 @@
     }
   }
+
   if(pcSlice->getPPS()->getSliceHeaderExtensionPresentFlag())
   {
@@ -1389,82 +1527,4 @@
 // ====================================================================================================================
 
-
-/** Write PCM alignment bits. 
- * \returns Void
- */
-Void  TEncCavlc::xWritePCMAlignZero    ()
-{
-  m_pcBitIf->writeAlignZero();
-}
-
-Void TEncCavlc::xWriteUnaryMaxSymbol( UInt uiSymbol, UInt uiMaxSymbol )
-{
-  if (uiMaxSymbol == 0)
-  {
-    return;
-  }
-  xWriteFlag( uiSymbol ? 1 : 0 );
-  if ( uiSymbol == 0 )
-  {
-    return;
-  }
-  
-  Bool bCodeLast = ( uiMaxSymbol > uiSymbol );
-  
-  while( --uiSymbol )
-  {
-    xWriteFlag( 1 );
-  }
-  if( bCodeLast )
-  {
-    xWriteFlag( 0 );
-  }
-  return;
-}
-
-Void TEncCavlc::xWriteExGolombLevel( UInt uiSymbol )
-{
-  if( uiSymbol )
-  {
-    xWriteFlag( 1 );
-    UInt uiCount = 0;
-    Bool bNoExGo = (uiSymbol < 13);
-    
-    while( --uiSymbol && ++uiCount < 13 )
-    {
-      xWriteFlag( 1 );
-    }
-    if( bNoExGo )
-    {
-      xWriteFlag( 0 );
-    }
-    else
-    {
-      xWriteEpExGolomb( uiSymbol, 0 );
-    }
-  }
-  else
-  {
-    xWriteFlag( 0 );
-  }
-  return;
-}
-
-Void TEncCavlc::xWriteEpExGolomb( UInt uiSymbol, UInt uiCount )
-{
-  while( uiSymbol >= (UInt)(1<<uiCount) )
-  {
-    xWriteFlag( 1 );
-    uiSymbol -= 1<<uiCount;
-    uiCount  ++;
-  }
-  xWriteFlag( 0 );
-  while( uiCount-- )
-  {
-    xWriteFlag( (uiSymbol>>uiCount) & 1 );
-  }
-  return;
-}
-
 /** code explicit wp tables
  * \param TComSlice* pcSlice
Index: trunk/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCavlc.h	(revision 125)
+++ trunk/source/Lib/TLibEncoder/TEncCavlc.h	(revision 189)
@@ -68,9 +68,4 @@
   TComSlice*    m_pcSlice;
   UInt          m_uiCoeffCost;
-
-  Void  xWritePCMAlignZero    ();
-  Void  xWriteEpExGolomb      ( UInt uiSymbol, UInt uiCount );
-  Void  xWriteExGolombLevel    ( UInt uiSymbol );
-  Void  xWriteUnaryMaxSymbol  ( UInt uiSymbol, UInt uiMaxSymbol );
 
   Void codeShortTermRefPicSet              ( TComSPS* pcSPS, TComReferencePictureSet* pcRPS, Bool calledFromSliceHeader, Int idx );
Index: trunk/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCfg.h	(revision 125)
+++ trunk/source/Lib/TLibEncoder/TEncCfg.h	(revision 189)
@@ -158,4 +158,7 @@
   Int       m_loopFilterTcOffsetDiv2;
   Bool      m_DeblockingFilterControlPresent;
+#if L0386_DB_METRIC
+  Bool      m_DeblockingFilterMetric;
+#endif
   Bool      m_bUseSAO;
   Int       m_maxNumOffsetsPerPic;
@@ -188,5 +191,7 @@
   Bool      m_bUseASR;
   Bool      m_bUseHADME;
+#if !L0034_COMBINED_LIST_CLEANUP
   Bool      m_bUseLComb;
+#endif
   Bool      m_useRDOQ;
   Bool      m_useRDOQTS;
@@ -234,4 +239,31 @@
   Int       m_pictureTimingSEIEnabled;
   Int       m_recoveryPointSEIEnabled;
+#if J0149_TONE_MAPPING_SEI
+  Bool      m_toneMappingInfoSEIEnabled;
+  Int       m_toneMapId;
+  Bool      m_toneMapCancelFlag;
+  Bool      m_toneMapPersistenceFlag;
+  Int       m_codedDataBitDepth;
+  Int       m_targetBitDepth;
+  Int       m_modelId; 
+  Int       m_minValue;
+  Int       m_maxValue;
+  Int       m_sigmoidMidpoint;
+  Int       m_sigmoidWidth;
+  Int       m_numPivots;
+  Int       m_cameraIsoSpeedIdc;
+  Int       m_cameraIsoSpeedValue;
+  Int       m_exposureCompensationValueSignFlag;
+  Int       m_exposureCompensationValueNumerator;
+  Int       m_exposureCompensationValueDenomIdc;
+  Int       m_refScreenLuminanceWhite;
+  Int       m_extendedRangeWhiteLevel;
+  Int       m_nominalBlackLevelLumaCodeValue;
+  Int       m_nominalWhiteLevelLumaCodeValue;
+  Int       m_extendedWhiteLevelLumaCodeValue;
+  Int*      m_startOfCodedInterval;
+  Int*      m_codedPivotValue;
+  Int*      m_targetPivotValue;
+#endif
   Int       m_framePackingSEIEnabled;
   Int       m_framePackingSEIType;
@@ -243,4 +275,10 @@
   Int       m_gradualDecodingRefreshInfoEnabled;
   Int       m_decodingUnitInfoSEIEnabled;
+#if L0208_SOP_DESCRIPTION_SEI
+  Int       m_SOPDescriptionSEIEnabled;
+#endif
+#if K0180_SCALABLE_NESTING_SEI
+  Int       m_scalableNestingSEIEnabled;
+#endif
   //====== Weighted Prediction ========
   Bool      m_useWeightedPred;       //< Use of Weighting Prediction (P_SLICE)
@@ -379,4 +417,7 @@
   Void      setLoopFilterTcOffset           ( Int   i )      { m_loopFilterTcOffsetDiv2    = i; }
   Void      setDeblockingFilterControlPresent ( Bool b ) { m_DeblockingFilterControlPresent = b; }
+#if L0386_DB_METRIC
+  Void      setDeblockingFilterMetric       ( Bool  b )      { m_DeblockingFilterMetric = b; }
+#endif
 
   //====== Motion search ========
@@ -433,4 +474,7 @@
   Int       getLoopFilterTcOffset           ()      { return m_loopFilterTcOffsetDiv2; }
   Bool      getDeblockingFilterControlPresent()  { return  m_DeblockingFilterControlPresent; }
+#if L0386_DB_METRIC
+  Bool      getDeblockingFilterMetric       ()      { return m_DeblockingFilterMetric; }
+#endif
 
   //==== Motion search ========
@@ -450,5 +494,7 @@
   Void      setUseASR                       ( Bool  b )     { m_bUseASR     = b; }
   Void      setUseHADME                     ( Bool  b )     { m_bUseHADME   = b; }
+#if !L0034_COMBINED_LIST_CLEANUP
   Void      setUseLComb                     ( Bool  b )     { m_bUseLComb   = b; }
+#endif
   Void      setUseRDOQ                      ( Bool  b )     { m_useRDOQ    = b; }
   Void      setUseRDOQTS                    ( Bool  b )     { m_useRDOQTS  = b; }
@@ -472,5 +518,7 @@
   Bool      getUseASR                       ()      { return m_bUseASR;     }
   Bool      getUseHADME                     ()      { return m_bUseHADME;   }
+#if !L0034_COMBINED_LIST_CLEANUP
   Bool      getUseLComb                     ()      { return m_bUseLComb;   }
+#endif
   Bool      getUseRDOQ                      ()      { return m_useRDOQ;    }
   Bool      getUseRDOQTS                    ()      { return m_useRDOQTS;  }
@@ -569,4 +617,56 @@
   Void  setRecoveryPointSEIEnabled(Int b)                { m_recoveryPointSEIEnabled = b; }
   Int   getRecoveryPointSEIEnabled()                     { return m_recoveryPointSEIEnabled; }
+#if J0149_TONE_MAPPING_SEI
+  Void  setToneMappingInfoSEIEnabled(Bool b)                 {  m_toneMappingInfoSEIEnabled = b;  }
+  Bool  getToneMappingInfoSEIEnabled()                       {  return m_toneMappingInfoSEIEnabled;  }
+  Void  setTMISEIToneMapId(Int b)                            {  m_toneMapId = b;  }
+  Int   getTMISEIToneMapId()                                 {  return m_toneMapId;  }
+  Void  setTMISEIToneMapCancelFlag(Bool b)                   {  m_toneMapCancelFlag=b;  }
+  Bool  getTMISEIToneMapCancelFlag()                         {  return m_toneMapCancelFlag;  }
+  Void  setTMISEIToneMapPersistenceFlag(Bool b)              {  m_toneMapPersistenceFlag = b;  }
+  Bool   getTMISEIToneMapPersistenceFlag()                   {  return m_toneMapPersistenceFlag;  }
+  Void  setTMISEICodedDataBitDepth(Int b)                    {  m_codedDataBitDepth = b;  }
+  Int   getTMISEICodedDataBitDepth()                         {  return m_codedDataBitDepth;  }
+  Void  setTMISEITargetBitDepth(Int b)                       {  m_targetBitDepth = b;  }
+  Int   getTMISEITargetBitDepth()                            {  return m_targetBitDepth;  }
+  Void  setTMISEIModelID(Int b)                              {  m_modelId = b;  }
+  Int   getTMISEIModelID()                                   {  return m_modelId;  }
+  Void  setTMISEIMinValue(Int b)                             {  m_minValue = b;  }
+  Int   getTMISEIMinValue()                                  {  return m_minValue;  }
+  Void  setTMISEIMaxValue(Int b)                             {  m_maxValue = b;  }
+  Int   getTMISEIMaxValue()                                  {  return m_maxValue;  }
+  Void  setTMISEISigmoidMidpoint(Int b)                      {  m_sigmoidMidpoint = b;  }
+  Int   getTMISEISigmoidMidpoint()                           {  return m_sigmoidMidpoint;  }
+  Void  setTMISEISigmoidWidth(Int b)                         {  m_sigmoidWidth = b;  }
+  Int   getTMISEISigmoidWidth()                              {  return m_sigmoidWidth;  }
+  Void  setTMISEIStartOfCodedInterva( Int*  p )              {  m_startOfCodedInterval = p;  }
+  Int*  getTMISEIStartOfCodedInterva()                       {  return m_startOfCodedInterval;  }
+  Void  setTMISEINumPivots(Int b)                            {  m_numPivots = b;  }
+  Int   getTMISEINumPivots()                                 {  return m_numPivots;  }
+  Void  setTMISEICodedPivotValue( Int*  p )                  {  m_codedPivotValue = p;  }
+  Int*  getTMISEICodedPivotValue()                           {  return m_codedPivotValue;  }
+  Void  setTMISEITargetPivotValue( Int*  p )                 {  m_targetPivotValue = p;  }
+  Int*  getTMISEITargetPivotValue()                          {  return m_targetPivotValue;  }
+  Void  setTMISEICameraIsoSpeedIdc(Int b)                    {  m_cameraIsoSpeedIdc = b;  }
+  Int   getTMISEICameraIsoSpeedIdc()                         {  return m_cameraIsoSpeedIdc;  }
+  Void  setTMISEICameraIsoSpeedValue(Int b)                  {  m_cameraIsoSpeedValue = b;  }
+  Int   getTMISEICameraIsoSpeedValue()                       {  return m_cameraIsoSpeedValue;  }
+  Void  setTMISEIExposureCompensationValueSignFlag(Int b)    {  m_exposureCompensationValueSignFlag = b;  }
+  Int   getTMISEIExposureCompensationValueSignFlag()         {  return m_exposureCompensationValueSignFlag;  }
+  Void  setTMISEIExposureCompensationValueNumerator(Int b)   {  m_exposureCompensationValueNumerator = b;  }
+  Int   getTMISEIExposureCompensationValueNumerator()        {  return m_exposureCompensationValueNumerator;  }
+  Void  setTMISEIExposureCompensationValueDenomIdc(Int b)    {  m_exposureCompensationValueDenomIdc =b;  }
+  Int   getTMISEIExposureCompensationValueDenomIdc()         {  return m_exposureCompensationValueDenomIdc;  }
+  Void  setTMISEIRefScreenLuminanceWhite(Int b)              {  m_refScreenLuminanceWhite = b;  }
+  Int   getTMISEIRefScreenLuminanceWhite()                   {  return m_refScreenLuminanceWhite;  }
+  Void  setTMISEIExtendedRangeWhiteLevel(Int b)              {  m_extendedRangeWhiteLevel = b;  }
+  Int   getTMISEIExtendedRangeWhiteLevel()                   {  return m_extendedRangeWhiteLevel;  }
+  Void  setTMISEINominalBlackLevelLumaCodeValue(Int b)       {  m_nominalBlackLevelLumaCodeValue = b;  }
+  Int   getTMISEINominalBlackLevelLumaCodeValue()            {  return m_nominalBlackLevelLumaCodeValue;  }
+  Void  setTMISEINominalWhiteLevelLumaCodeValue(Int b)       {  m_nominalWhiteLevelLumaCodeValue = b;  }
+  Int   getTMISEINominalWhiteLevelLumaCodeValue()            {  return m_nominalWhiteLevelLumaCodeValue;  }
+  Void  setTMISEIExtendedWhiteLevelLumaCodeValue(Int b)      {  m_extendedWhiteLevelLumaCodeValue =b;  }
+  Int   getTMISEIExtendedWhiteLevelLumaCodeValue()           {  return m_extendedWhiteLevelLumaCodeValue;  }
+#endif
   Void  setFramePackingArrangementSEIEnabled(Int b)      { m_framePackingSEIEnabled = b; }
   Int   getFramePackingArrangementSEIEnabled()           { return m_framePackingSEIEnabled; }
@@ -587,4 +687,12 @@
   Void  setDecodingUnitInfoSEIEnabled(Int b)                { m_decodingUnitInfoSEIEnabled = b;    }
   Int   getDecodingUnitInfoSEIEnabled()                     { return m_decodingUnitInfoSEIEnabled; }
+#if L0208_SOP_DESCRIPTION_SEI
+  Void  setSOPDescriptionSEIEnabled(Int b)                { m_SOPDescriptionSEIEnabled = b; }
+  Int   getSOPDescriptionSEIEnabled()                     { return m_SOPDescriptionSEIEnabled; }
+#endif
+#if K0180_SCALABLE_NESTING_SEI
+  Void  setScalableNestingSEIEnabled(Int b)                { m_scalableNestingSEIEnabled = b; }
+  Int   getScalableNestingSEIEnabled()                     { return m_scalableNestingSEIEnabled; }
+#endif
   Void      setUseWP               ( Bool b )    { m_useWeightedPred   = b;    }
   Void      setWPBiPred            ( Bool b )    { m_useWeightedBiPred = b;    }
Index: trunk/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 125)
+++ trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 189)
@@ -96,4 +96,7 @@
 #if L0045_NON_NESTED_SEI_RESTRICTIONS
   xResetNonNestedSEIPresentFlags();
+#if K0180_SCALABLE_NESTING_SEI
+  xResetNestedSEIPresentFlags();
+#endif
 #endif
 #if SVC_UPSAMPLING
@@ -134,4 +137,5 @@
   m_pcSliceEncoder       = pcTEncTop->getSliceEncoder();
   m_pcListPic            = pcTEncTop->getListPic();  
+  
   m_pcEntropyCoder       = pcTEncTop->getEntropyCoder();
   m_pcCavlcCoder         = pcTEncTop->getCavlcCoder();
@@ -210,7 +214,94 @@
 }
 
+#if J0149_TONE_MAPPING_SEI
+SEIToneMappingInfo*  TEncGOP::xCreateSEIToneMappingInfo()
+{
+  SEIToneMappingInfo *seiToneMappingInfo = new SEIToneMappingInfo();
+  seiToneMappingInfo->m_toneMapId = m_pcCfg->getTMISEIToneMapId();
+  seiToneMappingInfo->m_toneMapCancelFlag = m_pcCfg->getTMISEIToneMapCancelFlag();
+  seiToneMappingInfo->m_toneMapPersistenceFlag = m_pcCfg->getTMISEIToneMapPersistenceFlag();
+
+  seiToneMappingInfo->m_codedDataBitDepth = m_pcCfg->getTMISEICodedDataBitDepth();
+  assert(seiToneMappingInfo->m_codedDataBitDepth >= 8 && seiToneMappingInfo->m_codedDataBitDepth <= 14);
+  seiToneMappingInfo->m_targetBitDepth = m_pcCfg->getTMISEITargetBitDepth();
+  assert( (seiToneMappingInfo->m_targetBitDepth >= 1 && seiToneMappingInfo->m_targetBitDepth <= 17) || (seiToneMappingInfo->m_targetBitDepth  == 255) );
+  seiToneMappingInfo->m_modelId = m_pcCfg->getTMISEIModelID();
+  assert(seiToneMappingInfo->m_modelId >=0 &&seiToneMappingInfo->m_modelId<=4);
+
+  switch( seiToneMappingInfo->m_modelId)
+  {
+  case 0:
+    {
+      seiToneMappingInfo->m_minValue = m_pcCfg->getTMISEIMinValue();
+      seiToneMappingInfo->m_maxValue = m_pcCfg->getTMISEIMaxValue();
+      break;
+    }
+  case 1:
+    {
+      seiToneMappingInfo->m_sigmoidMidpoint = m_pcCfg->getTMISEISigmoidMidpoint();
+      seiToneMappingInfo->m_sigmoidWidth = m_pcCfg->getTMISEISigmoidWidth();
+      break;
+    }
+  case 2:
+    {
+      UInt num = 1u<<(seiToneMappingInfo->m_targetBitDepth);
+      seiToneMappingInfo->m_startOfCodedInterval.resize(num);
+      Int* ptmp = m_pcCfg->getTMISEIStartOfCodedInterva();
+      if(ptmp)
+      {
+        for(int i=0; i<num;i++)
+        {
+          seiToneMappingInfo->m_startOfCodedInterval[i] = ptmp[i];
+        }
+      }
+      break;
+    }
+  case 3:
+    {
+      seiToneMappingInfo->m_numPivots = m_pcCfg->getTMISEINumPivots();
+      seiToneMappingInfo->m_codedPivotValue.resize(seiToneMappingInfo->m_numPivots);
+      seiToneMappingInfo->m_targetPivotValue.resize(seiToneMappingInfo->m_numPivots);
+      Int* ptmpcoded = m_pcCfg->getTMISEICodedPivotValue();
+      Int* ptmptarget = m_pcCfg->getTMISEITargetPivotValue();
+      if(ptmpcoded&&ptmptarget)
+      {
+        for(int i=0; i<(seiToneMappingInfo->m_numPivots);i++)
+        {
+          seiToneMappingInfo->m_codedPivotValue[i]=ptmpcoded[i];
+          seiToneMappingInfo->m_targetPivotValue[i]=ptmptarget[i];
+         }
+       }
+       break;
+     }
+  case 4:
+     {
+       seiToneMappingInfo->m_cameraIsoSpeedIdc = m_pcCfg->getTMISEICameraIsoSpeedIdc();
+       seiToneMappingInfo->m_cameraIsoSpeedValue = m_pcCfg->getTMISEICameraIsoSpeedValue();
+       assert( seiToneMappingInfo->m_cameraIsoSpeedValue !=0 );
+       seiToneMappingInfo->m_exposureCompensationValueSignFlag = m_pcCfg->getTMISEIExposureCompensationValueSignFlag();
+       seiToneMappingInfo->m_exposureCompensationValueNumerator = m_pcCfg->getTMISEIExposureCompensationValueNumerator();
+       seiToneMappingInfo->m_exposureCompensationValueDenomIdc = m_pcCfg->getTMISEIExposureCompensationValueDenomIdc();
+       seiToneMappingInfo->m_refScreenLuminanceWhite = m_pcCfg->getTMISEIRefScreenLuminanceWhite();
+       seiToneMappingInfo->m_extendedRangeWhiteLevel = m_pcCfg->getTMISEIExtendedRangeWhiteLevel();
+       assert( seiToneMappingInfo->m_extendedRangeWhiteLevel >= 100 );
+       seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue = m_pcCfg->getTMISEINominalBlackLevelLumaCodeValue();
+       seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue = m_pcCfg->getTMISEINominalWhiteLevelLumaCodeValue();
+       assert( seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue > seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue );
+       seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue = m_pcCfg->getTMISEIExtendedWhiteLevelLumaCodeValue();
+       assert( seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue >= seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue );
+       break;
+    }
+  default:
+    {
+      assert(!"Undefined SEIToneMapModelId");
+      break;
+    }
+  }
+  return seiToneMappingInfo;
+}
+#endif
 Void TEncGOP::xCreateLeadingSEIMessages (/*SEIMessages seiMessages,*/ AccessUnit &accessUnit, TComSPS *sps)
 {
-  OutputNALUnit nalu(NAL_UNIT_SEI);
+  OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
 
   if(m_pcCfg->getActiveParameterSetsSEIEnabled())
@@ -233,5 +324,5 @@
     SEIFramePacking *sei = xCreateSEIFramePacking ();
 
-    nalu = NALUnit(NAL_UNIT_SEI);
+    nalu = NALUnit(NAL_UNIT_PREFIX_SEI);
     m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
     m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps);
@@ -244,5 +335,5 @@
     SEIDisplayOrientation *sei = xCreateSEIDisplayOrientation();
 
-    nalu = NALUnit(NAL_UNIT_SEI); 
+    nalu = NALUnit(NAL_UNIT_PREFIX_SEI); 
     m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
     m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
@@ -251,4 +342,17 @@
     delete sei;
   }
+#if J0149_TONE_MAPPING_SEI
+  if(m_pcCfg->getToneMappingInfoSEIEnabled())
+  {
+    SEIToneMappingInfo *sei = xCreateSEIToneMappingInfo ();
+      
+    nalu = NALUnit(NAL_UNIT_PREFIX_SEI); 
+    m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+    m_seiWriter.writeSEImessage(nalu.m_Bitstream, *sei, sps); 
+    writeRBSPTrailingBits(nalu.m_Bitstream);
+    accessUnit.push_back(new NALUnitEBSP(nalu));
+    delete sei;
+  }
+#endif
 }
 
@@ -276,4 +380,19 @@
   m_iNumPicCoded = 0;
   SEIPictureTiming pictureTimingSEI;
+#if L0208_SOP_DESCRIPTION_SEI
+  Bool writeSOP = m_pcCfg->getSOPDescriptionSEIEnabled();
+#endif
+#if K0180_SCALABLE_NESTING_SEI
+  // Initialize Scalable Nesting SEI with single layer values
+  SEIScalableNesting scalableNestingSEI;
+  scalableNestingSEI.m_bitStreamSubsetFlag           = 1;      // If the nested SEI messages are picture buffereing SEI mesages, picure timing SEI messages or sub-picture timing SEI messages, bitstream_subset_flag shall be equal to 1
+  scalableNestingSEI.m_nestingOpFlag                 = 0;
+  scalableNestingSEI.m_nestingNumOpsMinus1           = 0;      //nesting_num_ops_minus1
+  scalableNestingSEI.m_allLayersFlag                 = 0;
+  scalableNestingSEI.m_nestingNoOpMaxTemporalIdPlus1 = 6 + 1;  //nesting_no_op_max_temporal_id_plus1
+  scalableNestingSEI.m_nestingNumLayersMinus1        = 1 - 1;  //nesting_num_layers_minus1
+  scalableNestingSEI.m_nestingLayerId[0]             = 0;
+  scalableNestingSEI.m_callerOwnsSEIs                = true;
+#endif
 #if L0044_DU_DPB_OUTPUT_DELAY_HRD
   Int picSptDpbOutputDuDelay = 0;
@@ -348,5 +467,5 @@
     }
 
-    if( getNalUnitType(pocCurr) == NAL_UNIT_CODED_SLICE_IDR || getNalUnitType(pocCurr) == NAL_UNIT_CODED_SLICE_IDR_N_LP )
+    if( getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_N_LP )
     {
       m_iLastIDR = pocCurr;
@@ -364,7 +483,8 @@
 #if SVC_EXTENSION
     pcPic->setLayerId( m_layerId );
-#endif
-
+    m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS(), m_pcEncTop->getVPS() );
+#else
     m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iNumPicRcvd, iGOPid, pcSlice, m_pcEncTop->getSPS(), m_pcEncTop->getPPS() );
+#endif
     pcSlice->setLastIDR(m_iLastIDR);
     pcSlice->setSliceIdx(0);
@@ -411,9 +531,13 @@
     }
     // Set the nal unit type
-    pcSlice->setNalUnitType(getNalUnitType(pocCurr));
+    pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR));
 #if IDR_ALIGNMENT
     if (m_layerId > 0)
     {
+#if VPS_EXTN_DIRECT_REF_LAYERS_CONTINUE
+      TComList<TComPic*> *cListPic = m_ppcTEncTop[m_layerId]->getRefLayerEnc(m_layerId)->getListPic();
+#else
       TComList<TComPic*> *cListPic = m_ppcTEncTop[m_layerId-1]->getListPic();
+#endif
       pcSlice->setBaseColPic (*cListPic, m_layerId );
     }
@@ -424,7 +548,7 @@
     {
 #if IDR_ALIGNMENT
-      if( pcSlice->getBaseColPic()->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR )
-      {
-        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_IDR);
+      if( pcSlice->getBaseColPic()->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || pcSlice->getBaseColPic()->getSlice(0)->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )
+      {
+        pcSlice->setNalUnitType(pcSlice->getBaseColPic()->getSlice(0)->getNalUnitType());
       }
       else
@@ -432,7 +556,14 @@
       pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_CRA);
     }
+#if ZERO_NUM_DIRECT_LAYERS
+    if( m_layerId > 0 && pcSlice->getActiveNumILRRefIdx() == 0 && pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA )
+    {
+      pcSlice->setSliceType(I_SLICE);
+    }
+    else
+#endif
     if( m_layerId > 0 && !m_pcEncTop->getElRapSliceTypeB() )
     {
-      if( (pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA) &&
+      if( (pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP) &&
           (pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA) &&
            pcSlice->getSliceType() == B_SLICE )
@@ -442,9 +573,17 @@
     }
 #endif
-    if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_TRAIL_R)
-    {
-      if(pcSlice->getTemporalLayerNonReferenceFlag())
+    if(pcSlice->getTemporalLayerNonReferenceFlag())
+    {
+      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_TRAIL_R)
       {
         pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TRAIL_N);
+    }
+      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_RADL_R)
+      {
+        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_RADL_N);
+      }
+      if(pcSlice->getNalUnitType()==NAL_UNIT_CODED_SLICE_RASL_R)
+      {
+        pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_RASL_N);
       }
     }
@@ -471,5 +610,5 @@
         else
         {
-          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA);
+          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA_R);
         }
       }
@@ -524,8 +663,24 @@
     pcSlice->setNumRefIdx(REF_PIC_LIST_1,min(m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive,pcSlice->getRPS()->getNumberOfPictures()));
 
-#if REF_LIST_BUGFIX
+#if REF_IDX_FRAMEWORK
+#if ZERO_NUM_DIRECT_LAYERS
+    if( m_layerId > 0 && pcSlice->getActiveNumILRRefIdx() )
+#else
     if(m_layerId > 0)
-    {
-      if( pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA )
+#endif
+    {
+#if JCTVC_M0458_INTERLAYER_RPS_SIG
+      if( pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA )
+      {
+        pcSlice->setNumRefIdx(REF_PIC_LIST_0, pcSlice->getActiveNumILRRefIdx());
+        pcSlice->setNumRefIdx(REF_PIC_LIST_1, pcSlice->getActiveNumILRRefIdx());
+      }
+      else
+      {
+        pcSlice->setNumRefIdx(REF_PIC_LIST_0, pcSlice->getNumRefIdx(REF_PIC_LIST_0)+pcSlice->getActiveNumILRRefIdx());
+        pcSlice->setNumRefIdx(REF_PIC_LIST_1, pcSlice->getNumRefIdx(REF_PIC_LIST_1)+pcSlice->getActiveNumILRRefIdx());
+      }
+#else
+      if( pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA )
       {
         pcSlice->setNumRefIdx(REF_PIC_LIST_0, pcSlice->getNumILRRefIdx());
@@ -537,4 +692,5 @@
         pcSlice->setNumRefIdx(REF_PIC_LIST_1, pcSlice->getNumRefIdx(REF_PIC_LIST_1)+pcSlice->getNumILRRefIdx());
       }
+#endif
     }
 #endif
@@ -545,5 +701,9 @@
 
 #if SVC_EXTENSION      
+#if ZERO_NUM_DIRECT_LAYERS
+    if( m_layerId > 0 && pcSlice->getActiveNumILRRefIdx() )
+#else
     if(m_layerId > 0)
+#endif
     {
 #if !IDR_ALIGNMENT
@@ -553,6 +713,10 @@
 #if SVC_UPSAMPLING
       if ( pcPic->isSpatialEnhLayer())
-      {    
+      { 
+#if SCALED_REF_LAYER_OFFSETS
+        m_pcPredSearch->upsampleBasePic( pcPic->getFullPelBaseRec(), pcSlice->getBaseColPic()->getPicYuvRec(), pcPic->getPicYuvRec(), pcSlice->getSPS()->getScaledRefLayerWindow() );
+#else
         m_pcPredSearch->upsampleBasePic( pcPic->getFullPelBaseRec(), pcSlice->getBaseColPic()->getPicYuvRec(), pcPic->getPicYuvRec() );
+#endif
       }
       else
@@ -573,6 +737,10 @@
 
     //  Set reference list
-#if REF_LIST_BUGFIX
+#if REF_IDX_FRAMEWORK
+#if ZERO_NUM_DIRECT_LAYERS
+    if(m_layerId ==  0 || ( m_layerId > 0 && pcSlice->getActiveNumILRRefIdx() == 0 ) )
+#else
     if(m_layerId ==  0)
+#endif
     {
       pcSlice->setRefPicList( rcListPic);
@@ -582,5 +750,9 @@
 #endif
 #if REF_IDX_FRAMEWORK
+#if ZERO_NUM_DIRECT_LAYERS
+    if( m_layerId > 0 && pcSlice->getActiveNumILRRefIdx() )
+#else
     if(m_layerId > 0)
+#endif
     {
       m_pcEncTop->setILRPic(pcPic);
@@ -592,10 +764,6 @@
       }
 #endif
-#if REF_LIST_BUGFIX
       pcSlice->setRefPicListModificationSvc();
-      pcSlice->setRefPicListSvc( rcListPic, m_pcEncTop->getIlpList() );
-#else
-      pcSlice->addRefPicList ( m_pcEncTop->getIlpList(), 1);
-#endif
+      pcSlice->setRefPicList( rcListPic, false, m_pcEncTop->getIlpList());
 
 #if REF_IDX_MFM
@@ -607,5 +775,5 @@
         for(Int colIdx = 0; colIdx < pcSlice->getNumRefIdx( RefPicList(1 - ColFromL0Flag) ); colIdx++) 
         { 
-          if( pcSlice->getRefPic( RefPicList(1 - ColFromL0Flag), colIdx)->isILR() ) 
+          if( pcSlice->getRefPic( RefPicList(1 - ColFromL0Flag), colIdx)->isILR(m_layerId) ) 
           { 
             ColRefIdx = colIdx; 
@@ -620,5 +788,5 @@
           for(Int colIdx = 0; colIdx < pcSlice->getNumRefIdx( RefPicList(1 - ColFromL0Flag) ); colIdx++) 
           { 
-            if( pcSlice->getRefPic( RefPicList(1 - ColFromL0Flag), colIdx)->isILR() ) 
+            if( pcSlice->getRefPic( RefPicList(1 - ColFromL0Flag), colIdx)->isILR(m_layerId) ) 
             { 
               ColRefIdx = colIdx; 
@@ -644,5 +812,5 @@
       pcSlice->setSliceType ( P_SLICE );
     }
-
+#if !L0034_COMBINED_LIST_CLEANUP
     if (pcSlice->getSliceType() != B_SLICE || !pcSlice->getSPS()->getUseLComb())
     {
@@ -656,4 +824,5 @@
       pcSlice->setNumRefIdx(REF_PIC_LIST_C, pcSlice->getNumRefIdx(REF_PIC_LIST_0));
     }
+#endif
 
     if (pcSlice->getSliceType() == B_SLICE)
@@ -683,4 +852,8 @@
       pcSlice->setCheckLDC(bLowDelay);  
     }
+    else
+    {
+      pcSlice->setCheckLDC(true);  
+    }
 
     uiColDir = 1-uiColDir;
@@ -689,4 +862,7 @@
     pcSlice->setRefPOCList();
 
+#if L0034_COMBINED_LIST_CLEANUP
+    pcSlice->setList1IdxToList0Idx();
+#else
     pcSlice->setNoBackPredFlag( false );
     if ( pcSlice->getSliceType() == B_SLICE && !pcSlice->getRefPicListCombinationFlag())
@@ -712,4 +888,5 @@
     }
     pcSlice->generateCombinedList();
+#endif
 
     if (m_pcEncTop->getTMVPModeId() == 2)
@@ -831,4 +1008,33 @@
     UInt uiNumSlices = 1;
 
+#if SIMPLIFIED_MV_POS_SCALING
+    if (m_layerId > 0)
+    {
+#if SCALED_REF_LAYER_OFFSETS
+      const Window &scalEL = m_pcEncTop->getScaledRefLayerWindow();
+
+      Int widthBL   = pcSlice->getBaseColPic()->getPicYuvRec()->getWidth();
+      Int heightBL  = pcSlice->getBaseColPic()->getPicYuvRec()->getHeight();
+
+      Int widthEL   = pcPic->getPicYuvRec()->getWidth()  - scalEL.getWindowLeftOffset() - scalEL.getWindowRightOffset();
+      Int heightEL  = pcPic->getPicYuvRec()->getHeight() - scalEL.getWindowTopOffset()  - scalEL.getWindowBottomOffset();
+#else
+      const Window &confBL = pcSlice->getBaseColPic()->getPicYuvRec()->getConformanceWindow();
+      const Window &confEL = pcPic->getPicYuvRec()->getConformanceWindow();
+
+      Int widthBL   = pcSlice->getBaseColPic()->getPicYuvRec()->getWidth () - confBL.getWindowLeftOffset() - confBL.getWindowRightOffset();
+      Int heightBL  = pcSlice->getBaseColPic()->getPicYuvRec()->getHeight() - confBL.getWindowTopOffset() - confBL.getWindowBottomOffset();
+
+      Int widthEL   = pcPic->getPicYuvRec()->getWidth() - confEL.getWindowLeftOffset() - confEL.getWindowRightOffset();
+      Int heightEL  = pcPic->getPicYuvRec()->getHeight() - confEL.getWindowTopOffset() - confEL.getWindowBottomOffset();
+#endif
+      g_mvScalingFactor[m_layerId][0] = Clip3(-4096, 4095, ((widthEL  << 8) + (widthBL  >> 1)) / widthBL);
+      g_mvScalingFactor[m_layerId][1] = Clip3(-4096, 4095, ((heightEL << 8) + (heightBL >> 1)) / heightBL);
+
+      g_posScalingFactor[m_layerId][0] = ((widthBL  << 16) + (widthEL  >> 1)) / widthEL;
+      g_posScalingFactor[m_layerId][1] = ((heightBL << 16) + (heightEL >> 1)) / heightEL;
+    }
+#endif
+
     UInt uiInternalAddress = pcPic->getNumPartInCU()-4;
     UInt uiExternalAddress = pcPic->getPicSym()->getNumberOfCUsInFrame()-1;
@@ -949,5 +1155,5 @@
     startCUAddrSliceSegmentIdx++;
 #if AVC_BASE
-    if( m_layerId == 0 )
+    if( m_layerId == 0 && m_pcEncTop->getVPS()->getAvcBaseLayerFlag() )
     {
       pcPic->getPicYuvOrg()->copyToPic( pcPic->getPicYuvRec() );
@@ -1027,4 +1233,10 @@
     Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
     m_pcLoopFilter->setCfg(bLFCrossTileBoundary);
+#if L0386_DB_METRIC
+    if ( m_pcCfg->getDeblockingFilterMetric() )
+    {
+      dblMetric(pcPic, uiNumSlices);
+    }
+#endif
     m_pcLoopFilter->loopFilterPic( pcPic );
 
@@ -1059,5 +1271,5 @@
       OutputNALUnit nalu(NAL_UNIT_VPS, 0, m_layerId);
 #if AVC_BASE
-      if( m_layerId == 1 )
+      if( ( m_layerId == 1 && m_pcEncTop->getVPS()->getAvcBaseLayerFlag() ) || ( m_layerId == 0 && !m_pcEncTop->getVPS()->getAvcBaseLayerFlag() ) )
 #else
       if( m_layerId == 0 )
@@ -1133,4 +1345,44 @@
     }
 
+#if L0208_SOP_DESCRIPTION_SEI
+    if (writeSOP) // write SOP description SEI (if enabled) at the beginning of GOP
+    {
+      Int SOPcurrPOC = pocCurr;
+
+      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
+      m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+      m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
+
+      SEISOPDescription SOPDescriptionSEI;
+      SOPDescriptionSEI.m_sopSeqParameterSetId = pcSlice->getSPS()->getSPSId();
+
+      UInt i = 0;
+      UInt prevEntryId = iGOPid;
+      for (j = iGOPid; j < m_iGopSize; j++)
+      {
+        Int deltaPOC = m_pcCfg->getGOPEntry(j).m_POC - m_pcCfg->getGOPEntry(prevEntryId).m_POC;
+        if ((SOPcurrPOC + deltaPOC) < m_pcCfg->getFramesToBeEncoded())
+        {
+          SOPcurrPOC += deltaPOC;
+          SOPDescriptionSEI.m_sopDescVclNaluType[i] = getNalUnitType(SOPcurrPOC, m_iLastIDR);
+          SOPDescriptionSEI.m_sopDescTemporalId[i] = m_pcCfg->getGOPEntry(j).m_temporalId;
+          SOPDescriptionSEI.m_sopDescStRpsIdx[i] = m_pcEncTop->getReferencePictureSetIdxForSOP(pcSlice, SOPcurrPOC, j);
+          SOPDescriptionSEI.m_sopDescPocDelta[i] = deltaPOC;
+
+          prevEntryId = j;
+          i++;
+        }
+      }
+
+      SOPDescriptionSEI.m_numPicsInSopMinus1 = i - 1;
+
+      m_seiWriter.writeSEImessage( nalu.m_Bitstream, SOPDescriptionSEI, pcSlice->getSPS());
+      writeRBSPTrailingBits(nalu.m_Bitstream);
+      accessUnit.push_back(new NALUnitEBSP(nalu));
+
+      writeSOP = false;
+    }
+#endif
+
     if( ( m_pcCfg->getPictureTimingSEIEnabled() || m_pcCfg->getDecodingUnitInfoSEIEnabled() ) &&
         ( pcSlice->getSPS()->getVuiParametersPresentFlag() ) &&
@@ -1178,5 +1430,5 @@
        || ( pcSlice->getSPS()->getVuiParameters()->getHrdParameters()->getVclHrdParametersPresentFlag() ) ) )
     {
-      OutputNALUnit nalu(NAL_UNIT_SEI);
+      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
       m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
       m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
@@ -1219,4 +1471,5 @@
       writeRBSPTrailingBits(nalu.m_Bitstream);
 #if L0045_NON_NESTED_SEI_RESTRICTIONS
+      {
       UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
       UInt offsetPosition = m_activeParameterSetSEIPresentInAU;   // Insert BP SEI after APS SEI
@@ -1228,6 +1481,33 @@
       accessUnit.insert(it, new NALUnitEBSP(nalu));
       m_bufferingPeriodSEIPresentInAU = true;
+      }
 #else
       accessUnit.push_back(new NALUnitEBSP(nalu));
+#endif
+
+#if K0180_SCALABLE_NESTING_SEI
+      if (m_pcCfg->getScalableNestingSEIEnabled())
+      {
+        OutputNALUnit naluTmp(NAL_UNIT_PREFIX_SEI);
+        m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+        m_pcEntropyCoder->setBitstream(&naluTmp.m_Bitstream);
+        scalableNestingSEI.m_nestedSEIs.clear();
+        scalableNestingSEI.m_nestedSEIs.push_back(&sei_buffering_period);
+        m_seiWriter.writeSEImessage( naluTmp.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
+        writeRBSPTrailingBits(naluTmp.m_Bitstream);
+#if L0045_NON_NESTED_SEI_RESTRICTIONS
+        UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
+        UInt offsetPosition = m_activeParameterSetSEIPresentInAU + m_bufferingPeriodSEIPresentInAU + m_pictureTimingSEIPresentInAU;   // Insert BP SEI after non-nested APS, BP and PT SEIs
+        AccessUnit::iterator it;
+        for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
+        {
+          it++;
+        }
+        accessUnit.insert(it, new NALUnitEBSP(naluTmp));
+        m_nestedBufferingPeriodSEIPresentInAU = true;
+#else
+        accessUnit.push_back(new NALUnitEBSP(naluTmp));
+#endif
+      }
 #endif
 
@@ -1241,5 +1521,5 @@
       {
         // Gradual decoding refresh SEI 
-        OutputNALUnit nalu(NAL_UNIT_SEI);
+        OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
         m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
         m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
@@ -1253,5 +1533,5 @@
       }
     // Recovery point SEI
-      OutputNALUnit nalu(NAL_UNIT_SEI);
+      OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI);
       m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
       m_pcEntropyCoder->setBitstream(&nalu.m_Bitstream);
@@ -1444,13 +1724,6 @@
 
           pcSlice->setTileOffstForMultES( uiOneBitstreamPerSliceLength );
-          if (!sliceSegment)
-          {
             pcSlice->setTileLocationCount ( 0 );
-            m_pcSliceEncoder->encodeSlice(pcPic, pcBitstreamRedirect, pcSubstreamsOut); // redirect is only used for CAVLC tile position info.
-          }
-          else
-          {
-            m_pcSliceEncoder->encodeSlice(pcPic, &nalu.m_Bitstream, pcSubstreamsOut); // nalu.m_Bitstream is only used for CAVLC tile position info.
-          }
+          m_pcSliceEncoder->encodeSlice(pcPic, pcSubstreamsOut);
 
           {
@@ -1484,5 +1757,5 @@
               if (ui+1 < pcSlice->getPPS()->getNumSubstreams())
               {
-                puiSubstreamSizes[ui] = pcSubstreamsOut[ui].getNumberOfWrittenBits();
+                puiSubstreamSizes[ui] = pcSubstreamsOut[ui].getNumberOfWrittenBits() + (pcSubstreamsOut[ui].countStartCodeEmulations()<<3);
               }
             }
@@ -1516,5 +1789,5 @@
           // 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.
           Bool bNALUAlignedWrittenToList    = false; // used to ensure current NALU is not written more than once to the NALU list.
-          xWriteTileLocationToSliceHeader(nalu, pcBitstreamRedirect, pcSlice);
+          xAttachSliceDataToNalUnit(nalu, pcBitstreamRedirect);
           accessUnit.push_back(new NALUnitEBSP(nalu));
 #if RATE_CONTROL_LAMBDA_DOMAIN
@@ -1544,5 +1817,5 @@
             {
               UInt numRBSPBytes_nal = UInt((*it)->m_nalUnitData.str().size());
-              if ((*it)->m_nalUnitType != NAL_UNIT_SEI && (*it)->m_nalUnitType != NAL_UNIT_SEI_SUFFIX)
+              if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
               {
                 numRBSPBytes += numRBSPBytes_nal;
@@ -1640,7 +1913,7 @@
         }
 #if SVC_EXTENSION
-        OutputNALUnit nalu(NAL_UNIT_SEI_SUFFIX, pcSlice->getTLayer(), m_layerId);
-#else
-        OutputNALUnit nalu(NAL_UNIT_SEI_SUFFIX, pcSlice->getTLayer());
+        OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer(), m_layerId);
+#else
+        OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer());
 #endif
 
@@ -1667,5 +1940,5 @@
         sei_temporal_level0_index.rapIdx = m_rapIdx;
 
-        OutputNALUnit nalu(NAL_UNIT_SEI); 
+        OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI); 
 
         /* write the SEI messages */
@@ -1807,5 +2080,6 @@
         if( m_pcCfg->getPictureTimingSEIEnabled() )
         {
-          OutputNALUnit nalu(NAL_UNIT_SEI, pcSlice->getTLayer());
+          {
+            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
           m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
           m_seiWriter.writeSEImessage(nalu.m_Bitstream, pictureTimingSEI, pcSlice->getSPS());
@@ -1827,4 +2101,32 @@
 #endif
         }
+#if K0180_SCALABLE_NESTING_SEI
+          if ( m_pcCfg->getScalableNestingSEIEnabled() ) // put picture timing SEI into scalable nesting SEI
+          {
+            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
+            m_pcEntropyCoder->setEntropyCoder(m_pcCavlcCoder, pcSlice);
+            scalableNestingSEI.m_nestedSEIs.clear();
+            scalableNestingSEI.m_nestedSEIs.push_back(&pictureTimingSEI);
+            m_seiWriter.writeSEImessage(nalu.m_Bitstream, scalableNestingSEI, pcSlice->getSPS());
+            writeRBSPTrailingBits(nalu.m_Bitstream);
+#if L0045_NON_NESTED_SEI_RESTRICTIONS
+            UInt seiPositionInAu = xGetFirstSeiLocation(accessUnit);
+            UInt offsetPosition = m_activeParameterSetSEIPresentInAU 
+              + m_bufferingPeriodSEIPresentInAU + m_pictureTimingSEIPresentInAU + m_nestedBufferingPeriodSEIPresentInAU;    // Insert PT SEI after APS and BP SEI
+            AccessUnit::iterator it;
+            for(j = 0, it = accessUnit.begin(); j < seiPositionInAu + offsetPosition; j++)
+            {
+              it++;
+            }
+            accessUnit.insert(it, new NALUnitEBSP(nalu));
+            m_nestedPictureTimingSEIPresentInAU = true;
+#else
+            AccessUnit::iterator it = find_if(accessUnit.begin(), accessUnit.end(), mem_fun(&NALUnit::isSlice));
+            accessUnit.insert(it, new NALUnitEBSP(nalu));
+#endif
+          }
+#endif
+
+        }
         if( m_pcCfg->getDecodingUnitInfoSEIEnabled() && hrd->getSubPicCpbParamsPresentFlag() )
         {             
@@ -1832,5 +2134,5 @@
           for( Int i = 0; i < ( pictureTimingSEI.m_numDecodingUnitsMinus1 + 1 ); i ++ )
           {
-            OutputNALUnit nalu(NAL_UNIT_SEI, pcSlice->getTLayer());
+            OutputNALUnit nalu(NAL_UNIT_PREFIX_SEI, pcSlice->getTLayer());
 
             SEIDecodingUnitInfo tempSEI;
@@ -1880,5 +2182,5 @@
                   break;
                 }
-                if ((*it)->m_nalUnitType != NAL_UNIT_SEI && (*it)->m_nalUnitType != NAL_UNIT_SEI_SUFFIX)
+                if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
                 {
                   ctr++;
@@ -1891,4 +2193,7 @@
 #if L0045_NON_NESTED_SEI_RESTRICTIONS
       xResetNonNestedSEIPresentFlags();
+#if K0180_SCALABLE_NESTING_SEI
+      xResetNestedSEIPresentFlags();
+#endif
 #endif
       pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
@@ -2113,16 +2418,16 @@
     case NAL_UNIT_CODED_SLICE_TRAIL_R: return "TRAIL_R";
     case NAL_UNIT_CODED_SLICE_TRAIL_N: return "TRAIL_N";
-    case NAL_UNIT_CODED_SLICE_TLA: return "TLA";
+    case NAL_UNIT_CODED_SLICE_TLA_R:      return "TLA_R";
     case NAL_UNIT_CODED_SLICE_TSA_N: return "TSA_N";
     case NAL_UNIT_CODED_SLICE_STSA_R: return "STSA_R";
     case NAL_UNIT_CODED_SLICE_STSA_N: return "STSA_N";
-    case NAL_UNIT_CODED_SLICE_BLA: return "BLA";
-    case NAL_UNIT_CODED_SLICE_BLANT: return "BLANT";
+    case NAL_UNIT_CODED_SLICE_BLA_W_LP:   return "BLA_W_LP";
+    case NAL_UNIT_CODED_SLICE_BLA_W_RADL: return "BLA_W_RADL";
     case NAL_UNIT_CODED_SLICE_BLA_N_LP: return "BLA_N_LP";
-    case NAL_UNIT_CODED_SLICE_IDR: return "IDR";
+    case NAL_UNIT_CODED_SLICE_IDR_W_RADL: return "IDR_W_RADL";
     case NAL_UNIT_CODED_SLICE_IDR_N_LP: return "IDR_N_LP";
     case NAL_UNIT_CODED_SLICE_CRA: return "CRA";
-    case NAL_UNIT_CODED_SLICE_DLP: return "DLP";
-    case NAL_UNIT_CODED_SLICE_TFD: return "TFD";
+    case NAL_UNIT_CODED_SLICE_RADL_R:     return "RADL_R";
+    case NAL_UNIT_CODED_SLICE_RASL_R:     return "RASL_R";
     case NAL_UNIT_VPS: return "VPS";
     case NAL_UNIT_SPS: return "SPS";
@@ -2132,5 +2437,6 @@
     case NAL_UNIT_EOB: return "EOB";
     case NAL_UNIT_FILLER_DATA: return "FILLER";
-    case NAL_UNIT_SEI: return "SEI";
+    case NAL_UNIT_PREFIX_SEI:             return "SEI";
+    case NAL_UNIT_SUFFIX_SEI:             return "SEI";
     default: return "UNK";
   }
@@ -2223,5 +2529,5 @@
     printf("*** %6s numBytesInNALunit: %u\n", nalUnitTypeToString((*it)->m_nalUnitType), numRBSPBytes_nal);
 #endif
-    if ((*it)->m_nalUnitType != NAL_UNIT_SEI && (*it)->m_nalUnitType != NAL_UNIT_SEI_SUFFIX)
+    if ((*it)->m_nalUnitType != NAL_UNIT_PREFIX_SEI && (*it)->m_nalUnitType != NAL_UNIT_SUFFIX_SEI)
     {
       numRBSPBytes += numRBSPBytes_nal;
@@ -2314,4 +2620,11 @@
     for (Int iRefIndex = 0; iRefIndex < pcSlice->getNumRefIdx(RefPicList(iRefList)); iRefIndex++)
     {
+#if REF_IDX_FRAMEWORK && VPS_EXTN_DIRECT_REF_LAYERS_CONTINUE
+      if( pcSlice->getRefPic(RefPicList(iRefList), iRefIndex)->isILR(m_layerId) )
+      {
+        printf( "%d(%d) ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)-pcSlice->getLastIDR(), pcSlice->getRefPic(RefPicList(iRefList), iRefIndex)->getLayerId() );
+      }
+      else
+#endif
       printf ("%d ", pcSlice->getRefPOC(RefPicList(iRefList), iRefIndex)-pcSlice->getLastIDR());
     }
@@ -2325,9 +2638,9 @@
  * This function checks the configuration and returns the appropriate nal_unit_type for the picture.
  */
-NalUnitType TEncGOP::getNalUnitType(Int pocCurr)
+NalUnitType TEncGOP::getNalUnitType(Int pocCurr, Int lastIDR)
 {
   if (pocCurr == 0)
   {
-    return NAL_UNIT_CODED_SLICE_IDR;
+    return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
   }
   if (pocCurr % m_pcCfg->getIntraPeriod() == 0)
@@ -2339,5 +2652,5 @@
     else if (m_pcCfg->getDecodingRefreshType() == 2)
     {
-      return NAL_UNIT_CODED_SLICE_IDR;
+      return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
     }
   }
@@ -2351,5 +2664,12 @@
       // controlling the reference pictures used for encoding that leading picture. Such a leading 
       // picture need not be marked as a TFD picture.
-      return NAL_UNIT_CODED_SLICE_TFD;
+      return NAL_UNIT_CODED_SLICE_RASL_R;
+    }
+  }
+  if (lastIDR>0)
+  {
+    if (pocCurr < lastIDR)
+    {
+      return NAL_UNIT_CODED_SLICE_RADL_R;
     }
   }
@@ -2402,9 +2722,10 @@
 }
 
-/** Determine the difference between consecutive tile sizes (in bytes) and writes it to  bistream rNalu [slice header]
- * \param rpcBitstreamRedirect contains the bitstream to be concatenated to rNalu. rpcBitstreamRedirect contains slice payload. rpcSlice contains tile location information.
- * \returns Updates rNalu to contain concatenated bitstream. rpcBitstreamRedirect is cleared at the end of this function call.
+/** Attaches the input bitstream to the stream in the output NAL unit
+    Updates rNalu to contain concatenated bitstream. rpcBitstreamRedirect is cleared at the end of this function call.
+ *  \param codedSliceData contains the coded slice data (bitstream) to be concatenated to rNalu
+ *  \param rNalu          target NAL unit
  */
-Void TEncGOP::xWriteTileLocationToSliceHeader (OutputNALUnit& rNalu, TComOutputBitstream*& rpcBitstreamRedirect, TComSlice*& rpcSlice)
+Void TEncGOP::xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream*& codedSliceData)
 {
   // Byte-align
@@ -2412,30 +2733,12 @@
 
   // Perform bitstream concatenation
-  if (rpcBitstreamRedirect->getNumberOfWrittenBits() > 0)
-  {
-    UInt uiBitCount  = rpcBitstreamRedirect->getNumberOfWrittenBits();
-    if (rpcBitstreamRedirect->getByteStreamLength()>0)
-    {
-      UChar *pucStart  =  reinterpret_cast<UChar*>(rpcBitstreamRedirect->getByteStream());
-      UInt uiWriteByteCount = 0;
-      while (uiWriteByteCount < (uiBitCount >> 3) )
-      {
-        UInt uiBits = (*pucStart);
-        rNalu.m_Bitstream.write(uiBits, 8);
-        pucStart++;
-        uiWriteByteCount++;
-      }
-    }
-    UInt uiBitsHeld = (uiBitCount & 0x07);
-    for (UInt uiIdx=0; uiIdx < uiBitsHeld; uiIdx++)
-    {
-      rNalu.m_Bitstream.write((rpcBitstreamRedirect->getHeldBits() & (1 << (7-uiIdx))) >> (7-uiIdx), 1);
-    }          
+  if (codedSliceData->getNumberOfWrittenBits() > 0)
+    {
+    rNalu.m_Bitstream.addSubstream(codedSliceData);
   }
 
   m_pcEntropyCoder->setBitstream(&rNalu.m_Bitstream);
 
-  delete rpcBitstreamRedirect;
-  rpcBitstreamRedirect = new TComOutputBitstream;
+  codedSliceData->clear();
 }
 
@@ -2562,7 +2865,131 @@
      }               
   }
-  assert(it != accessUnit.end());
+//  assert(it != accessUnit.end());  // Triggers with some legit configurations
   return seiStartPos;
 }
 #endif
+
+#if L0386_DB_METRIC
+Void TEncGOP::dblMetric( TComPic* pcPic, UInt uiNumSlices )
+{
+  TComPicYuv* pcPicYuvRec = pcPic->getPicYuvRec();
+  Pel* Rec    = pcPicYuvRec->getLumaAddr( 0 );
+  Pel* tempRec = Rec;
+  Int  stride = pcPicYuvRec->getStride();
+  UInt log2maxTB = pcPic->getSlice(0)->getSPS()->getQuadtreeTULog2MaxSize();
+  UInt maxTBsize = (1<<log2maxTB);
+  const UInt minBlockArtSize = 8;
+  const UInt picWidth = pcPicYuvRec->getWidth();
+  const UInt picHeight = pcPicYuvRec->getHeight();
+  const UInt noCol = (picWidth>>log2maxTB);
+  const UInt noRows = (picHeight>>log2maxTB);
+  UInt64 *colSAD = (UInt64*)malloc(noCol*sizeof(UInt64));
+  UInt64 *rowSAD = (UInt64*)malloc(noRows*sizeof(UInt64));
+  UInt colIdx = 0;
+  UInt rowIdx = 0;
+  Pel p0, p1, p2, q0, q1, q2;
+  
+  Int qp = pcPic->getSlice(0)->getSliceQp();
+  Int bitdepthScale = 1 << (g_bitDepthY-8);
+  Int beta = TComLoopFilter::getBeta( qp ) * bitdepthScale;
+  const Int thr2 = (beta>>2);
+  const Int thr1 = 2*bitdepthScale;
+  UInt a = 0;
+  
+  memset(colSAD, 0, noCol*sizeof(UInt64));
+  memset(rowSAD, 0, noRows*sizeof(UInt64));
+  
+  if (maxTBsize > minBlockArtSize)
+  {
+    // Analyze vertical artifact edges
+    for(Int c = maxTBsize; c < picWidth; c += maxTBsize)
+    {
+      for(Int r = 0; r < picHeight; r++)
+      {
+        p2 = Rec[c-3];
+        p1 = Rec[c-2];
+        p0 = Rec[c-1];
+        q0 = Rec[c];
+        q1 = Rec[c+1];
+        q2 = Rec[c+2];
+        a = ((abs(p2-(p1<<1)+p0)+abs(q0-(q1<<1)+q2))<<1);
+        if ( thr1 < a && a < thr2)
+        {
+          colSAD[colIdx] += abs(p0 - q0);
+        }
+        Rec += stride;
+      }
+      colIdx++;
+      Rec = tempRec;
+    }
+    
+    // Analyze horizontal artifact edges
+    for(Int r = maxTBsize; r < picHeight; r += maxTBsize)
+    {
+      for(Int c = 0; c < picWidth; c++)
+      {
+        p2 = Rec[c + (r-3)*stride];
+        p1 = Rec[c + (r-2)*stride];
+        p0 = Rec[c + (r-1)*stride];
+        q0 = Rec[c + r*stride];
+        q1 = Rec[c + (r+1)*stride];
+        q2 = Rec[c + (r+2)*stride];
+        a = ((abs(p2-(p1<<1)+p0)+abs(q0-(q1<<1)+q2))<<1);
+        if (thr1 < a && a < thr2)
+        {
+          rowSAD[rowIdx] += abs(p0 - q0);
+        }
+      }
+      rowIdx++;
+    }
+  }
+  
+  UInt64 colSADsum = 0;
+  UInt64 rowSADsum = 0;
+  for(Int c = 0; c < noCol-1; c++)
+  {
+    colSADsum += colSAD[c];
+  }
+  for(Int r = 0; r < noRows-1; r++)
+  {
+    rowSADsum += rowSAD[r];
+  }
+  
+  colSADsum <<= 10;
+  rowSADsum <<= 10;
+  colSADsum /= (noCol-1);
+  colSADsum /= picHeight;
+  rowSADsum /= (noRows-1);
+  rowSADsum /= picWidth;
+  
+  UInt64 avgSAD = ((colSADsum + rowSADsum)>>1);
+  avgSAD >>= (g_bitDepthY-8);
+  
+  if ( avgSAD > 2048 )
+  {
+    avgSAD >>= 9;
+    Int offset = Clip3(2,6,(Int)avgSAD);
+    for (Int i=0; i<uiNumSlices; i++)
+    {
+      pcPic->getSlice(i)->setDeblockingFilterOverrideFlag(true);
+      pcPic->getSlice(i)->setDeblockingFilterDisable(false);
+      pcPic->getSlice(i)->setDeblockingFilterBetaOffsetDiv2( offset );
+      pcPic->getSlice(i)->setDeblockingFilterTcOffsetDiv2( offset );
+    }
+  }
+  else
+  {
+    for (Int i=0; i<uiNumSlices; i++)
+    {
+      pcPic->getSlice(i)->setDeblockingFilterOverrideFlag(false);
+      pcPic->getSlice(i)->setDeblockingFilterDisable(        pcPic->getSlice(i)->getPPS()->getPicDisableDeblockingFilterFlag() );
+      pcPic->getSlice(i)->setDeblockingFilterBetaOffsetDiv2( pcPic->getSlice(i)->getPPS()->getDeblockingFilterBetaOffsetDiv2() );
+      pcPic->getSlice(i)->setDeblockingFilterTcOffsetDiv2(   pcPic->getSlice(i)->getPPS()->getDeblockingFilterTcOffsetDiv2()   );
+    }
+  }
+  
+  free(colSAD);
+  free(rowSAD);
+}
+#endif
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncGOP.h	(revision 125)
+++ trunk/source/Lib/TLibEncoder/TEncGOP.h	(revision 189)
@@ -131,4 +131,8 @@
   Bool                    m_bufferingPeriodSEIPresentInAU;
   Bool                    m_pictureTimingSEIPresentInAU;
+#if K0180_SCALABLE_NESTING_SEI
+  Bool                    m_nestedBufferingPeriodSEIPresentInAU;
+  Bool                    m_nestedPictureTimingSEIPresentInAU;
+#endif
 #endif
 public:
@@ -149,5 +153,5 @@
   Void  compressGOP ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec, std::list<AccessUnit>& accessUnitsInGOP );
 #endif
-  Void xWriteTileLocationToSliceHeader (OutputNALUnit& rNalu, TComOutputBitstream*& rpcBitstreamRedirect, TComSlice*& rpcSlice);
+  Void  xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream*& rpcBitstreamRedirect);
 
   
@@ -160,5 +164,5 @@
   
   TEncSlice*  getSliceEncoder()   { return m_pcSliceEncoder; }
-  NalUnitType getNalUnitType( Int pocCurr );
+  NalUnitType getNalUnitType( Int pocCurr, Int lastIdr );
   Void arrangeLongtermPicturesInRPS(TComSlice *, TComList<TComPic*>& );
 protected:
@@ -178,4 +182,8 @@
   SEIFramePacking*        xCreateSEIFramePacking();
   SEIDisplayOrientation*  xCreateSEIDisplayOrientation();
+
+#if J0149_TONE_MAPPING_SEI
+  SEIToneMappingInfo*     xCreateSEIToneMappingInfo();
+#endif
 
   Void xCreateLeadingSEIMessages (/*SEIMessages seiMessages,*/ AccessUnit &accessUnit, TComSPS *sps);
@@ -188,4 +196,14 @@
     m_pictureTimingSEIPresentInAU      = false;
   }
+#if K0180_SCALABLE_NESTING_SEI
+  Void xResetNestedSEIPresentFlags()
+  {
+    m_nestedBufferingPeriodSEIPresentInAU    = false;
+    m_nestedPictureTimingSEIPresentInAU      = false;
+  }
+#endif
+#endif
+#if L0386_DB_METRIC
+  Void dblMetric( TComPic* pcPic, UInt uiNumSlices );
 #endif
 };// END CLASS DEFINITION TEncGOP
Index: trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 125)
+++ trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 189)
@@ -1677,12 +1677,4 @@
 #endif
 {
-#if SAO_CHROMA_LAMBDA 
-  m_dLambdaLuma    = dLambdaLuma;
-  m_dLambdaChroma  = dLambdaChroma;
-#else
-  m_dLambdaLuma    = dLambda;
-  m_dLambdaChroma  = dLambda;
-#endif
-
   if(m_bUseNIF)
   {
Index: trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 125)
+++ trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 189)
@@ -57,7 +57,4 @@
 {
 private:
-  Double            m_dLambdaLuma;
-  Double            m_dLambdaChroma;
-
   TEncEntropy*      m_pcEntropyCoder;
   TEncSbac***       m_pppcRDSbacCoder;              ///< for CABAC
Index: trunk/source/Lib/TLibEncoder/TEncSbac.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSbac.h	(revision 125)
+++ trunk/source/Lib/TLibEncoder/TEncSbac.h	(revision 189)
@@ -109,5 +109,4 @@
   Void  xWriteEpExGolomb     ( UInt uiSymbol, UInt uiCount );
   Void  xWriteCoefRemainExGolomb ( UInt symbol, UInt &rParam );
-  Void  xWriteTerminatingBit ( UInt uiBit );
   
   Void  xCopyFrom            ( TEncSbac* pSrc );
Index: trunk/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 125)
+++ trunk/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 189)
@@ -3249,4 +3249,11 @@
     UInt          uiBitsTempL0[MAX_NUM_REF];
 
+#if L0034_COMBINED_LIST_CLEANUP
+    TComMv        mvValidList1;
+    Int           refIdxValidList1 = 0;
+    UInt          bitsValidList1 = MAX_UINT;
+    UInt          costValidList1 = MAX_UINT;
+#endif
+
 #if (ENCODER_FAST_MODE)
     Bool          testILR;
@@ -3289,5 +3296,5 @@
 #if (ENCODER_FAST_MODE)
         TComPic* pcPic    = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxTemp );
-        if( !testILR && pcPic->isILR() && (ePartSize == SIZE_2Nx2N) ) 
+        if( !testILR && pcPic->isILR(pcCU->getLayerId()) && (ePartSize == SIZE_2Nx2N) ) 
         {
           continue;
@@ -3326,6 +3333,10 @@
         uiBitsTemp += m_auiMVPIdxCost[aaiMvpIdx[iRefList][iRefIdxTemp]][AMVP_MAX_NUM_CANDS];
 #if ZERO_MVD_EST
+#if L0034_COMBINED_LIST_CLEANUP
+        if ( iRefList == 0 || pcCU->getSlice()->getList1IdxToList0Idx( iRefIdxTemp ) < 0 )
+#else
         if ((iRefList != 1 || !pcCU->getSlice()->getNoBackPredFlag()) &&
             (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) <= 0 || pcCU->getSlice()->getRefIdxOfLC(eRefPicList, iRefIdxTemp)>=0))
+#endif
         {
           uiZeroMvdBitsTemp = uiBitsTemp;
@@ -3347,4 +3358,29 @@
         
 #if GPB_SIMPLE_UNI
+#if L0034_COMBINED_LIST_CLEANUP
+        if ( iRefList == 1 )    // list 1
+        {
+          if ( pcCU->getSlice()->getList1IdxToList0Idx( iRefIdxTemp ) >= 0 )
+          {
+            cMvTemp[1][iRefIdxTemp] = cMvTemp[0][pcCU->getSlice()->getList1IdxToList0Idx( iRefIdxTemp )];
+            uiCostTemp = uiCostTempL0[pcCU->getSlice()->getList1IdxToList0Idx( iRefIdxTemp )];
+            /*first subtract the bit-rate part of the cost of the other list*/
+            uiCostTemp -= m_pcRdCost->getCost( uiBitsTempL0[pcCU->getSlice()->getList1IdxToList0Idx( iRefIdxTemp )] );
+            /*correct the bit-rate part of the current ref*/
+            m_pcRdCost->setPredictor  ( cMvPred[iRefList][iRefIdxTemp] );
+            uiBitsTemp += m_pcRdCost->getBits( cMvTemp[1][iRefIdxTemp].getHor(), cMvTemp[1][iRefIdxTemp].getVer() );
+            /*calculate the correct cost*/
+            uiCostTemp += m_pcRdCost->getCost( uiBitsTemp );
+          }
+          else
+          {
+            xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp );
+          }
+        }
+        else
+        {
+          xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp );
+        }
+#else
         if ( pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0)
         {
@@ -3388,4 +3424,5 @@
           }        
         }
+#endif
 #else
         xMotionEstimation ( pcCU, pcOrgYuv, iPartIdx, eRefPicList, &cMvPred[iRefList][iRefIdxTemp], iRefIdxTemp, cMvTemp[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp );
@@ -3394,4 +3431,30 @@
         xCheckBestMVP(pcCU, eRefPicList, cMvTemp[iRefList][iRefIdxTemp], cMvPred[iRefList][iRefIdxTemp], aaiMvpIdx[iRefList][iRefIdxTemp], uiBitsTemp, uiCostTemp);
 
+#if L0034_COMBINED_LIST_CLEANUP
+        if ( iRefList == 0 )
+        {
+          uiCostTempL0[iRefIdxTemp] = uiCostTemp;
+          uiBitsTempL0[iRefIdxTemp] = uiBitsTemp;
+        }
+        if ( uiCostTemp < uiCost[iRefList] )
+        {
+          uiCost[iRefList] = uiCostTemp;
+          uiBits[iRefList] = uiBitsTemp; // storing for bi-prediction
+
+          // set motion
+          cMv[iRefList]     = cMvTemp[iRefList][iRefIdxTemp];
+          iRefIdx[iRefList] = iRefIdxTemp;
+        }
+
+        if ( iRefList == 1 && uiCostTemp < costValidList1 && pcCU->getSlice()->getList1IdxToList0Idx( iRefIdxTemp ) < 0 )
+        {
+          costValidList1 = uiCostTemp;
+          bitsValidList1 = uiBitsTemp;
+
+          // set motion
+          mvValidList1     = cMvTemp[iRefList][iRefIdxTemp];
+          refIdxValidList1 = iRefIdxTemp;
+        }
+#else
         if(pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && !pcCU->getSlice()->getNoBackPredFlag())
         {
@@ -3449,4 +3512,5 @@
             }
           }
+#endif
       }
     }
@@ -3516,8 +3580,33 @@
         
         Int         iRefList    = iIter % 2;
+#if L0034_COMBINED_LIST_CLEANUP
+        if ( m_pcEncCfg->getUseFastEnc() )
+        {
+          if( uiCost[0] <= uiCost[1] )
+          {
+            iRefList = 1;
+          }
+          else
+          {
+            iRefList = 0;
+          }
+        }
+        else if ( iIter == 0 )
+        {
+          iRefList = 0;
+        }
+        if ( iIter == 0 && !pcCU->getSlice()->getMvdL1ZeroFlag())
+        {
+          pcCU->getCUMvField(RefPicList(1-iRefList))->setAllMv( cMv[1-iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
+          pcCU->getCUMvField(RefPicList(1-iRefList))->setAllRefIdx( iRefIdx[1-iRefList], ePartSize, uiPartAddr, 0, iPartIdx );
+          TComYuv*  pcYuvPred = &m_acYuvPred[1-iRefList];
+          motionCompensation ( pcCU, pcYuvPred, RefPicList(1-iRefList), iPartIdx );
+        }
+#else
         if ( m_pcEncCfg->getUseFastEnc() && (pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(0)==0 )) )
         {
           iRefList = 1;
         }
+#endif
         RefPicList  eRefPicList = ( iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0 );
 
@@ -3533,5 +3622,5 @@
         Bool     testIter = true;
         TComPic* pcPic    = pcCU->getSlice()->getRefPic( RefPicList(1 - iRefList), iRefIdxBi[1 - iRefList] );
-        if(pcPic->isILR() && (ePartSize == SIZE_2Nx2N))
+        if(pcPic->isILR(pcCU->getLayerId()) && (ePartSize == SIZE_2Nx2N))
         {
           testIter = false;  //the fixed part is ILR, skip this iteration       
@@ -3548,5 +3637,5 @@
           Bool testRefIdx = true;
           pcPic           = pcCU->getSlice()->getRefPic( RefPicList(iRefList) , iRefIdxTemp );
-          if(pcPic->isILR() && (ePartSize == SIZE_2Nx2N))
+          if(pcPic->isILR(pcCU->getLayerId()) && (ePartSize == SIZE_2Nx2N))
           {
             testRefIdx = false;  //the refined part is ILR, skip this reference pic           
@@ -3680,8 +3769,15 @@
     UInt uiMEBits = 0;
     // Set Motion Field_
+#if L0034_COMBINED_LIST_CLEANUP
+    cMv[1] = mvValidList1;
+    iRefIdx[1] = refIdxValidList1;
+    uiBits[1] = bitsValidList1;
+    uiCost[1] = costValidList1;
+#else
     if ( pcCU->getSlice()->getNoBackPredFlag() || (pcCU->getSlice()->getNumRefIdx(REF_PIC_LIST_C) > 0 && pcCU->getSlice()->getRefIdxOfL0FromRefIdxOfL1(0)==0 ) )
     {
       uiCost[1] = MAX_UINT;
     }
+#endif
 #if AMP_MRG
     if (bTestNormalMC)
@@ -4212,5 +4308,5 @@
   //  Do integer search
 #if REF_IDX_ME_ZEROMV
-  if( pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->isILR())  //ILR reference pic 
+  if( pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->isILR(pcCU->getLayerId()))  //ILR reference pic 
   {
     rcMv.setZero();  //use Mv(0, 0) for integer ME 
@@ -4245,5 +4341,5 @@
   {
 #if REF_IDX_ME_ZEROMV
-    if( pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->isILR())  //ILR reference pic
+    if( pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->isILR(pcCU->getLayerId()))  //ILR reference pic
     {
       xPatternSearchFracDIFMv0( pcCU, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost, bBi );
@@ -4663,5 +4759,5 @@
     while( pcCU->getWidth(0) > (pcCU->getSlice()->getSPS()->getMaxTrSize()<<uiTrLevel) ) uiTrLevel++;
   }
-  UInt uiMaxTrMode = pcCU->getSlice()->getSPS()->getMaxTrDepth() + uiTrLevel;
+  UInt uiMaxTrMode = 1 + uiTrLevel;
   
   while((uiWidth>>uiMaxTrMode) < (g_uiMaxCUWidth>>g_uiMaxCUDepth)) uiMaxTrMode--;
@@ -6219,5 +6315,5 @@
     for( Int refIdx = 0; refIdx < pcCU->getSlice()->getNumRefIdx(eRefPicList); refIdx++ )
     {
-      if( pcCU->getSlice()->getRefPic(eRefPicList, refIdx)->isILR() )
+      if( pcCU->getSlice()->getRefPic(eRefPicList, refIdx)->isILR(pcCU->getLayerId()) )
       {
         iRefIdxTemp = refIdx;
Index: trunk/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 125)
+++ trunk/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 189)
@@ -178,5 +178,10 @@
  \param pPPS          PPS associated with the slice
  */
+#if SVC_EXTENSION
+//\param vps          VPS associated with the slice
+Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, TComVPS *vps )
+#else
 Void TEncSlice::initEncSlice( TComPic* pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd, Int iGOPid, TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS )
+#endif
 {
   Double dQP;
@@ -189,5 +194,7 @@
   rpcSlice->setPic( pcPic );
 #if SVC_EXTENSION
-  rpcSlice->initSlice( pcPic->getLayerId() );
+  UInt layerId = pcPic->getLayerId();
+  rpcSlice->setVPS( vps );
+  rpcSlice->initSlice( layerId );
 #else
   rpcSlice->initSlice();
@@ -337,4 +344,15 @@
   }
 
+#if JCTVC_M0259_LAMBDAREFINEMENT
+  if( rpcSlice->getLayerId() > 0 && depth >= 3 && m_pcCfg->getGOPSize() == ( 1 << depth ) )
+  {
+    Int nCurLayer = rpcSlice->getLayerId();
+    Double gamma = xCalEnhLambdaFactor( m_ppcTEncTop[nCurLayer-1]->getQP() - m_ppcTEncTop[nCurLayer]->getQP() ,
+      1.0 * m_ppcTEncTop[nCurLayer]->getSourceWidth() * m_ppcTEncTop[nCurLayer]->getSourceHeight() 
+      / m_ppcTEncTop[nCurLayer-1]->getSourceWidth() / m_ppcTEncTop[nCurLayer-1]->getSourceHeight() );
+    dLambda *= gamma;
+  }
+#endif
+
   // store lambda
   m_pcRdCost ->setLambda( dLambda );
@@ -354,4 +372,11 @@
   qpc = Clip3( 0, 57, iQP + chromaQPOffset);
   weight = pow( 2.0, (iQP-g_aucChromaScale[qpc])/3.0 );  // takes into account of the chroma qp mapping and chroma qp Offset
+#if JCTVC_M0259_LAMBDAREFINEMENT
+  if( rpcSlice->getLayerId() > 0 && m_pcCfg->getGOPSize() >= 8 && rpcSlice->isIntra() == false && depth == 0 )
+  {
+    dLambda *= 1.1;
+    weight *= 1.15;
+  }
+#endif
   m_pcRdCost->setCrDistortionWeight(weight);
 #endif
@@ -400,4 +425,13 @@
   rpcSlice->setNumRefIdx(REF_PIC_LIST_1,m_pcCfg->getGOPEntry(iGOPid).m_numRefPicsActive);
   
+#if L0386_DB_METRIC
+  if ( m_pcCfg->getDeblockingFilterMetric() )
+  {
+    rpcSlice->setDeblockingFilterOverrideFlag(true);
+    rpcSlice->setDeblockingFilterDisable(false);
+    rpcSlice->setDeblockingFilterBetaOffsetDiv2( 0 );
+    rpcSlice->setDeblockingFilterTcOffsetDiv2( 0 );
+  } else
+#endif
   if (rpcSlice->getPPS()->getDeblockingFilterControlPresentFlag())
   {
@@ -452,4 +486,22 @@
   rpcSlice->setMaxNumMergeCand        ( m_pcCfg->getMaxNumMergeCand()        );
   xStoreWPparam( pPPS->getUseWP(), pPPS->getWPBiPred() );
+
+#if SVC_EXTENSION && REF_IDX_FRAMEWORK
+  if( layerId > 0 )
+  {
+#if JCTVC_M0458_INTERLAYER_RPS_SIG
+  // currently only one reference layer is supported in software and no decision logic to select yet.
+  // hence num of active inter layer references is set to one always
+    if( rpcSlice->getNumILRRefIdx() > 0 )
+    {
+      rpcSlice->setActiveNumILRRefIdx(1);
+      rpcSlice->setInterLayerPredEnabledFlag(1);
+    }
+#else
+    rpcSlice->setNumILRRefIdx( rpcSlice->getVPS()->getNumDirectRefLayers( layerId ) );
+#endif 
+  }
+
+#endif
 }
 
@@ -1182,5 +1234,5 @@
  \retval rpcBitstream  bitstream class
  */
-Void TEncSlice::encodeSlice   ( TComPic*& rpcPic, TComOutputBitstream* pcBitstream, TComOutputBitstream* pcSubstreams )
+Void TEncSlice::encodeSlice   ( TComPic*& rpcPic, TComOutputBitstream* pcSubstreams )
 {
   UInt       uiCUAddr;
@@ -1362,37 +1414,5 @@
       }
       {
-          UInt uiCounter = 0;
-          vector<uint8_t>& rbsp   = pcSubstreams[uiSubStrm].getFIFO();
-          for (vector<uint8_t>::iterator it = rbsp.begin(); it != rbsp.end();)
-          {
-            /* 1) find the next emulated 00 00 {00,01,02,03}
-             * 2a) if not found, write all remaining bytes out, stop.
-             * 2b) otherwise, write all non-emulated bytes out
-             * 3) insert emulation_prevention_three_byte
-             */
-            vector<uint8_t>::iterator found = it;
-            do
-            {
-              /* NB, end()-1, prevents finding a trailing two byte sequence */
-              found = search_n(found, rbsp.end()-1, 2, 0);
-              found++;
-              /* if not found, found == end, otherwise found = second zero byte */
-              if (found == rbsp.end())
-              {
-                break;
-              }
-              if (*(++found) <= 3)
-              {
-                break;
-              }
-            } while (true);
-            it = found;
-            if (found != rbsp.end())
-            {
-              it++;
-              uiCounter++;
-            }
-          }
-        
+        UInt numStartCodeEmulations = pcSubstreams[uiSubStrm].countStartCodeEmulations();
         UInt uiAccumulatedSubstreamLength = 0;
         for (Int iSubstrmIdx=0; iSubstrmIdx < iNumSubstreams; iSubstrmIdx++)
@@ -1402,5 +1422,5 @@
         // add bits coded in previous dependent slices + bits coded so far
         // add number of emulation prevention byte count in the tile
-        pcSlice->addTileLocation( ((pcSlice->getTileOffstForMultES() + uiAccumulatedSubstreamLength - uiBitsOriginallyInSubstreams) >> 3) + uiCounter );
+        pcSlice->addTileLocation( ((pcSlice->getTileOffstForMultES() + uiAccumulatedSubstreamLength - uiBitsOriginallyInSubstreams) >> 3) + numStartCodeEmulations );
       }
     }
@@ -1875,3 +1895,11 @@
 }
 
+#if JCTVC_M0259_LAMBDAREFINEMENT
+Double TEncSlice::xCalEnhLambdaFactor( Double deltaQP , Double beta )
+{
+  double tmp = beta * pow( 2.0 , deltaQP / 6 );
+  double gamma = tmp / ( tmp + 1 );
+  return( gamma );
+}
+#endif
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSlice.h	(revision 125)
+++ trunk/source/Lib/TLibEncoder/TEncSlice.h	(revision 189)
@@ -116,6 +116,12 @@
   
   /// preparation of slice encoding (reference marking, QP and lambda)
+#if SVC_EXTENSION
+  Void    initEncSlice        ( TComPic*  pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd,
+                                Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS, TComVPS *vps );
+#else
   Void    initEncSlice        ( TComPic*  pcPic, Int pocLast, Int pocCurr, Int iNumPicRcvd,
                                 Int iGOPid,   TComSlice*& rpcSlice, TComSPS* pSPS, TComPPS *pPPS );
+#endif
+
 #if RATE_CONTROL_LAMBDA_DOMAIN
   Void    resetQP             ( TComPic* pic, Int sliceQP, Double lambda );
@@ -126,5 +132,5 @@
   Void    precompressSlice    ( TComPic*& rpcPic                                );      ///< precompress slice for multi-loop opt.
   Void    compressSlice       ( TComPic*& rpcPic                                );      ///< analysis stage of slice
-  Void    encodeSlice         ( TComPic*& rpcPic, TComOutputBitstream* rpcBitstream, TComOutputBitstream* pcSubstreams  );
+  Void    encodeSlice         ( TComPic*& rpcPic, TComOutputBitstream* pcSubstreams  );
   
   // misc. functions
@@ -141,4 +147,9 @@
 private:
   Double  xGetQPValueAccordingToLambda ( Double lambda );
+
+#if JCTVC_M0259_LAMBDAREFINEMENT
+private:
+  Double  xCalEnhLambdaFactor( Double deltaQP , Double beta );
+#endif
 };
 
Index: trunk/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncTop.cpp	(revision 125)
+++ trunk/source/Lib/TLibEncoder/TEncTop.cpp	(revision 189)
@@ -294,5 +294,4 @@
     if(m_cIlpPic[i])
     {
-      //m_cIlpPic[i]->setPicYuvRec(NULL);
       m_cIlpPic[i]->destroy();
       delete m_cIlpPic[i];
@@ -500,8 +499,13 @@
     {
       TEncPic* pcEPic = new TEncPic;
+
 #if SVC_EXTENSION //Temporal solution, should be modified
       if(m_layerId > 0)
       {
+#if VPS_EXTN_DIRECT_REF_LAYERS_CONTINUE
+        TEncTop *pcEncTopBase = (TEncTop *)getRefLayerEnc( m_layerId );
+#else
         TEncTop *pcEncTopBase = (TEncTop *)getLayerEnc( m_layerId-1 );
+#endif
         if(m_iSourceWidth != pcEncTopBase->getSourceWidth() || m_iSourceHeight != pcEncTopBase->getSourceHeight() )
         {
@@ -527,5 +531,9 @@
       if(m_layerId > 0)
       {
+#if VPS_EXTN_DIRECT_REF_LAYERS_CONTINUE
+        TEncTop *pcEncTopBase = (TEncTop *)getRefLayerEnc( m_layerId );
+#else
         TEncTop *pcEncTopBase = (TEncTop *)getLayerEnc( m_layerId-1 );
+#endif
         if(m_iSourceWidth != pcEncTopBase->getSourceWidth() || m_iSourceHeight != pcEncTopBase->getSourceHeight() )
         {
@@ -543,4 +551,5 @@
 #endif
     }
+
     if (getUseSAO())
     {
@@ -566,4 +575,7 @@
 #if REF_IDX_MFM
   m_cSPS.setMFMEnabledFlag(m_bMFMEnabledFlag);
+#endif
+#if SCALED_REF_LAYER_OFFSETS
+  m_cSPS.getScaledRefLayerWindow() = m_scaledRefLayerWindow;
 #endif
   ProfileTierLevel& profileTierLevel = *m_cSPS.getPTL()->getGeneralPTL();
@@ -599,6 +611,15 @@
   m_cSPS.setMaxCUHeight   ( g_uiMaxCUHeight     );
   m_cSPS.setMaxCUDepth    ( g_uiMaxCUDepth      );
-  m_cSPS.setMinTrDepth    ( 0                   );
-  m_cSPS.setMaxTrDepth    ( 1                   );
+
+  Int minCUSize = m_cSPS.getMaxCUWidth() >> ( m_cSPS.getMaxCUDepth()-g_uiAddCUDepth );
+  Int log2MinCUSize = 0;
+  while(minCUSize > 1)
+  {
+    minCUSize >>= 1;
+    log2MinCUSize++;
+  }
+
+  m_cSPS.setLog2MinCodingBlockSize(log2MinCUSize);
+  m_cSPS.setLog2DiffMaxMinCodingBlockSize(m_cSPS.getMaxCUDepth()-g_uiAddCUDepth);
 #if SVC_EXTENSION
   m_cSPS.setSPSId         ( m_iSPSIdCnt       );
@@ -618,6 +639,7 @@
 
   m_cSPS.setMaxTrSize   ( 1 << m_uiQuadtreeTULog2MaxSize );
-  
+#if !L0034_COMBINED_LIST_CLEANUP
   m_cSPS.setUseLComb    ( m_bUseLComb           );
+#endif
   
   Int i;
@@ -763,5 +785,20 @@
   m_cPPS.setOutputFlagPresentFlag( false );
   m_cPPS.setSignHideFlag(getSignHideFlag());
+#if L0386_DB_METRIC
+  if ( getDeblockingFilterMetric() )
+  {
+    m_cPPS.setDeblockingFilterControlPresentFlag (true);
+    m_cPPS.setDeblockingFilterOverrideEnabledFlag(true);
+    m_cPPS.setPicDisableDeblockingFilterFlag(false);
+    m_cPPS.setDeblockingFilterBetaOffsetDiv2(0);
+    m_cPPS.setDeblockingFilterTcOffsetDiv2(0);
+  } 
+  else
+  {
   m_cPPS.setDeblockingFilterControlPresentFlag (m_DeblockingFilterControlPresent );
+  }
+#else
+  m_cPPS.setDeblockingFilterControlPresentFlag (m_DeblockingFilterControlPresent );
+#endif
   m_cPPS.setLog2ParallelMergeLevelMinus2   (m_log2ParallelMergeLevelMinus2 );
   m_cPPS.setCabacInitPresentFlag(CABAC_INIT_PRESENT_FLAG);
@@ -810,5 +847,5 @@
     }
   }
-#if REF_LIST_BUGFIX
+#if REF_IDX_FRAMEWORK
   if (!m_layerId)
   {
@@ -1036,4 +1073,36 @@
 }
 
+#if L0208_SOP_DESCRIPTION_SEI
+Int TEncTop::getReferencePictureSetIdxForSOP(TComSlice* slice, Int POCCurr, Int GOPid )
+{
+  int rpsIdx = GOPid;
+
+  for(Int extraNum=m_iGOPSize; extraNum<m_extraRPSs+m_iGOPSize; extraNum++)
+  {    
+    if(m_uiIntraPeriod > 0 && getDecodingRefreshType() > 0)
+    {
+      Int POCIndex = POCCurr%m_uiIntraPeriod;
+      if(POCIndex == 0)
+      {
+        POCIndex = m_uiIntraPeriod;
+      }
+      if(POCIndex == m_GOPList[extraNum].m_POC)
+      {
+        rpsIdx = extraNum;
+      }
+    }
+    else
+    {
+      if(POCCurr==m_GOPList[extraNum].m_POC)
+      {
+        rpsIdx = extraNum;
+      }
+    }
+  }
+
+  return rpsIdx;
+}
+#endif
+
 Void  TEncTop::xInitPPSforTiles()
 {
@@ -1118,4 +1187,24 @@
 }
 
+#if SVC_EXTENSION
+#if VPS_EXTN_DIRECT_REF_LAYERS_CONTINUE
+TEncTop* TEncTop::getRefLayerEnc( UInt layerId )
+{
+  if( m_ppcTEncTop[m_layerId]->getNumDirectRefLayers() <= 0 )
+  {
+#if ZERO_NUM_DIRECT_LAYERS
+    return (TEncTop *)getLayerEnc( 0 );
+#else
+    return NULL;
+#endif
+  }
+
+  // currently only one reference layer is supported
+  assert( m_ppcTEncTop[m_layerId]->getNumDirectRefLayers() == 1 );
+
+  return (TEncTop *)getLayerEnc( getVPS()->getRefLayerId( m_layerId, 0 ) );
+}
+#endif
+
 #if REF_IDX_FRAMEWORK
 Void TEncTop::xInitILRP()
@@ -1123,4 +1212,11 @@
   if(m_layerId>0)
   {
+    g_bitDepthY     = m_cSPS.getBitDepthY();
+    g_bitDepthC     = m_cSPS.getBitDepthC();
+    g_uiMaxCUWidth  = m_cSPS.getMaxCUWidth();
+    g_uiMaxCUHeight = m_cSPS.getMaxCUHeight();
+    g_uiMaxCUDepth  = m_cSPS.getMaxCUDepth();
+    g_uiAddCUDepth  = max (0, m_cSPS.getLog2MinCodingBlockSize() - (Int)m_cSPS.getQuadtreeTULog2MinSize() );
+
     Int  numReorderPics[MAX_TLAYER];
     Window &conformanceWindow = m_cSPS.getConformanceWindow();
@@ -1132,5 +1228,4 @@
       {
         m_cIlpPic[j] = new  TComPic;
-        //m_cIlpPic[j]->createWithOutYuv(m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, &m_cSPS, true);
 #if SVC_UPSAMPLING
         m_cIlpPic[j]->create(m_iSourceWidth, m_iSourceHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth, conformanceWindow, defaultDisplayWindow, numReorderPics, &m_cSPS, true);
@@ -1151,8 +1246,7 @@
   if(m_cIlpPic[0])
   {
-    //m_cIlpPic[0]->setPicYuvRec(pcPic->getFullPelBaseRec());
     m_cIlpPic[0]->copyUpsampledPictureYuv(pcPic->getFullPelBaseRec(), m_cIlpPic[0]->getPicYuvRec());
     m_cIlpPic[0]->getSlice(0)->setPOC(pcPic->getPOC());
-    m_cIlpPic[0]->setLayerId(0); //set reference layerId
+    m_cIlpPic[0]->setLayerId(pcPic->getSlice(0)->getBaseColPic()->getLayerId()); //set reference layerId
     m_cIlpPic[0]->getPicYuvRec()->setBorderExtension(false);
     m_cIlpPic[0]->getPicYuvRec()->extendPicBorder();
@@ -1160,3 +1254,4 @@
 }
 #endif
+#endif
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncTop.h	(revision 125)
+++ trunk/source/Lib/TLibEncoder/TEncTop.h	(revision 189)
@@ -139,4 +139,7 @@
   Bool                    m_bMFMEnabledFlag;
 #endif
+#if SCALED_REF_LAYER_OFFSETS
+  Window                  m_scaledRefLayerWindow;
+#endif
 protected:
   Void  xGetNewPicBuffer  ( TComPic*& rpcPic );           ///< get picture buffer which will be processed
@@ -192,4 +195,7 @@
   TComPPS*                getPPS                () { return  &m_cPPS;                 }
   Void selectReferencePictureSet(TComSlice* slice, Int POCCurr, Int GOPid );
+#if L0208_SOP_DESCRIPTION_SEI
+  Int getReferencePictureSetIdxForSOP(TComSlice* slice, Int POCCurr, Int GOPid );
+#endif
   TComScalingList*        getScalingList        () { return  &m_scalingList;         }
 #if SVC_EXTENSION
@@ -200,4 +206,7 @@
   Void                    setNumPicRcvd         ( Int num ) { m_iNumPicRcvd = num;      }
 #endif
+#if SCALED_REF_LAYER_OFFSETS
+  Window&  getScaledRefLayerWindow()            { return m_scaledRefLayerWindow; }
+#endif
 
   // -------------------------------------------------------------------------------------------------------------------
@@ -209,9 +218,9 @@
 #if REF_IDX_FRAMEWORK
   TComPic** getIlpList() { return m_cIlpPic; }
-  Void setILRPic(TComPic *pcPic);
+  Void      setILRPic(TComPic *pcPic);
 #endif
 #if REF_IDX_MFM
-  Void setMFMEnabledFlag       (Bool flag)   {m_bMFMEnabledFlag = flag;}
-  Bool getMFMEnabledFlag()                   {return m_bMFMEnabledFlag;}    
+  Void      setMFMEnabledFlag       (Bool flag)   {m_bMFMEnabledFlag = flag;}
+  Bool      getMFMEnabledFlag()                   {return m_bMFMEnabledFlag;}    
 #endif
 #if AVC_SYNTAX
@@ -219,7 +228,9 @@
   fstream*  getBLSyntaxFile() { return m_pBLSyntaxFile; }
 #endif
-  Void encode( TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
-              std::list<AccessUnit>& accessUnitsOut, Int iPicIdInGOP  );
-  Void encodePrep( TComPicYuv* pcPicYuvOrg );
+  Void      encode( TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsOut, Int iPicIdInGOP  );
+  Void      encodePrep( TComPicYuv* pcPicYuvOrg );
+#if VPS_EXTN_DIRECT_REF_LAYERS_CONTINUE
+  TEncTop*  getRefLayerEnc(UInt layerId);
+#endif
 #else
   Void encode( Bool bEos, TComPicYuv* pcPicYuvOrg, TComList<TComPicYuv*>& rcListPicYuvRecOut,
Index: trunk/source/Lib/TLibEncoder/WeightPredAnalysis.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 125)
+++ trunk/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 189)
@@ -235,11 +235,15 @@
         Int offset = (Int)( ((currDC<<log2Denom) - ((Int64)weight * refDC) + (Int64)realOffset) >> realLog2Denom );
 
-        // Chroma offset range limination
+        // Chroma offset range limitation
         if(comp)
         {
-          Int shift = 1 << (g_bitDepthC - 1);
-          Int pred = ( shift - ( ( shift*weight)>>(log2Denom) ) );
+          Int pred = ( 128 - ( ( 128*weight)>>(log2Denom) ) );
           Int deltaOffset = Clip3( -512, 511, (offset - pred) );    // signed 10bit
           offset = Clip3( -128, 127, (deltaOffset + pred) );        // signed 8bit
+        }
+        // Luma offset range limitation
+        else
+        {
+          offset = Clip3( -128, 127, offset);
         }
 
