Index: branches/SHM-2.0-dev/source/Lib/TLibCommon/CommonDef.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibCommon/CommonDef.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibCommon/CommonDef.h	(revision 133)
@@ -56,5 +56,5 @@
 // ====================================================================================================================
 
-#define NV_VERSION        "1.2"                 ///< Current software version
+#define NV_VERSION        "2.0"                 ///< Current software version
 
 // ====================================================================================================================
@@ -110,5 +110,7 @@
 #define MAX_NUM_REF_PICS            16          ///< max. number of pictures used for reference
 #define MAX_NUM_REF                 16          ///< max. number of entries in picture reference list
+#if !L0034_COMBINED_LIST_CLEANUP
 #define MAX_NUM_REF_LC              MAX_NUM_REF_PICS  // TODO: remove this macro definition (leftover from combined list concept)
+#endif
 
 #define MAX_UINT                    0xFFFFFFFFU ///< max. value of unsigned 32-bit integer
@@ -197,5 +199,5 @@
   
   NAL_UNIT_CODED_SLICE_TSA_N,     // 2
-  NAL_UNIT_CODED_SLICE_TLA,       // 3   // Current name in the spec: TSA_R
+  NAL_UNIT_CODED_SLICE_TLA_R,       // 3
   
   NAL_UNIT_CODED_SLICE_STSA_N,    // 4
@@ -203,33 +205,33 @@
 
   NAL_UNIT_CODED_SLICE_RADL_N,    // 6
-  NAL_UNIT_CODED_SLICE_DLP,       // 7 // Current name in the spec: RADL_R
+  NAL_UNIT_CODED_SLICE_RADL_R,      // 7
   
   NAL_UNIT_CODED_SLICE_RASL_N,    // 8
-  NAL_UNIT_CODED_SLICE_TFD,       // 9 // Current name in the spec: RASL_R
-
-  NAL_UNIT_RESERVED_10,
-  NAL_UNIT_RESERVED_11,
-  NAL_UNIT_RESERVED_12,
-  NAL_UNIT_RESERVED_13,
-  NAL_UNIT_RESERVED_14,
-  NAL_UNIT_RESERVED_15,
-
-  NAL_UNIT_CODED_SLICE_BLA,       // 16   // Current name in the spec: BLA_W_LP
-  NAL_UNIT_CODED_SLICE_BLANT,     // 17   // Current name in the spec: BLA_W_DLP
+  NAL_UNIT_CODED_SLICE_RASL_R,      // 9
+
+  NAL_UNIT_RESERVED_VCL_N10,
+  NAL_UNIT_RESERVED_VCL_R11,
+  NAL_UNIT_RESERVED_VCL_N12,
+  NAL_UNIT_RESERVED_VCL_R13,
+  NAL_UNIT_RESERVED_VCL_N14,
+  NAL_UNIT_RESERVED_VCL_R15,
+
+  NAL_UNIT_CODED_SLICE_BLA_W_LP,    // 16
+  NAL_UNIT_CODED_SLICE_BLA_W_RADL,  // 17
   NAL_UNIT_CODED_SLICE_BLA_N_LP,  // 18
-  NAL_UNIT_CODED_SLICE_IDR,       // 19  // Current name in the spec: IDR_W_DLP
+  NAL_UNIT_CODED_SLICE_IDR_W_RADL,  // 19
   NAL_UNIT_CODED_SLICE_IDR_N_LP,  // 20
   NAL_UNIT_CODED_SLICE_CRA,       // 21
-  NAL_UNIT_RESERVED_22,
-  NAL_UNIT_RESERVED_23,
-
-  NAL_UNIT_RESERVED_24,
-  NAL_UNIT_RESERVED_25,
-  NAL_UNIT_RESERVED_26,
-  NAL_UNIT_RESERVED_27,
-  NAL_UNIT_RESERVED_28,
-  NAL_UNIT_RESERVED_29,
-  NAL_UNIT_RESERVED_30,
-  NAL_UNIT_RESERVED_31,
+  NAL_UNIT_RESERVED_IRAP_VCL22,
+  NAL_UNIT_RESERVED_IRAP_VCL23,
+
+  NAL_UNIT_RESERVED_VCL24,
+  NAL_UNIT_RESERVED_VCL25,
+  NAL_UNIT_RESERVED_VCL26,
+  NAL_UNIT_RESERVED_VCL27,
+  NAL_UNIT_RESERVED_VCL28,
+  NAL_UNIT_RESERVED_VCL29,
+  NAL_UNIT_RESERVED_VCL30,
+  NAL_UNIT_RESERVED_VCL31,
 
   NAL_UNIT_VPS,                   // 32
@@ -240,13 +242,13 @@
   NAL_UNIT_EOB,                   // 37
   NAL_UNIT_FILLER_DATA,           // 38
-  NAL_UNIT_SEI,                   // 39 Prefix SEI
-  NAL_UNIT_SEI_SUFFIX,            // 40 Suffix SEI
-  NAL_UNIT_RESERVED_41,
-  NAL_UNIT_RESERVED_42,
-  NAL_UNIT_RESERVED_43,
-  NAL_UNIT_RESERVED_44,
-  NAL_UNIT_RESERVED_45,
-  NAL_UNIT_RESERVED_46,
-  NAL_UNIT_RESERVED_47,
+  NAL_UNIT_PREFIX_SEI,              // 39
+  NAL_UNIT_SUFFIX_SEI,              // 40
+  NAL_UNIT_RESERVED_NVCL41,
+  NAL_UNIT_RESERVED_NVCL42,
+  NAL_UNIT_RESERVED_NVCL43,
+  NAL_UNIT_RESERVED_NVCL44,
+  NAL_UNIT_RESERVED_NVCL45,
+  NAL_UNIT_RESERVED_NVCL46,
+  NAL_UNIT_RESERVED_NVCL47,
   NAL_UNIT_UNSPECIFIED_48,
   NAL_UNIT_UNSPECIFIED_49,
Index: branches/SHM-2.0-dev/source/Lib/TLibCommon/NAL.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibCommon/NAL.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibCommon/NAL.h	(revision 133)
@@ -76,24 +76,24 @@
     return m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_R
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_TRAIL_N
-        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TLA
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TLA_R
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_TSA_N
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_R
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_STSA_N
-        || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA
-        || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLANT
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_LP
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_W_RADL
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_BLA_N_LP
-        || m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_W_RADL
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_IDR_N_LP
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_CRA
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_RADL_N
-        || m_nalUnitType == NAL_UNIT_CODED_SLICE_DLP
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_RADL_R
         || m_nalUnitType == NAL_UNIT_CODED_SLICE_RASL_N
-        || m_nalUnitType == NAL_UNIT_CODED_SLICE_TFD;
+        || m_nalUnitType == NAL_UNIT_CODED_SLICE_RASL_R;
   }
 #if L0045_NON_NESTED_SEI_RESTRICTIONS
   Bool isSei()
   {
-    return m_nalUnitType == NAL_UNIT_SEI 
-        || m_nalUnitType == NAL_UNIT_SEI_SUFFIX;
+    return m_nalUnitType == NAL_UNIT_PREFIX_SEI 
+        || m_nalUnitType == NAL_UNIT_SUFFIX_SEI;
   }
 
Index: branches/SHM-2.0-dev/source/Lib/TLibCommon/SEI.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibCommon/SEI.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibCommon/SEI.cpp	(revision 133)
@@ -38,4 +38,9 @@
 #include "CommonDef.h"
 #include "SEI.h"
+
+#if J0149_TONE_MAPPING_SEI 
+//Table D-7 Meaning of camera iso sensitivity indicator and exposure index rating indicator
+Int  Table_exp_indicator[32] = {0, 10, 12, 16, 20, 25, 32, 40, 50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, -1};
+#endif
 
 SEIMessages getSeisByType(SEIMessages &seiList, SEI::PayloadType seiType)
Index: branches/SHM-2.0-dev/source/Lib/TLibCommon/SEI.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibCommon/SEI.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibCommon/SEI.h	(revision 133)
@@ -355,4 +355,58 @@
 };
 
+#if L0208_SOP_DESCRIPTION_SEI
+class SEISOPDescription : public SEI
+{
+public:
+  PayloadType payloadType() const { return SOP_DESCRIPTION; }
+
+  SEISOPDescription() {}
+  virtual ~SEISOPDescription() {}
+
+  UInt m_sopSeqParameterSetId;
+  UInt m_numPicsInSopMinus1;
+
+  UInt m_sopDescVclNaluType[MAX_NUM_PICS_IN_SOP];
+  UInt m_sopDescTemporalId[MAX_NUM_PICS_IN_SOP];
+  UInt m_sopDescStRpsIdx[MAX_NUM_PICS_IN_SOP];
+  Int m_sopDescPocDelta[MAX_NUM_PICS_IN_SOP];
+};
+#endif
+
+#if J0149_TONE_MAPPING_SEI 
+class SEIToneMappingInfo : public SEI
+{
+public:
+  PayloadType payloadType() const { return TONE_MAPPING_INFO; }
+  SEIToneMappingInfo() {}
+  virtual ~SEIToneMappingInfo() {}
+
+  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;
+  std::vector<Int> m_startOfCodedInterval;
+  Int    m_numPivots;
+  std::vector<Int> m_codedPivotValue;
+  std::vector<Int> m_targetPivotValue;
+  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;
+};
+#endif
+
 typedef std::list<SEI*> SEIMessages;
 
@@ -366,3 +420,35 @@
 Void deleteSEIs (SEIMessages &seiList);
 
+#if K0180_SCALABLE_NESTING_SEI
+class SEIScalableNesting : public SEI
+{
+public:
+  PayloadType payloadType() const { return SCALABLE_NESTING; }
+
+  SEIScalableNesting() {}
+  virtual ~SEIScalableNesting()
+  {
+    if (!m_callerOwnsSEIs)
+    {
+      deleteSEIs(m_nestedSEIs);
+    }
+  }
+
+  Bool  m_bitStreamSubsetFlag;
+  Bool  m_nestingOpFlag;
+  Bool  m_defaultOpFlag;                             //value valid if m_nestingOpFlag != 0
+  UInt  m_nestingNumOpsMinus1;                       // -"-
+  UInt  m_nestingMaxTemporalIdPlus1[MAX_TLAYER];     // -"-
+  UInt  m_nestingOpIdx[MAX_NESTING_NUM_OPS];         // -"-
+
+  Bool  m_allLayersFlag;                             //value valid if m_nestingOpFlag == 0
+  UInt  m_nestingNoOpMaxTemporalIdPlus1;             //value valid if m_nestingOpFlag == 0 and m_allLayersFlag == 0
+  UInt  m_nestingNumLayersMinus1;                    //value valid if m_nestingOpFlag == 0 and m_allLayersFlag == 0
+  UChar m_nestingLayerId[MAX_NESTING_NUM_LAYER];     //value valid if m_nestingOpFlag == 0 and m_allLayersFlag == 0. This can e.g. be a static array of 64 unsigned char values
+
+  Bool  m_callerOwnsSEIs;
+  SEIMessages m_nestedSEIs;
+};
+#endif
+
 //! \}
Index: branches/SHM-2.0-dev/source/Lib/TLibCommon/TComBitStream.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibCommon/TComBitStream.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibCommon/TComBitStream.cpp	(revision 133)
@@ -177,4 +177,5 @@
   }
 }
+
 Void TComOutputBitstream::writeByteAlignment()
 {
@@ -182,4 +183,37 @@
   writeAlignZero();
 }
+
+Int TComOutputBitstream::countStartCodeEmulations()
+{
+  UInt cnt = 0;
+  vector<uint8_t>& rbsp   = getFIFO();
+  for (vector<uint8_t>::iterator it = rbsp.begin(); it != rbsp.end();)
+  {
+    vector<uint8_t>::iterator found = it;
+    do
+    {
+      // find the next emulated 00 00 {00,01,02,03}
+      // 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())
+    {
+      cnt++;
+    }
+  }
+  return cnt;
+}
+
 /**
  * read #uiNumberOfBits# from bitstream without updating the bitstream
Index: branches/SHM-2.0-dev/source/Lib/TLibCommon/TComBitStream.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibCommon/TComBitStream.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibCommon/TComBitStream.h	(revision 133)
@@ -154,4 +154,7 @@
   Void          addSubstream    ( TComOutputBitstream* pcSubstream );
   Void writeByteAlignment();
+
+  //! returns the number of start code emulations contained in the current buffer
+  Int countStartCodeEmulations();
 };
 
@@ -163,4 +166,5 @@
 {
   std::vector<uint8_t> *m_fifo; /// FIFO for storage of complete bytes
+  std::vector<UInt> m_emulationPreventionByteLocation;
 
 protected:
@@ -206,4 +210,11 @@
   UInt  getNumBitsRead() { return m_numBitsRead; }
   Void readByteAlignment();
+
+  Void      pushEmulationPreventionByteLocation ( UInt pos )                  { m_emulationPreventionByteLocation.push_back( pos ); }
+  UInt      numEmulationPreventionBytesRead     ()                            { return (UInt) m_emulationPreventionByteLocation.size();    }
+  std::vector<UInt>  getEmulationPreventionByteLocation  ()                   { return m_emulationPreventionByteLocation;           }
+  UInt      getEmulationPreventionByteLocation  ( UInt idx )                  { return m_emulationPreventionByteLocation[ idx ];    }
+  Void      clearEmulationPreventionByteLocation()                            { m_emulationPreventionByteLocation.clear();          }
+  Void      setEmulationPreventionByteLocation  ( std::vector<UInt> vec )     { m_emulationPreventionByteLocation = vec;            }
 };
 
Index: branches/SHM-2.0-dev/source/Lib/TLibCommon/TComLoopFilter.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 133)
@@ -57,10 +57,10 @@
 // ====================================================================================================================
 
-const UChar tctable_8x8[54] =
+const UChar TComLoopFilter::sm_tcTable[54] =
 {
   0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,5,5,6,6,7,8,9,10,11,13,14,16,18,20,22,24
 };
 
-const UChar betatable_8x8[52] =
+const UChar TComLoopFilter::sm_betaTable[52] =
 {
   0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,7,8,9,10,11,12,13,14,15,16,17,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64
@@ -585,6 +585,6 @@
       Int iIndexB = Clip3(0, MAX_QP, iQP + (betaOffsetDiv2 << 1));
       
-      Int iTc =  tctable_8x8[iIndexTC]*iBitdepthScale;
-      Int iBeta = betatable_8x8[iIndexB]*iBitdepthScale;
+      Int iTc =  sm_tcTable[iIndexTC]*iBitdepthScale;
+      Int iBeta = sm_betaTable[iIndexB]*iBitdepthScale;
       Int iSideThreshold = (iBeta+(iBeta>>1))>>3;
       Int iThrCut = iTc*10;
@@ -735,5 +735,5 @@
 
         Int iIndexTC = Clip3(0, MAX_QP+DEFAULT_INTRA_TC_OFFSET, iQP + DEFAULT_INTRA_TC_OFFSET*(ucBs - 1) + (tcOffsetDiv2 << 1));
-        Int iTc =  tctable_8x8[iIndexTC]*iBitdepthScale;
+        Int iTc =  sm_tcTable[iIndexTC]*iBitdepthScale;
 
         for ( UInt uiStep = 0; uiStep < uiPelsInPartChroma; uiStep++ )
Index: branches/SHM-2.0-dev/source/Lib/TLibCommon/TComLoopFilter.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibCommon/TComLoopFilter.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibCommon/TComLoopFilter.h	(revision 133)
@@ -99,4 +99,7 @@
   __inline Int xCalcDQ( Pel* piSrc, Int iOffset);
   
+  static const UChar sm_tcTable[54];
+  static const UChar sm_betaTable[52];
+
 public:
   TComLoopFilter();
@@ -111,4 +114,10 @@
   /// picture-level deblocking filter
   Void loopFilterPic( TComPic* pcPic );
+
+  static Int getBeta( Int qp )
+  {
+    Int indexB = Clip3( 0, MAX_QP, qp );
+    return sm_betaTable[ indexB ];
+  }
 };
 
Index: branches/SHM-2.0-dev/source/Lib/TLibCommon/TComPic.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibCommon/TComPic.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibCommon/TComPic.cpp	(revision 133)
@@ -559,5 +559,5 @@
 }
 
-Void TComPic:: copyUpsampledPictureYuv(TComPicYuv*   pcPicYuvIn, TComPicYuv*   pcPicYuvOut)
+Void TComPic::copyUpsampledPictureYuv(TComPicYuv*   pcPicYuvIn, TComPicYuv*   pcPicYuvOut)
 {
   Int upsampledRowWidthLuma = pcPicYuvOut->getStride(); // 2 * pcPicYuvOut->getLumaMargin() + pcPicYuvOut->getWidth(); 
Index: branches/SHM-2.0-dev/source/Lib/TLibCommon/TComPicYuv.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 133)
@@ -60,4 +60,5 @@
   m_piPicOrgU       = NULL;
   m_piPicOrgV       = NULL;
+  
   m_bIsBorderExtended = false;
 }
Index: branches/SHM-2.0-dev/source/Lib/TLibCommon/TComPrediction.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibCommon/TComPrediction.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibCommon/TComPrediction.cpp	(revision 133)
@@ -83,6 +83,6 @@
   if( m_piYuvExt == NULL )
   {
-    Int extWidth  = g_uiMaxCUWidth + 16; 
-    Int extHeight = g_uiMaxCUHeight + 1;
+    Int extWidth  = MAX_CU_SIZE + 16; 
+    Int extHeight = MAX_CU_SIZE + 1;
     Int i, j;
     for (i = 0; i < 4; i++)
@@ -94,18 +94,18 @@
       }
     }
-    m_iYuvExtHeight  = ((g_uiMaxCUHeight + 2) << 4);
-    m_iYuvExtStride = ((g_uiMaxCUWidth  + 8) << 4);
+    m_iYuvExtHeight  = ((MAX_CU_SIZE + 2) << 4);
+    m_iYuvExtStride = ((MAX_CU_SIZE  + 8) << 4);
     m_piYuvExt = new Int[ m_iYuvExtStride * m_iYuvExtHeight ];
 
     // new structure
-    m_acYuvPred[0] .create( g_uiMaxCUWidth, g_uiMaxCUHeight );
-    m_acYuvPred[1] .create( g_uiMaxCUWidth, g_uiMaxCUHeight );
-
-    m_cYuvPredTemp.create( g_uiMaxCUWidth, g_uiMaxCUHeight );
-  }
-
-  if (m_iLumaRecStride != (g_uiMaxCUWidth>>1) + 1)
-  {
-    m_iLumaRecStride =  (g_uiMaxCUWidth>>1) + 1;
+    m_acYuvPred[0] .create( MAX_CU_SIZE, MAX_CU_SIZE );
+    m_acYuvPred[1] .create( MAX_CU_SIZE, MAX_CU_SIZE );
+
+    m_cYuvPredTemp.create( MAX_CU_SIZE, MAX_CU_SIZE );
+  }
+
+  if (m_iLumaRecStride != (MAX_CU_SIZE>>1) + 1)
+  {
+    m_iLumaRecStride =  (MAX_CU_SIZE>>1) + 1;
     if (!m_pLumaRecBuffer)
     {
Index: branches/SHM-2.0-dev/source/Lib/TLibCommon/TComRom.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibCommon/TComRom.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibCommon/TComRom.cpp	(revision 133)
@@ -62,5 +62,4 @@
   g_aucConvertToBit[ i ] = c;
   
-  // g_auiFrameScanXY[ g_aucConvertToBit[ transformSize ] ]: zigzag scan array for transformSize
   c=2;
   for ( i=0; i<MAX_CU_DEPTH; i++ )
@@ -77,7 +76,5 @@
 Void destroyROM()
 {
-  Int i;
-  
-  for ( i=0; i<MAX_CU_DEPTH; i++ )
+  for (Int i=0; i<MAX_CU_DEPTH; i++ )
   {
     delete[] g_auiSigLastScan[0][i];
Index: branches/SHM-2.0-dev/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibCommon/TComSlice.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibCommon/TComSlice.cpp	(revision 133)
@@ -54,5 +54,5 @@
 , m_iPOC                          ( 0 )
 , m_iLastIDR                      ( 0 )
-, m_eNalUnitType                  ( NAL_UNIT_CODED_SLICE_IDR )
+, m_eNalUnitType                  ( NAL_UNIT_CODED_SLICE_IDR_W_RADL )
 , m_eSliceType                    ( I_SLICE )
 , m_iSliceQp                      ( 0 )
@@ -65,6 +65,8 @@
 , m_deblockingFilterBetaOffsetDiv2 ( 0 )
 , m_deblockingFilterTcOffsetDiv2   ( 0 )
+#if !L0034_COMBINED_LIST_CLEANUP
 , m_bRefPicListModificationFlagLC ( false )
 , m_bRefPicListCombinationFlag    ( false )
+#endif
 , m_bCheckLDC                     ( false )
 , m_iSliceQpDelta                 ( 0 )
@@ -84,5 +86,7 @@
 , m_dLambda                       ( 0.0 )
 #endif
-, m_bNoBackPredFlag               ( false )
+#if !L0034_COMBINED_LIST_CLEANUP
+, m_bNoBackPredFlag             ( false )
+#endif
 , m_uiTLayer                      ( 0 )
 #if SVC_EXTENSION
@@ -113,5 +117,9 @@
 , m_enableTMVPFlag                ( true )
 {
+#if L0034_COMBINED_LIST_CLEANUP
+  m_aiNumRefIdx[0] = m_aiNumRefIdx[1] = 0;
+#else
   m_aiNumRefIdx[0] = m_aiNumRefIdx[1] = m_aiNumRefIdx[2] = 0;
+#endif
   
 #if REF_LIST_BUGFIX
@@ -120,4 +128,10 @@
   initEqualRef();
   
+#if L0034_COMBINED_LIST_CLEANUP
+  for ( Int idx = 0; idx < MAX_NUM_REF; idx++ )
+  {
+    m_list1IdxToList0Idx[idx] = -1;
+  }
+#else
   for(Int iNumCount = 0; iNumCount < MAX_NUM_REF_LC; iNumCount++)
   {
@@ -129,4 +143,5 @@
     m_iRefIdxOfL1FromRefIdxOfL0[iNumCount] = -1;
   }    
+#endif
   for(Int iNumCount = 0; iNumCount < MAX_NUM_REF; iNumCount++)
   {
@@ -136,5 +151,5 @@
     m_aiRefPOCList  [1][iNumCount] = 0;
   }
-  resetWpScaling(m_weightPredTable);
+  resetWpScaling();
   initWpAcDcParam();
   m_saoEnabledFlag = false;
@@ -173,12 +188,16 @@
   m_colRefIdx = 0;
   initEqualRef();
+#if !L0034_COMBINED_LIST_CLEANUP
   m_bNoBackPredFlag = false;
   m_bRefPicListCombinationFlag = false;
   m_bRefPicListModificationFlagLC = false;
+#endif
   m_bCheckLDC = false;
   m_iSliceQpDeltaCb = 0;
   m_iSliceQpDeltaCr = 0;
 
+#if !L0034_COMBINED_LIST_CLEANUP
   m_aiNumRefIdx[REF_PIC_LIST_C]      = 0;
+#endif
 
   m_maxNumMergeCand = MRG_MAX_NUM_CANDS;
@@ -194,9 +213,9 @@
 Bool TComSlice::getRapPicFlag()
 {
-  return getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR
+  return getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
       || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
       || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
-      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT
-      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
       || getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA;
 }
@@ -213,5 +232,5 @@
 }
 
-Void  TComSlice::sortPicList        (TComList<TComPic*>& rcListPic)
+Void  TComSlice::sortPicList(TComList<TComPic*>& rcListPic)
 {
   TComPic*    pcPicExtract;
@@ -268,16 +287,30 @@
 
 
-TComPic* TComSlice::xGetLongTermRefPic (TComList<TComPic*>& rcListPic,
-                                        Int                 poc)
+TComPic* TComSlice::xGetLongTermRefPic(TComList<TComPic*>& rcListPic, Int poc, Bool pocHasMsb)
 {
   TComList<TComPic*>::iterator  iterPic = rcListPic.begin();  
   TComPic*                      pcPic = *(iterPic);
   TComPic*                      pcStPic = pcPic;
+  
+  Int pocCycle = 1 << getSPS()->getBitsForPOC();
+  if (!pocHasMsb)
+  {
+    poc = poc % pocCycle;
+  }
+  
   while ( iterPic != rcListPic.end() )
   {
     pcPic = *(iterPic);
-    if(pcPic && (pcPic->getPOC()%(1<<getSPS()->getBitsForPOC())) == (poc%(1<<getSPS()->getBitsForPOC())))
-    {
-      if(pcPic->getIsLongTerm())
+    if (pcPic && pcPic->getPOC()!=this->getPOC() && pcPic->getSlice( 0 )->isReferenced())
+    {
+      Int picPoc = pcPic->getPOC();
+      if (!pocHasMsb)
+      {
+        picPoc = picPoc % pocCycle;
+      }
+      
+      if (poc == picPoc)
+      {
+       if (pcPic->getIsLongTerm())
       {
         return pcPic;
@@ -289,11 +322,13 @@
       break;
     }
+    }
 
     iterPic++;
   }
+  
   return  pcStPic;
 }
 
-Void TComSlice::setRefPOCList       ()
+Void TComSlice::setRefPOCList()
 {
   for (Int iDir = 0; iDir < 2; iDir++)
@@ -307,4 +342,22 @@
 }
 
+#if L0034_COMBINED_LIST_CLEANUP
+Void TComSlice::setList1IdxToList0Idx()
+{
+  Int idxL0, idxL1;
+  for ( idxL1 = 0; idxL1 < getNumRefIdx( REF_PIC_LIST_1 ); idxL1++ )
+  {
+    m_list1IdxToList0Idx[idxL1] = -1;
+    for ( idxL0 = 0; idxL0 < getNumRefIdx( REF_PIC_LIST_0 ); idxL0++ )
+    {
+      if ( m_apcRefPicList[REF_PIC_LIST_0][idxL0]->getPOC() == m_apcRefPicList[REF_PIC_LIST_1][idxL1]->getPOC() )
+      {
+        m_list1IdxToList0Idx[idxL1] = idxL0;
+        break;
+      }
+    }
+  }
+}
+#else
 Void TComSlice::generateCombinedList()
 {
@@ -369,10 +422,19 @@
   }
 }
-
-Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic)
-{
+#endif
+
+#if FIX1071
+Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr )
+#else
+Void TComSlice::setRefPicList( TComList<TComPic*>& rcListPic )
+#endif
+{
+#if FIX1071
+  if (!checkNumPocTotalCurr)
+#endif
+  {
 #if REF_IDX_FRAMEWORK
   if( m_eSliceType == I_SLICE || ( getSPS()->getLayerId() && 
-      (getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA) &&
+      (getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP) &&
       (getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA) ) )
 #else
@@ -388,4 +450,5 @@
   m_aiNumRefIdx[0] = getNumRefIdx(REF_PIC_LIST_0);
   m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
+  }
 
   TComPic*  pcRefPic= NULL;
@@ -410,4 +473,5 @@
     }
   }
+  
   for(; i < m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures(); i++)
   {
@@ -422,9 +486,10 @@
     }
   }
+  
   for(i = m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()+m_pcRPS->getNumberOfLongtermPictures()-1; i > m_pcRPS->getNumberOfNegativePictures()+m_pcRPS->getNumberOfPositivePictures()-1 ; i--)
   {
     if(m_pcRPS->getUsed(i))
     {
-      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i));
+      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i), m_pcRPS->getCheckLTMSBPresent(i));
       pcRefPic->setIsLongTerm(1);
       pcRefPic->getPicYuvRec()->extendPicBorder();
@@ -434,5 +499,5 @@
     if(pcRefPic==NULL) 
     {
-      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i));
+      pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i), m_pcRPS->getCheckLTMSBPresent(i));
     }
     pcRefPic->setCheckLTMSBPresent(m_pcRPS->getCheckLTMSBPresent(i));  
@@ -443,6 +508,30 @@
   TComPic*  rpsCurrList1[MAX_NUM_REF+1];
   Int numPocTotalCurr = NumPocStCurr0 + NumPocStCurr1 + NumPocLtCurr;
-
-  {
+#if FIX1071
+  if (checkNumPocTotalCurr)
+  {
+    // The variable NumPocTotalCurr is derived as specified in subclause 7.4.7.2. It is a requirement of bitstream conformance that the following applies to the value of NumPocTotalCurr:
+    // – If the current picture is a BLA or CRA picture, the value of NumPocTotalCurr shall be equal to 0.
+    // – Otherwise, when the current picture contains a P or B slice, the value of NumPocTotalCurr shall not be equal to 0.
+    if (getRapPicFlag())
+    {
+      assert(numPocTotalCurr == 0);
+    }
+
+    if (m_eSliceType == I_SLICE)
+  {
+      ::memset( m_apcRefPicList, 0, sizeof (m_apcRefPicList));
+      ::memset( m_aiNumRefIdx,   0, sizeof ( m_aiNumRefIdx ));
+      
+      return;
+    }
+    
+    assert(numPocTotalCurr != 0);
+    
+    m_aiNumRefIdx[0] = getNumRefIdx(REF_PIC_LIST_0);
+    m_aiNumRefIdx[1] = getNumRefIdx(REF_PIC_LIST_1);
+  }
+#endif
+  
     Int cIdx = 0;
     for ( i=0; i<NumPocStCurr0; i++, cIdx++)
@@ -458,9 +547,8 @@
       rpsCurrList0[cIdx] = RefPicSetLtCurr[i];
     }
-  }
 
   if (m_eSliceType==B_SLICE)
   {
-    Int cIdx = 0;
+    cIdx = 0;
     for ( i=0; i<NumPocStCurr1; i++, cIdx++)
     {
@@ -509,6 +597,8 @@
   }
 
-  if(this->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA && this->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA)
+  if(this->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && this->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA)
+  {
     return;
+  }
 
   TComRefPicListModification* refPicListModification = this->getRefPicListModification();
@@ -589,5 +679,5 @@
 
   //temporal reference pictures
-  if( !(getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA && getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA) )
+  if( !(getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA) )
   { 
     for(i=0; i < m_pcRPS->getNumberOfNegativePictures(); i++)
@@ -619,5 +709,5 @@
       if(m_pcRPS->getUsed(i))
       {
-        pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i));
+        pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i), m_pcRPS->getCheckLTMSBPresent(i));
         pcRefPic->setIsLongTerm(1);
         pcRefPic->getPicYuvRec()->extendPicBorder();
@@ -627,5 +717,5 @@
       if(pcRefPic==NULL) 
       {
-        pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i));
+        pcRefPic = xGetLongTermRefPic(rcListPic, m_pcRPS->getPOC(i), m_pcRPS->getCheckLTMSBPresent(i));
       }
       pcRefPic->setCheckLTMSBPresent(m_pcRPS->getCheckLTMSBPresent(i));  
@@ -636,5 +726,5 @@
 #if REF_IDX_MFM
   assert(m_aiNumILRRefIdx == 1);
-  if(!(getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA && getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA) && getSPS()->getMFMEnabledFlag())
+  if(!(getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA) && getSPS()->getMFMEnabledFlag())
   { 
     ilpPic[0]->copyUpsampledMvField(getBaseColPic());
@@ -672,23 +762,39 @@
   { 
     for ( i=0; i<NumPocStCurr0 && cIdx<numRpsCurrTempList0; cIdx++,i++) 
-      refPicListTemp0[cIdx] = RefPicSetStCurr0[ i ];   
-    for ( i=0; i<NumPocStCurr1 && cIdx<numRpsCurrTempList0; cIdx++,i++) 
-      refPicListTemp0[cIdx] = RefPicSetStCurr1[ i ]; 
-    for ( i=0; i<NumPocLtCurr && cIdx<numRpsCurrTempList0; cIdx++,i++) 
+    {
+      refPicListTemp0[cIdx] = RefPicSetStCurr0[ i ];
+    }
+    for ( i=0; i<NumPocStCurr1 && cIdx<numRpsCurrTempList0; cIdx++,i++)
+    {
+      refPicListTemp0[cIdx] = RefPicSetStCurr1[ i ];
+    }
+    for ( i=0; i<NumPocLtCurr && cIdx<numRpsCurrTempList0; cIdx++,i++)
+    {
       refPicListTemp0[cIdx] = RefPicSetLtCurr[ i ];
+    }
     for ( i=0; i<m_aiNumILRRefIdx && cIdx<numRpsCurrTempList0; cIdx++,i++)
+    {
       refPicListTemp0[cIdx] = ilpPic[ i ];
+    }
   }
   cIdx = 0;
   while (cIdx<numRpsCurrTempList1 && m_eSliceType==B_SLICE)
   { 
-    for ( i=0; i<NumPocStCurr1 && cIdx<numRpsCurrTempList1; cIdx++,i++) 
+    for ( i=0; i<NumPocStCurr1 && cIdx<numRpsCurrTempList1; cIdx++,i++)
+    {
       refPicListTemp1[cIdx] = RefPicSetStCurr1[ i ];
-    for ( i=0; i<NumPocStCurr0 && cIdx<numRpsCurrTempList1; cIdx++,i++) 
-      refPicListTemp1[cIdx] = RefPicSetStCurr0[ i ]; 
-    for ( i=0; i<NumPocLtCurr && cIdx<numRpsCurrTempList1; cIdx++,i++) 
+    }
+    for ( i=0; i<NumPocStCurr0 && cIdx<numRpsCurrTempList1; cIdx++,i++)
+    {
+      refPicListTemp1[cIdx] = RefPicSetStCurr0[ i ];
+    }
+    for ( i=0; i<NumPocLtCurr && cIdx<numRpsCurrTempList1; cIdx++,i++)
+    {
       refPicListTemp1[cIdx] = RefPicSetLtCurr[ i ];
+    }
     for ( i=0; i<m_aiNumILRRefIdx && cIdx<numRpsCurrTempList1; cIdx++,i++)
+    {
       refPicListTemp1[cIdx] = ilpPic[ i ];
+    }
   }
   ::memset(m_bIsUsedAsLongTerm, 0, sizeof(m_bIsUsedAsLongTerm));
@@ -724,5 +830,5 @@
 #if REF_IDX_FRAMEWORK
   if( m_eSliceType == I_SLICE || ( getSPS()->getLayerId() && 
-    (getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA) &&
+    (getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP) &&
     (getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA) ) )
 #else
@@ -793,5 +899,5 @@
 }
 
-Void TComSlice::checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, Bool& prevRAPisBLA)
+Void TComSlice::checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, Bool& prevRAPisBLA, TComList<TComPic *>& rcListPic)
 {
   for(Int i = 0; i < pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures(); i++)
@@ -806,8 +912,15 @@
     if(pocCRA < MAX_UINT && getPOC() > pocCRA)
     {
+      if (!pReferencePictureSet->getCheckLTMSBPresent(i))
+      {
+        assert(xGetLongTermRefPic(rcListPic, pReferencePictureSet->getPOC(i), false)->getPOC() >= pocCRA);
+      }
+      else
+      {
       assert(pReferencePictureSet->getPOC(i) >= pocCRA);
     }
   }
-  if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP ) // IDR picture found
+  }
+  if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP ) // IDR picture found
   {
     pocCRA = getPOC();
@@ -819,6 +932,6 @@
     prevRAPisBLA = false;
   }
-  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
-         || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT
+  else if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+         || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
          || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP ) // BLA picture found
   {
@@ -851,8 +964,8 @@
   Int pocCurr = getPOC(); 
 
-  if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
-    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT
+  if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+    || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
     || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
-    || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR
+    || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
     || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )  // IDR or BLA picture
   {
@@ -866,6 +979,6 @@
       iterPic++;
     }
-    if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
-      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT
+    if ( getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+      || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
       || getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
     {
@@ -881,5 +994,8 @@
       {
         rpcPic = *(iterPic);
-        if (rpcPic->getPOC() != pocCurr && rpcPic->getPOC() != pocCRA) rpcPic->getSlice(0)->setReferenced(false);
+        if (rpcPic->getPOC() != pocCurr && rpcPic->getPOC() != pocCRA)
+        {
+          rpcPic->getSlice(0)->setReferenced(false);
+        }
         iterPic++;
       }
@@ -912,9 +1028,19 @@
   m_deblockingFilterTcOffsetDiv2 = pSrc->m_deblockingFilterTcOffsetDiv2;
   
+#if L0034_COMBINED_LIST_CLEANUP
+  for (i = 0; i < 2; i++)
+#else
   for (i = 0; i < 3; i++)
+#endif
   {
     m_aiNumRefIdx[i]     = pSrc->m_aiNumRefIdx[i];
   }
 
+#if L0034_COMBINED_LIST_CLEANUP
+  for (i = 0; i < MAX_NUM_REF; i++)
+  {
+    m_list1IdxToList0Idx[i] = pSrc->m_list1IdxToList0Idx[i];
+  } 
+#else
   for (i = 0; i < 2; i++)
   {
@@ -933,4 +1059,5 @@
   m_bRefPicListModificationFlagLC = pSrc->m_bRefPicListModificationFlagLC;
   m_bRefPicListCombinationFlag    = pSrc->m_bRefPicListCombinationFlag;
+#endif
   m_bCheckLDC             = pSrc->m_bCheckLDC;
   m_iSliceQpDelta        = pSrc->m_iSliceQpDelta;
@@ -984,5 +1111,7 @@
   }
 
+#if !L0034_COMBINED_LIST_CLEANUP
   m_bNoBackPredFlag      = pSrc->m_bNoBackPredFlag;
+#endif
   m_uiTLayer                      = pSrc->m_uiTLayer;
   m_bTLayerSwitchingFlag          = pSrc->m_bTLayerSwitchingFlag;
@@ -1018,4 +1147,5 @@
 
 Int TComSlice::m_prevPOC = 0;
+
 /** Function for setting the slice's temporal layer ID and corresponding temporal_layer_switching_point_flag.
  * \param uiTLayer Temporal layer ID of the current slice
@@ -1078,11 +1208,14 @@
   Int i, isReference;
 
-  Int j = 0;
   // loop through all pictures in the reference picture buffer
   TComList<TComPic*>::iterator iterPic = rcListPic.begin();
   while ( iterPic != rcListPic.end())
   {
-    j++;
     rpcPic = *(iterPic++);
+
+    if(!rpcPic->getSlice( 0 )->isReferenced())
+    {
+      continue;
+    }
 
     isReference = 0;
@@ -1123,4 +1256,5 @@
     {            
       rpcPic->getSlice( 0 )->setReferenced( false );   
+      rpcPic->setUsedByCurr(0);
       rpcPic->setIsLongTerm(0);
     }
@@ -1128,5 +1262,5 @@
     assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getUsedByCurr()==0||rpcPic->getTLayer()<=this->getTLayer());
     //check that pictures of higher or equal temporal layer are not in the RPS if the current picture is a TSA picture
-    if(this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TLA || this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N)
+    if(this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TLA_R || this->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N)
     {
       assert(rpcPic->getSlice( 0 )->isReferenced()==0||rpcPic->getTLayer()<this->getTLayer());
@@ -1145,5 +1279,5 @@
 {
   TComPic* rpcPic;
-  Int i, isAvailable, j;
+  Int i, isAvailable;
   Int atLeastOneLost = 0;
   Int atLeastOneRemoved = 0;
@@ -1154,5 +1288,4 @@
   for(i=pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures();i<pReferencePictureSet->getNumberOfPictures();i++)
   {
-    j = 0;
     isAvailable = 0;
     // loop through all pictures in the reference picture buffer
@@ -1160,5 +1293,4 @@
     while ( iterPic != rcListPic.end())
     {
-      j++;
       rpcPic = *(iterPic++);
       if(pReferencePictureSet->getCheckLTMSBPresent(i)==true)
@@ -1183,8 +1315,16 @@
       while ( iterPic != rcListPic.end())
       {
-        j++;
         rpcPic = *(iterPic++);
 
-        if((rpcPic->getPicSym()->getSlice(0)->getPOC()%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC())) == (this->getPOC() + pReferencePictureSet->getDeltaPOC(i))%(1<<rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC()) && rpcPic->getSlice(0)->isReferenced())
+        Int pocCycle = 1 << rpcPic->getPicSym()->getSlice(0)->getSPS()->getBitsForPOC();
+        Int curPoc = rpcPic->getPicSym()->getSlice(0)->getPOC();
+        Int refPoc = pReferencePictureSet->getPOC(i);
+        if (!pReferencePictureSet->getCheckLTMSBPresent(i))
+        {
+          curPoc = curPoc % pocCycle;
+          refPoc = refPoc % pocCycle;
+        }
+        
+        if (rpcPic->getSlice(0)->isReferenced() && curPoc == refPoc)
         {
           isAvailable = 1;
@@ -1224,5 +1364,4 @@
   for(i=0;i<pReferencePictureSet->getNumberOfNegativePictures()+pReferencePictureSet->getNumberOfPositivePictures();i++)
   {
-    j = 0;
     isAvailable = 0;
     // loop through all pictures in the reference picture buffer
@@ -1230,5 +1369,4 @@
     while ( iterPic != rcListPic.end())
     {
-      j++;
       rpcPic = *(iterPic++);
 
@@ -1247,5 +1385,7 @@
         {
           if(printErrors)
+          {
             printf("\nShort-term reference picture with POC = %3d seems to have been removed or not correctly decoded.", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          }
           atLeastOneRemoved = 1;
         }
@@ -1253,5 +1393,7 @@
         {
           if(printErrors)
+          {
             printf("\nShort-term reference picture with POC = %3d is lost or not correctly decoded!", this->getPOC() + pReferencePictureSet->getDeltaPOC(i));
+          }
           atLeastOneLost = 1;
           iPocLost=this->getPOC() + pReferencePictureSet->getDeltaPOC(i);
@@ -1399,5 +1541,5 @@
  * \returns Void
  */
-Void  TComSlice::resetWpScaling(wpScalingParam  wp[2][MAX_NUM_REF][3])
+Void  TComSlice::resetWpScaling()
 {
   for ( Int e=0 ; e<2 ; e++ )
@@ -1407,5 +1549,5 @@
       for ( Int yuv=0 ; yuv<3 ; yuv++ )
       {
-        wpScalingParam  *pwp = &(wp[e][i][yuv]);
+        wpScalingParam  *pwp = &(m_weightPredTable[e][i][yuv]);
         pwp->bPresentFlag      = false;
         pwp->uiLog2WeightDenom = 0;
@@ -1423,13 +1565,4 @@
 Void  TComSlice::initWpScaling()
 {
-  initWpScaling(m_weightPredTable);
-}
-
-/** set WP tables 
- * \param wpScalingParam
- * \returns Void
- */
-Void  TComSlice::initWpScaling(wpScalingParam  wp[2][MAX_NUM_REF][3])
-{
   for ( Int e=0 ; e<2 ; e++ )
   {
@@ -1438,6 +1571,7 @@
       for ( Int yuv=0 ; yuv<3 ; yuv++ )
       {
-        wpScalingParam  *pwp = &(wp[e][i][yuv]);
-        if ( !pwp->bPresentFlag ) {
+        wpScalingParam  *pwp = &(m_weightPredTable[e][i][yuv]);
+        if ( !pwp->bPresentFlag ) 
+        {
           // Inferring values not present :
           pwp->iWeight = (1 << pwp->uiLog2WeightDenom);
@@ -1482,5 +1616,9 @@
   {
     m_numReorderPics[i] = 0;
+#if L0323_DPB
+    m_uiMaxDecPicBuffering[i] = 1; 
+#else
     m_uiMaxDecPicBuffering[i] = 0; 
+#endif
     m_uiMaxLatencyIncrease[i] = 0;
   }
@@ -1516,7 +1654,7 @@
 TComVPS::~TComVPS()
 {
-  if( m_hrdParameters    != NULL )     delete m_hrdParameters;
-  if( m_hrdOpSetIdx      != NULL )     delete m_hrdOpSetIdx;
-  if( m_cprmsPresentFlag != NULL )     delete m_cprmsPresentFlag;
+  if( m_hrdParameters    != NULL )     delete[] m_hrdParameters;
+  if( m_hrdOpSetIdx      != NULL )     delete[] m_hrdOpSetIdx;
+  if( m_cprmsPresentFlag != NULL )     delete[] m_cprmsPresentFlag;
 }
 
@@ -1533,9 +1671,9 @@
 , m_picWidthInLumaSamples     (352)
 , m_picHeightInLumaSamples    (288)
+, m_log2MinCodingBlockSize    (  0)
+, m_log2DiffMaxMinCodingBlockSize (0)
 , m_uiMaxCUWidth              ( 32)
 , m_uiMaxCUHeight             ( 32)
 , m_uiMaxCUDepth              (  3)
-, m_uiMinTrDepth              (  0)
-, m_uiMaxTrDepth              (  1)
 , m_bLongTermRefsPresent      (false)
 , m_uiQuadtreeTULog2MaxSize   (  0)
@@ -1547,5 +1685,7 @@
 , m_pcmLog2MaxSize            (  5)
 , m_uiPCMLog2MinSize          (  7)
+#if !L0034_COMBINED_LIST_CLEANUP
 , m_bUseLComb                 (false)
+#endif
 , m_bitDepthY                 (  8)
 , m_bitDepthC                 (  8)
@@ -1572,5 +1712,9 @@
   {
     m_uiMaxLatencyIncrease[i] = 0;
+#if L0323_DPB
+    m_uiMaxDecPicBuffering[i] = 1;
+#else
     m_uiMaxDecPicBuffering[i] = 0;
+#endif
     m_numReorderPics[i]       = 0;
   }
@@ -1591,4 +1735,5 @@
   m_RPSList.create(numRPS);
 }
+
 Void TComSPS::setHrdParameters( UInt frameRate, UInt numDU, UInt bitRate, Bool randomAccess )
 {
@@ -1835,12 +1980,15 @@
   return m_POC[bufferNum];
 }
+
 Void TComReferencePictureSet::setPOC(Int bufferNum, Int POC)
 {
   m_POC[bufferNum] = POC;
 }
+
 Bool TComReferencePictureSet::getCheckLTMSBPresent(Int bufferNum)
 {
   return m_bCheckLTMSB[bufferNum];
 }
+
 Void TComReferencePictureSet::setCheckLTMSBPresent(Int bufferNum, Bool b)
 {
@@ -2022,4 +2170,5 @@
   return (defaultCounter == (SCALING_LIST_NUM * SCALING_LIST_SIZE_NUM - 4)) ? false : true; // -4 for 32x32
 }
+
 /** get scaling matrix from RefMatrixID
  * \param sizeId size index
@@ -2031,4 +2180,5 @@
   ::memcpy(getScalingListAddress(sizeId, listId),((listId == refListId)? getScalingListDefaultAddress(sizeId, refListId): getScalingListAddress(sizeId, refListId)),sizeof(Int)*min(MAX_MATRIX_COEF_NUM,(Int)g_scalingListSize[sizeId]));
 }
+
 /** parse syntax infomation 
  *  \param pchFile syntax infomation
@@ -2123,4 +2273,5 @@
   m_scalingListCoef[SCALING_LIST_32x32][3] = m_scalingListCoef[SCALING_LIST_32x32][1]; // copy address for 32x32
 }
+
 /** destroy quantization matrix array
  */
@@ -2135,4 +2286,5 @@
   }
 }
+
 /** get default address of quantization matrix 
  * \param sizeId size index
@@ -2164,4 +2316,5 @@
   return src;
 }
+
 /** process of default matrix
  * \param sizeId size index
@@ -2173,4 +2326,5 @@
   setScalingListDC(sizeId,listId,SCALING_LIST_DC);
 }
+
 /** check DC value of matrix for default matrix signaling
  */
@@ -2240,5 +2394,5 @@
 //! activate a PPS and depending on isIDR parameter also SPS and VPS
 //! \returns true, if activation is successful
-Bool ParameterSetManager::activatePPS(Int ppsId, Bool isIDR)
+Bool ParameterSetManager::activatePPS(Int ppsId, Bool isIRAP)
 {
   TComPPS *pps = m_ppsMap.getPS(ppsId);
@@ -2246,7 +2400,7 @@
   {
     Int spsId = pps->getSPSId();
-    if (!isIDR && (spsId != m_activeSPSId))
-    {
-      printf("Warning: tried to activate PPS referring to a inactive SPS at non-IDR.");
+    if (!isIRAP && (spsId != m_activeSPSId))
+    {
+      printf("Warning: tried to activate PPS referring to a inactive SPS at non-IRAP.");
       return false;
     }
@@ -2255,7 +2409,7 @@
     {
       Int vpsId = sps->getVPSId();
-      if (!isIDR && (vpsId != m_activeVPSId))
-      {
-        printf("Warning: tried to activate PPS referring to a inactive VPS at non-IDR.");
+      if (!isIRAP && (vpsId != m_activeVPSId))
+      {
+        printf("Warning: tried to activate PPS referring to a inactive VPS at non-IRAP.");
         return false;
       }
@@ -2403,5 +2557,5 @@
     assert(iRefPicNum == 1);
 #if RAP_MFM_INIT
-    if(!(getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA && getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA) && getSPS()->getMFMEnabledFlag())
+    if(!(getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA_W_LP && getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA) && getSPS()->getMFMEnabledFlag())
 #else
     if( getPOC() != 0 )
Index: branches/SHM-2.0-dev/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibCommon/TComSlice.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibCommon/TComSlice.h	(revision 133)
@@ -908,11 +908,12 @@
   UInt        m_picHeightInLumaSamples;
   
-  Window      m_conformanceWindow;
-
+  Int         m_log2MinCodingBlockSize;
+  Int         m_log2DiffMaxMinCodingBlockSize;
   UInt        m_uiMaxCUWidth;
   UInt        m_uiMaxCUHeight;
   UInt        m_uiMaxCUDepth;
-  UInt        m_uiMinTrDepth;
-  UInt        m_uiMaxTrDepth;
+
+  Window      m_conformanceWindow;
+
   TComRPSList m_RPSList;
   Bool        m_bLongTermRefsPresent;
@@ -930,5 +931,7 @@
   Bool        m_useAMP;
 
+#if !L0034_COMBINED_LIST_CLEANUP
   Bool        m_bUseLComb;
+#endif
   
   // Parameter
@@ -1009,4 +1012,10 @@
   Bool getUsedByCurrPicLtSPSFlag(Int i)        {return m_usedByCurrPicLtSPSFlag[i];}
   Void setUsedByCurrPicLtSPSFlag(Int i, Bool x)      { m_usedByCurrPicLtSPSFlag[i] = x;}
+
+  Int  getLog2MinCodingBlockSize() const           { return m_log2MinCodingBlockSize; }
+  Void setLog2MinCodingBlockSize(Int val)          { m_log2MinCodingBlockSize = val; }
+  Int  getLog2DiffMaxMinCodingBlockSize() const    { return m_log2DiffMaxMinCodingBlockSize; }
+  Void setLog2DiffMaxMinCodingBlockSize(Int val)   { m_log2DiffMaxMinCodingBlockSize = val; }
+
   Void setMaxCUWidth  ( UInt u ) { m_uiMaxCUWidth = u;      }
   UInt getMaxCUWidth  ()         { return  m_uiMaxCUWidth;  }
@@ -1025,8 +1034,4 @@
   Bool getUseAMP() { return m_useAMP; }
   Void setUseAMP( Bool b ) { m_useAMP = b; }
-  Void setMinTrDepth  ( UInt u ) { m_uiMinTrDepth = u;      }
-  UInt getMinTrDepth  ()         { return  m_uiMinTrDepth;  }
-  Void setMaxTrDepth  ( UInt u ) { m_uiMaxTrDepth = u;      }
-  UInt getMaxTrDepth  ()         { return  m_uiMaxTrDepth;  }
   Void setQuadtreeTULog2MaxSize( UInt u ) { m_uiQuadtreeTULog2MaxSize = u;    }
   UInt getQuadtreeTULog2MaxSize()         { return m_uiQuadtreeTULog2MaxSize; }
@@ -1050,6 +1055,8 @@
   
   // Tool list
+#if !L0034_COMBINED_LIST_CLEANUP
   Void setUseLComb    (Bool b)   { m_bUseLComb = b;         }
   Bool getUseLComb    ()         { return m_bUseLComb;      }
+#endif
 
   Bool getUseLossless ()         { return m_useLossless; }
@@ -1370,11 +1377,12 @@
   Int         m_deblockingFilterBetaOffsetDiv2;    //< beta offset for deblocking filter
   Int         m_deblockingFilterTcOffsetDiv2;      //< tc offset for deblocking filter
-  
-  Int         m_aiNumRefIdx   [3];    //  for multiple reference of current slice
-
 #if REF_LIST_BUGFIX
   Int         m_aiNumILRRefIdx;       //< for inter-layer reference picture ser
 #endif
-
+#if L0034_COMBINED_LIST_CLEANUP
+  Int         m_list1IdxToList0Idx[MAX_NUM_REF];
+  Int         m_aiNumRefIdx   [2];    //  for multiple reference of current slice
+#else
+  Int         m_aiNumRefIdx   [3];    //  for multiple reference of current slice
   Int         m_iRefIdxOfLC[2][MAX_NUM_REF_LC];
   Int         m_eListIdFromIdxOfLC[MAX_NUM_REF_LC];
@@ -1384,4 +1392,5 @@
   Bool        m_bRefPicListModificationFlagLC;
   Bool        m_bRefPicListCombinationFlag;
+#endif
 
   Bool        m_bCheckLDC;
@@ -1421,6 +1430,7 @@
 
   Bool        m_abEqualRef  [2][MAX_NUM_REF][MAX_NUM_REF];
-  
+#if !L0034_COMBINED_LIST_CLEANUP
   Bool        m_bNoBackPredFlag;
+#endif
   UInt        m_uiTLayer;
 #if SVC_EXTENSION
@@ -1533,4 +1543,7 @@
   Bool      getMvdL1ZeroFlag ()                                  { return m_bLMvdL1Zero;    }
   Int       getNumRpsCurrTempList();
+#if L0034_COMBINED_LIST_CLEANUP
+  Int       getList1IdxToList0Idx ( Int list1Idx )               { return m_list1IdxToList0Idx[list1Idx]; }
+#else
   Int       getRefIdxOfLC       (RefPicList e, Int iRefIdx)     { return m_iRefIdxOfLC[e][iRefIdx];           }
   Int       getListIdFromIdxOfLC(Int iRefIdx)                   { return m_eListIdFromIdxOfLC[iRefIdx];       }
@@ -1542,12 +1555,14 @@
   Bool      getRefPicListCombinationFlag()                      {return m_bRefPicListCombinationFlag;}
   Void      setRefPicListCombinationFlag(Bool bflag)            {m_bRefPicListCombinationFlag=bflag;}   
+#endif
   Void      setReferenced(Bool b)                               { m_bRefenced = b; }
   Bool      isReferenced()                                      { return m_bRefenced; }
   Void      setPOC              ( Int i )                       { m_iPOC              = i; if(getTLayer()==0) m_prevPOC=i; }
   Void      setNalUnitType      ( NalUnitType e )               { m_eNalUnitType      = e;      }
-  NalUnitType getNalUnitType    ()                              { return m_eNalUnitType;        }
+  NalUnitType getNalUnitType    () const                        { return m_eNalUnitType;        }
   Bool      getRapPicFlag       ();  
-  Bool      getIdrPicFlag       ()                              { return getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP; }
-  Void      checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, Bool& prevRAPisBLA);
+  Bool      getIdrPicFlag       ()                              { return getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP; }
+  Bool      isIRAP              () const                        { return (getNalUnitType() >= 16) && (getNalUnitType() <= 23); }  
+  Void      checkCRA(TComReferencePictureSet *pReferencePictureSet, Int& pocCRA, Bool& prevRAPisBLA, TComList<TComPic *>& rcListPic);
   Void      decodingRefreshMarking(Int& pocCRA, Bool& bRefreshPending, TComList<TComPic*>& rcListPic);
   Void      setSliceType        ( SliceType e )                 { m_eSliceType        = e;      }
@@ -1590,5 +1605,9 @@
 #endif
 
+#if FIX1071
+  Void      setRefPicList       ( TComList<TComPic*>& rcListPic, Bool checkNumPocTotalCurr = false );
+#else
   Void      setRefPicList       ( TComList<TComPic*>& rcListPic );
+#endif
   Void      setRefPOCList       ();
   Void      setColFromL0Flag    ( UInt colFromL0 ) { m_colFromL0Flag = colFromL0; }
@@ -1628,8 +1647,11 @@
   
   static Void      sortPicList         ( TComList<TComPic*>& rcListPic );
-  
+#if L0034_COMBINED_LIST_CLEANUP
+  Void setList1IdxToList0Idx();
+#else
   Bool getNoBackPredFlag() { return m_bNoBackPredFlag; }
   Void setNoBackPredFlag( Bool b ) { m_bNoBackPredFlag = b; }
   Void generateCombinedList       ();
+#endif
 
   UInt getTLayer             ()                            { return m_uiTLayer;                      }
@@ -1679,6 +1701,5 @@
   Void  getWpScaling    ( RefPicList e, Int iRefIdx, wpScalingParam *&wp);
 
-  Void  resetWpScaling  (wpScalingParam  wp[2][MAX_NUM_REF][3]);
-  Void  initWpScaling    (wpScalingParam  wp[2][MAX_NUM_REF][3]);
+  Void  resetWpScaling  ();
   Void  initWpScaling   ();
   inline Bool applyWP   () { return( (m_eSliceType==P_SLICE && m_pcPPS->getUseWP()) || (m_eSliceType==B_SLICE && m_pcPPS->getWPBiPred()) ); }
@@ -1720,6 +1741,5 @@
   TComPic*  xGetRefPic  (TComList<TComPic*>& rcListPic,
                          Int                 poc);
-  TComPic*  xGetLongTermRefPic  (TComList<TComPic*>& rcListPic,
-                         Int                 poc);
+  TComPic*  xGetLongTermRefPic(TComList<TComPic*>& rcListPic, Int poc, Bool pocHasMsb);
 };// END CLASS DEFINITION TComSlice
 
@@ -1805,5 +1825,5 @@
   //! activate a PPS and depending on isIDR parameter also SPS and VPS
   //! \returns true, if activation is successful
-  Bool activatePPS(Int ppsId, Bool isIDR);
+  Bool activatePPS(Int ppsId, Bool isIRAP);
 
   TComVPS* getActiveVPS(){ return m_vpsMap.getPS(m_activeVPSId); };
Index: branches/SHM-2.0-dev/source/Lib/TLibCommon/TComTrQuant.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 133)
@@ -2007,5 +2007,5 @@
           }
           
-          if(piQCoef[minPos] == 32767 || piQCoef[minPos] == -32768)
+          if(piDstCoeff[minPos] == 32767 || piDstCoeff[minPos] == -32768)
           {
             finalChange = -1;
Index: branches/SHM-2.0-dev/source/Lib/TLibCommon/TypeDef.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibCommon/TypeDef.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibCommon/TypeDef.h	(revision 133)
@@ -65,5 +65,5 @@
 
 #define AVC_BASE                         0      ///< YUV BL reading for AVC base SVC
-#define REF_IDX_FRAMEWORK                0      ///< inter-layer reference framework
+#define REF_IDX_FRAMEWORK                1      ///< inter-layer reference framework
 
 #if SVC_UPSAMPLING
@@ -114,4 +114,15 @@
 //! \ingroup TLibCommon
 //! \{
+
+#define FIX1071 1 ///< Temporary fix for issue #1071
+
+#define L0208_SOP_DESCRIPTION_SEI     1 ///< L0208: add SOP descrioption SEI
+#define MAX_NUM_PICS_IN_SOP           1024
+
+#define K0180_SCALABLE_NESTING_SEI  1   ///JCTVC-K0180 scalable nesting sei message
+#define MAX_NESTING_NUM_OPS         1024
+#define MAX_NESTING_NUM_LAYER       64
+
+#define J0149_TONE_MAPPING_SEI        1 ///< J0149: Tone mapping information SEI
 #define L0363_DU_BIT_RATE             1 ///< L0363: add bit_rate_du_value_minus1 to HRD parameters
 #define L0328_SPLICING                1 ///< L0328: splicing support in HRD
@@ -138,4 +149,8 @@
 #define SIGNAL_BITRATE_PICRATE_IN_VPS               0  ///< K0125: Signal bit_rate and pic_rate in VPS
 #define L0232_RD_PENALTY           1  ///< L0232: RD-penalty for 32x32 TU for intra in non-intra slices
+#define L0386_DB_METRIC            1  ///< L0386: non-normative blockiness metric (automatically configures deblocking parameters in bitstream)
+#define L0323_DPB                     1 ///< L0323: Specification of active reference indices and decoded picture buffer
+
+#define L0034_COMBINED_LIST_CLEANUP 1
 
 #if VPS_EXTN_MASK_AND_DIM_INFO
@@ -477,5 +492,7 @@
   REF_PIC_LIST_0 = 0,   ///< reference list 0
   REF_PIC_LIST_1 = 1,   ///< reference list 1
+#if !L0034_COMBINED_LIST_CLEANUP
   REF_PIC_LIST_C = 2,   ///< combined reference list for uni-prediction in B-Slices
+#endif
   REF_PIC_LIST_X = 100  ///< special mark
 };
Index: branches/SHM-2.0-dev/source/Lib/TLibDecoder/NALread.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibDecoder/NALread.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibDecoder/NALread.cpp	(revision 133)
@@ -50,14 +50,18 @@
 //! \ingroup TLibDecoder
 //! \{
-static void convertPayloadToRBSP(vector<uint8_t>& nalUnitBuf, Bool isVclNalUnit)
+static void convertPayloadToRBSP(vector<uint8_t>& nalUnitBuf, TComInputBitstream *bitstream, Bool isVclNalUnit)
 {
   UInt zeroCount = 0;
   vector<uint8_t>::iterator it_read, it_write;
 
-  for (it_read = it_write = nalUnitBuf.begin(); it_read != nalUnitBuf.end(); it_read++, it_write++)
+  UInt pos = 0;
+  bitstream->clearEmulationPreventionByteLocation();
+  for (it_read = it_write = nalUnitBuf.begin(); it_read != nalUnitBuf.end(); it_read++, it_write++, pos++)
   {
     assert(zeroCount < 2 || *it_read >= 0x03);
     if (zeroCount == 2 && *it_read == 0x03)
     {
+      bitstream->pushEmulationPreventionByteLocation( pos );
+      pos++;
       it_read++;
       zeroCount = 0;
@@ -109,8 +113,8 @@
   if ( nalu.m_temporalId )
   {
-    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA
-         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLANT
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA_W_LP
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA_W_RADL
          && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_BLA_N_LP
-         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR
+         && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR_W_RADL
          && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_IDR_N_LP
          && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_CRA
@@ -122,5 +126,5 @@
   else
   {
-    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TLA
+    assert( nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TLA_R
          && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_TSA_N
          && nalu.m_nalUnitType != NAL_UNIT_CODED_SLICE_STSA_R
@@ -136,7 +140,8 @@
   /* perform anti-emulation prevention */
   TComInputBitstream *pcBitstream = new TComInputBitstream(NULL);
-  convertPayloadToRBSP(nalUnitBuf, (nalUnitBuf[0] & 64) == 0);
+  convertPayloadToRBSP(nalUnitBuf, pcBitstream, (nalUnitBuf[0] & 64) == 0);
   
   nalu.m_Bitstream = new TComInputBitstream(&nalUnitBuf);
+  nalu.m_Bitstream->setEmulationPreventionByteLocation(pcBitstream->getEmulationPreventionByteLocation());
   delete pcBitstream;
   readNalUnitHeader(nalu);
Index: branches/SHM-2.0-dev/source/Lib/TLibDecoder/SEIread.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibDecoder/SEIread.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibDecoder/SEIread.cpp	(revision 133)
@@ -90,4 +90,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");
@@ -154,5 +169,5 @@
   SEI *sei = NULL;
 
-  if(nalUnitType == NAL_UNIT_SEI)
+  if(nalUnitType == NAL_UNIT_PREFIX_SEI)
   {
     switch (payloadType)
@@ -219,4 +234,22 @@
       xParseSEIGradualDecodingRefreshInfo((SEIGradualDecodingRefreshInfo&) *sei, payloadSize);
       break;
+#if J0149_TONE_MAPPING_SEI
+    case SEI::TONE_MAPPING_INFO:
+      sei = new SEIToneMappingInfo;
+      xParseSEIToneMappingInfo((SEIToneMappingInfo&) *sei, payloadSize);
+      break;
+#endif
+#if L0208_SOP_DESCRIPTION_SEI
+    case SEI::SOP_DESCRIPTION:
+      sei = new SEISOPDescription;
+      xParseSEISOPDescription((SEISOPDescription&) *sei, payloadSize);
+      break;
+#endif
+#if K0180_SCALABLE_NESTING_SEI
+    case SEI::SCALABLE_NESTING:
+      sei = new SEIScalableNesting;
+      xParseSEIScalableNesting((SEIScalableNesting&) *sei, nalUnitType, payloadSize, sps);
+      break;
+#endif
     default:
       for (UInt i = 0; i < payloadSize; i++)
@@ -284,10 +317,13 @@
     {
       UInt reservedPayloadExtensionData;
-      READ_CODE (1, reservedPayloadExtensionData, "reserved_payload_extension_data");
+      READ_FLAG (reservedPayloadExtensionData, "reserved_payload_extension_data");
     }
 
     UInt dummy;
-    READ_CODE (1, dummy, "payload_bit_equal_to_one");
-    READ_CODE (payloadBitsRemaining-1, dummy, "payload_bit_equal_to_zero");
+    READ_FLAG (dummy, "payload_bit_equal_to_one"); payloadBitsRemaining--;
+    while (payloadBitsRemaining)
+    {
+      READ_FLAG (dummy, "payload_bit_equal_to_zero"); payloadBitsRemaining--;
+    }
   }
 
@@ -632,4 +668,162 @@
 }
 
+#if J0149_TONE_MAPPING_SEI
+Void SEIReader::xParseSEIToneMappingInfo(SEIToneMappingInfo& sei, UInt /*payloadSize*/)
+{
+  Int i;
+  UInt val;
+  READ_UVLC( val, "tone_map_id" );                         sei.m_toneMapId = val;
+  READ_FLAG( val, "tone_map_cancel_flag" );                sei.m_toneMapCancelFlag = val;
+
+  if ( !sei.m_toneMapCancelFlag )
+  {
+    READ_FLAG( val, "tone_map_persistence_flag" );         sei.m_toneMapPersistenceFlag = val; 
+    READ_CODE( 8, val, "coded_data_bit_depth" );           sei.m_codedDataBitDepth = val;
+    READ_CODE( 8, val, "target_bit_depth" );               sei.m_targetBitDepth = val;
+    READ_UVLC( val, "model_id" );                          sei.m_modelId = val; 
+    switch(sei.m_modelId)
+    {
+    case 0:
+      {
+        READ_CODE( 32, val, "min_value" );                 sei.m_minValue = val;
+        READ_CODE( 32, val, "max_value" );                 sei.m_maxValue = val;
+        break;
+      }
+    case 1:
+      {
+        READ_CODE( 32, val, "sigmoid_midpoint" );          sei.m_sigmoidMidpoint = val;
+        READ_CODE( 32, val, "sigmoid_width" );             sei.m_sigmoidWidth = val;
+        break;
+      }
+    case 2:
+      {
+        UInt num = 1u << sei.m_targetBitDepth;
+        sei.m_startOfCodedInterval.resize(num+1);
+        for(i = 0; i < num; i++)
+        {
+          READ_CODE( ((( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3), val, "start_of_coded_interval" );
+          sei.m_startOfCodedInterval[i] = val;
+        }
+        sei.m_startOfCodedInterval[num] = 1u << sei.m_codedDataBitDepth;
+        break;
+      }
+    case 3:
+      {
+        READ_CODE( 16, val,  "num_pivots" );                       sei.m_numPivots = val;
+        sei.m_codedPivotValue.resize(sei.m_numPivots);
+        sei.m_targetPivotValue.resize(sei.m_numPivots);
+        for(i = 0; i < sei.m_numPivots; i++ )
+        {
+          READ_CODE( ((( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3), val, "coded_pivot_value" );
+          sei.m_codedPivotValue[i] = val;
+          READ_CODE( ((( sei.m_targetBitDepth + 7 ) >> 3 ) << 3),    val, "target_pivot_value" );
+          sei.m_targetPivotValue[i] = val;
+        }
+        break;
+      }
+    case 4:
+      {
+        READ_CODE( 8, val, "camera_iso_speed_idc" );                     sei.m_cameraIsoSpeedValue = val;
+        if( sei.m_cameraIsoSpeedValue == 255) //Extended_ISO
+        {
+          READ_CODE( 32,   val,   "camera_iso_speed_value" );            sei.m_cameraIsoSpeedValue = val;
+        }
+        READ_FLAG( val, "exposure_compensation_value_sign_flag" );       sei.m_exposureCompensationValueSignFlag = val;
+        READ_CODE( 16, val, "exposure_compensation_value_numerator" );   sei.m_exposureCompensationValueNumerator = val;
+        READ_CODE( 16, val, "exposure_compensation_value_denom_idc" );   sei.m_exposureCompensationValueDenomIdc = val;
+        READ_CODE( 32, val, "ref_screen_luminance_white" );              sei.m_refScreenLuminanceWhite = val;
+        READ_CODE( 32, val, "extended_range_white_level" );              sei.m_extendedRangeWhiteLevel = val;
+        READ_CODE( 16, val, "nominal_black_level_luma_code_value" );     sei.m_nominalBlackLevelLumaCodeValue = val;
+        READ_CODE( 16, val, "nominal_white_level_luma_code_value" );     sei.m_nominalWhiteLevelLumaCodeValue= val;
+        READ_CODE( 16, val, "extended_white_level_luma_code_value" );    sei.m_extendedWhiteLevelLumaCodeValue = val;
+        break;
+      }
+    default:
+      {
+        assert(!"Undefined SEIToneMapModelId");
+        break;
+      }
+    }//switch model id
+  }// if(!sei.m_toneMapCancelFlag) 
+
+  xParseByteAlign();
+}
+#endif
+
+#if L0208_SOP_DESCRIPTION_SEI
+Void SEIReader::xParseSEISOPDescription(SEISOPDescription &sei, UInt payloadSize)
+{
+  Int iCode;
+  UInt uiCode;
+
+  READ_UVLC( uiCode,           "sop_seq_parameter_set_id"            ); sei.m_sopSeqParameterSetId = uiCode;
+  READ_UVLC( uiCode,           "num_pics_in_sop_minus1"              ); sei.m_numPicsInSopMinus1 = uiCode;
+  for (UInt i = 0; i <= sei.m_numPicsInSopMinus1; i++)
+  {
+    READ_CODE( 6, uiCode,                     "sop_desc_vcl_nalu_type" );  sei.m_sopDescVclNaluType[i] = uiCode;
+    READ_CODE( 3, sei.m_sopDescTemporalId[i], "sop_desc_temporal_id"   );  sei.m_sopDescTemporalId[i] = uiCode;
+    if (sei.m_sopDescVclNaluType[i] != NAL_UNIT_CODED_SLICE_IDR_W_RADL && sei.m_sopDescVclNaluType[i] != NAL_UNIT_CODED_SLICE_IDR_N_LP)
+    {
+      READ_UVLC( sei.m_sopDescStRpsIdx[i],    "sop_desc_st_rps_idx"    ); sei.m_sopDescStRpsIdx[i] = uiCode;
+    }
+    if (i > 0)
+    {
+      READ_SVLC( iCode,                       "sop_desc_poc_delta"     ); sei.m_sopDescPocDelta[i] = iCode;
+    }
+  }
+
+  xParseByteAlign();
+}
+#endif
+
+#if K0180_SCALABLE_NESTING_SEI
+Void SEIReader::xParseSEIScalableNesting(SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, TComSPS *sps)
+{
+  UInt uiCode;
+  SEIMessages seis;
+
+  READ_FLAG( uiCode,            "bitstream_subset_flag"         ); sei.m_bitStreamSubsetFlag = uiCode;
+  READ_FLAG( uiCode,            "nesting_op_flag"               ); sei.m_nestingOpFlag = uiCode;
+  if (sei.m_nestingOpFlag)
+  {
+    READ_FLAG( uiCode,            "default_op_flag"               ); sei.m_defaultOpFlag = uiCode;
+    READ_UVLC( uiCode,            "nesting_num_ops_minus1"        ); sei.m_nestingNumOpsMinus1 = uiCode;
+    for (UInt i = sei.m_defaultOpFlag; i <= sei.m_nestingNumOpsMinus1; i++)
+    {
+      READ_CODE( 3,        uiCode,  "nesting_max_temporal_id_plus1"   ); sei.m_nestingMaxTemporalIdPlus1[i] = uiCode;
+      READ_UVLC( uiCode,            "nesting_op_idx"                  ); sei.m_nestingOpIdx[i] = uiCode;
+    }
+  }
+  else
+  {
+    READ_FLAG( uiCode,            "all_layers_flag"               ); sei.m_allLayersFlag       = uiCode;
+    if (!sei.m_allLayersFlag)
+    {
+      READ_CODE( 3,        uiCode,  "nesting_no_op_max_temporal_id_plus1"  ); sei.m_nestingNoOpMaxTemporalIdPlus1 = uiCode;
+      READ_UVLC( uiCode,            "nesting_num_layers_minus1"            ); sei.m_nestingNumLayersMinus1        = uiCode;
+      for (UInt i = 0; i <= sei.m_nestingNumLayersMinus1; i++)
+      {
+        READ_CODE( 6,           uiCode,     "nesting_layer_id"      ); sei.m_nestingLayerId[i]   = uiCode;
+      }
+    }
+  }
+
+  // byte alignment
+  while ( m_pcBitstream->getNumBitsRead() % 8 != 0 )
+  {
+    UInt code;
+    READ_FLAG( code, "nesting_zero_bit" );
+  }
+
+  sei.m_callerOwnsSEIs = false;
+
+  // read nested SEI messages
+  do {
+    xReadSEImessage(sei.m_nestedSEIs, nalUnitType, sps);
+  } while (m_pcBitstream->getNumBitsLeft() > 8);
+
+}
+#endif
+
 Void SEIReader::xParseByteAlign()
 {
Index: branches/SHM-2.0-dev/source/Lib/TLibDecoder/SEIread.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibDecoder/SEIread.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibDecoder/SEIread.h	(revision 133)
@@ -70,4 +70,13 @@
   Void xParseSEITemporalLevel0Index   (SEITemporalLevel0Index &sei, UInt payloadSize);
   Void xParseSEIGradualDecodingRefreshInfo (SEIGradualDecodingRefreshInfo &sei, UInt payloadSize);
+#if J0149_TONE_MAPPING_SEI
+  Void xParseSEIToneMappingInfo       (SEIToneMappingInfo& sei, UInt payloadSize);
+#endif
+#if L0208_SOP_DESCRIPTION_SEI
+  Void xParseSEISOPDescription        (SEISOPDescription &sei, UInt payloadSize);
+#endif
+#if K0180_SCALABLE_NESTING_SEI
+  Void xParseSEIScalableNesting       (SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, TComSPS *sps);
+#endif
   Void xParseByteAlign();
 };
Index: branches/SHM-2.0-dev/source/Lib/TLibDecoder/TDecCAVLC.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 133)
@@ -593,11 +593,9 @@
 
   READ_UVLC(     uiCode, "bit_depth_luma_minus8" );
-  g_bitDepthY = 8 + uiCode;
-  pcSPS->setBitDepthY(g_bitDepthY);
+  pcSPS->setBitDepthY( uiCode + 8 );
   pcSPS->setQpBDOffsetY( (Int) (6*uiCode) );
 
   READ_UVLC( uiCode,    "bit_depth_chroma_minus8" );
-  g_bitDepthC = 8 + uiCode;
-  pcSPS->setBitDepthC(g_bitDepthC);
+  pcSPS->setBitDepthC( uiCode + 8 );
   pcSPS->setQpBDOffsetC( (Int) (6*uiCode) );
 
@@ -608,6 +606,11 @@
   for(UInt i=0; i <= pcSPS->getMaxTLayers()-1; i++)
   {
+#if L0323_DPB
+    READ_UVLC ( uiCode, "sps_max_dec_pic_buffering_minus1");
+    pcSPS->setMaxDecPicBuffering( uiCode + 1, i);
+#else
     READ_UVLC ( uiCode, "sps_max_dec_pic_buffering");
     pcSPS->setMaxDecPicBuffering( uiCode, i);
+#endif
     READ_UVLC ( uiCode, "sps_num_reorder_pics" );
     pcSPS->setNumReorderPics(uiCode, i);
@@ -628,9 +631,11 @@
 
   READ_UVLC( uiCode, "log2_min_coding_block_size_minus3" );
-  UInt log2MinCUSize = uiCode + 3;
+  Int log2MinCUSize = uiCode + 3;
+  pcSPS->setLog2MinCodingBlockSize(log2MinCUSize);
   READ_UVLC( uiCode, "log2_diff_max_min_coding_block_size" );
-  UInt uiMaxCUDepthCorrect = uiCode;
-  pcSPS->setMaxCUWidth  ( 1<<(log2MinCUSize + uiMaxCUDepthCorrect) ); g_uiMaxCUWidth  = 1<<(log2MinCUSize + uiMaxCUDepthCorrect);
-  pcSPS->setMaxCUHeight ( 1<<(log2MinCUSize + uiMaxCUDepthCorrect) ); g_uiMaxCUHeight = 1<<(log2MinCUSize + uiMaxCUDepthCorrect);
+  pcSPS->setLog2DiffMaxMinCodingBlockSize(uiCode);
+  Int maxCUDepthDelta = uiCode;
+  pcSPS->setMaxCUWidth  ( 1<<(log2MinCUSize + maxCUDepthDelta) ); 
+  pcSPS->setMaxCUHeight ( 1<<(log2MinCUSize + maxCUDepthDelta) );
   READ_UVLC( uiCode, "log2_min_transform_block_size_minus2" );   pcSPS->setQuadtreeTULog2MinSize( uiCode + 2 );
 
@@ -640,14 +645,8 @@
   READ_UVLC( uiCode, "max_transform_hierarchy_depth_inter" );    pcSPS->setQuadtreeTUMaxDepthInter( uiCode+1 );
   READ_UVLC( uiCode, "max_transform_hierarchy_depth_intra" );    pcSPS->setQuadtreeTUMaxDepthIntra( uiCode+1 );
-  g_uiAddCUDepth = 0;
-  while( ( pcSPS->getMaxCUWidth() >> uiMaxCUDepthCorrect ) > ( 1 << ( pcSPS->getQuadtreeTULog2MinSize() + g_uiAddCUDepth )  ) )
-  {
-    g_uiAddCUDepth++;
-  }
-  pcSPS->setMaxCUDepth( uiMaxCUDepthCorrect+g_uiAddCUDepth  ); 
-  g_uiMaxCUDepth  = uiMaxCUDepthCorrect+g_uiAddCUDepth;
-  // BB: these parameters may be removed completly and replaced by the fixed values
-  pcSPS->setMinTrDepth( 0 );
-  pcSPS->setMaxTrDepth( 1 );
+
+  Int addCuDepth = max (0, log2MinCUSize - (Int)pcSPS->getQuadtreeTULog2MinSize() );
+  pcSPS->setMaxCUDepth( maxCUDepthDelta + addCuDepth ); 
+
   READ_FLAG( uiCode, "scaling_list_enabled_flag" );                 pcSPS->setScalingListFlag ( uiCode );
   if(pcSPS->getScalingListFlag())
@@ -746,5 +745,9 @@
   for(UInt i = 0; i <= pcVPS->getMaxTLayers()-1; i++)
   {
+#if L0323_DPB
+    READ_UVLC( uiCode,  "vps_max_dec_pic_buffering_minus1[i]" );     pcVPS->setMaxDecPicBuffering( uiCode + 1, i );
+#else
     READ_UVLC( uiCode,  "vps_max_dec_pic_buffering[i]" );     pcVPS->setMaxDecPicBuffering( uiCode, i );
+#endif
     READ_UVLC( uiCode,  "vps_num_reorder_pics[i]" );          pcVPS->setNumReorderPics( uiCode, i );
     READ_UVLC( uiCode,  "vps_max_latency_increase[i]" );      pcVPS->setMaxLatencyIncrease( uiCode, i );
@@ -1074,6 +1077,6 @@
         iPOCmsb = iPrevPOCmsb;
       }
-      if ( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
-        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT
+      if ( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
         || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
       {
@@ -1084,10 +1087,10 @@
 
       TComReferencePictureSet* rps;
+      rps = rpcSlice->getLocalRPS();
+      rpcSlice->setRPS(rps);
       READ_FLAG( uiCode, "short_term_ref_pic_set_sps_flag" );
       if(uiCode == 0) // use short-term reference picture set explicitly signalled in slice header
       {
-        rps = rpcSlice->getLocalRPS();
         parseShortTermRefPicSet(sps,rps, sps->getRPSList()->getNumberOfReferencePictureSets());
-        rpcSlice->setRPS(rps);
       }
       else // use reference to short-term reference picture set in PPS
@@ -1106,7 +1109,5 @@
           uiCode = 0;
         }
-        rpcSlice->setRPS(sps->getRPSList()->getReferencePictureSet(uiCode));
-
-        rps = rpcSlice->getRPS();
+        memcpy(rps,sps->getRPSList()->getReferencePictureSet(uiCode),sizeof(TComReferencePictureSet));
       }
       if(sps->getLongTermRefsPresent())
@@ -1131,5 +1132,5 @@
         rps->setNumberOfLongtermPictures(numOfLtrp);
         Int maxPicOrderCntLSB = 1 << rpcSlice->getSPS()->getBitsForPOC();
-        Int prevLSB = 0, prevDeltaMSB = 0, deltaPocMSBCycleLT = 0;;
+        Int prevDeltaMSB = 0, deltaPocMSBCycleLT = 0;;
         for(Int j=offset+rps->getNumberOfLongtermPictures()-1, k = 0; k < numOfLtrp; j--, k++)
         {
@@ -1158,6 +1159,6 @@
             READ_UVLC( uiCode, "delta_poc_msb_cycle_lt[i]" );
             Bool deltaFlag = false;
-            //            First LTRP                               || First LTRP from SH           || curr LSB    != prev LSB
-            if( (j == offset+rps->getNumberOfLongtermPictures()-1) || (j == offset+(numOfLtrp-numLtrpInSPS)-1) || (pocLsbLt != prevLSB) )
+            //            First LTRP                               || First LTRP from SH
+            if( (j == offset+rps->getNumberOfLongtermPictures()-1) || (j == offset+(numOfLtrp-numLtrpInSPS)-1) )
             {
               deltaFlag = true;
@@ -1184,5 +1185,4 @@
             rps->setCheckLTMSBPresent(j,false);  
           }
-          prevLSB = pocLsbLt;
           prevDeltaMSB = deltaPocMSBCycleLT;
         }
@@ -1190,6 +1190,6 @@
         rps->setNumberOfPictures(offset);        
       }  
-      if ( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
-        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT
+      if ( rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+        || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
         || rpcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP )
       {
@@ -1423,6 +1423,10 @@
         if(!rpcSlice->getDeblockingFilterDisable())
         {
-          READ_SVLC( iCode, "beta_offset_div2" );                       rpcSlice->setDeblockingFilterBetaOffsetDiv2(iCode);
-          READ_SVLC( iCode, "tc_offset_div2" );                         rpcSlice->setDeblockingFilterTcOffsetDiv2(iCode);
+          READ_SVLC( iCode, "slice_beta_offset_div2" );                       rpcSlice->setDeblockingFilterBetaOffsetDiv2(iCode);
+          assert(rpcSlice->getDeblockingFilterBetaOffsetDiv2() >= -6 &&
+                 rpcSlice->getDeblockingFilterBetaOffsetDiv2() <=  6);
+          READ_SVLC( iCode, "slice_tc_offset_div2" );                         rpcSlice->setDeblockingFilterTcOffsetDiv2(iCode);
+          assert(rpcSlice->getDeblockingFilterTcOffsetDiv2() >= -6 &&
+                 rpcSlice->getDeblockingFilterTcOffsetDiv2() <=  6);
         }
       }
@@ -1456,9 +1460,8 @@
   }
   
-  if( pps->getTilesEnabledFlag() || pps->getEntropyCodingSyncEnabledFlag() )
-  {
     UInt *entryPointOffset          = NULL;
     UInt numEntryPointOffsets, offsetLenMinus1;
-
+  if( pps->getTilesEnabledFlag() || pps->getEntropyCodingSyncEnabledFlag() )
+  {
     READ_UVLC(numEntryPointOffsets, "num_entry_point_offsets"); rpcSlice->setNumEntryPointOffsets ( numEntryPointOffsets );
     if (numEntryPointOffsets>0)
@@ -1477,4 +1480,43 @@
 #endif
     }
+  }
+  else
+  {
+    rpcSlice->setNumEntryPointOffsets ( 0 );
+  }
+
+  if(pps->getSliceHeaderExtensionPresentFlag())
+  {
+    READ_UVLC(uiCode,"slice_header_extension_length");
+    for(Int i=0; i<uiCode; i++)
+    {
+      UInt ignore;
+      READ_CODE(8,ignore,"slice_header_extension_data_byte");
+    }
+  }
+  m_pcBitstream->readByteAlignment();
+
+  if( pps->getTilesEnabledFlag() || pps->getEntropyCodingSyncEnabledFlag() )
+  {
+    Int endOfSliceHeaderLocation = m_pcBitstream->getByteLocation();
+    Int  curEntryPointOffset     = 0;
+    Int  prevEntryPointOffset    = 0;
+    for (UInt idx=0; idx<numEntryPointOffsets; idx++)
+    {
+      curEntryPointOffset += entryPointOffset[ idx ];
+
+      Int emulationPreventionByteCount = 0;
+      for ( UInt curByteIdx  = 0; curByteIdx<m_pcBitstream->numEmulationPreventionBytesRead(); curByteIdx++ )
+      {
+        if ( m_pcBitstream->getEmulationPreventionByteLocation( curByteIdx ) >= ( prevEntryPointOffset + endOfSliceHeaderLocation ) && 
+             m_pcBitstream->getEmulationPreventionByteLocation( curByteIdx ) <  ( curEntryPointOffset  + endOfSliceHeaderLocation ) )
+        {
+          emulationPreventionByteCount++;
+        }
+      }
+
+      entryPointOffset[ idx ] -= emulationPreventionByteCount;
+      prevEntryPointOffset = curEntryPointOffset;
+    }
 
     if ( pps->getTilesEnabledFlag() )
@@ -1512,19 +1554,5 @@
     }
   }
-  else
-  {
-    rpcSlice->setNumEntryPointOffsets ( 0 );
-  }
-
-  if(pps->getSliceHeaderExtensionPresentFlag())
-  {
-    READ_UVLC(uiCode,"slice_header_extension_length");
-    for(Int i=0; i<uiCode; i++)
-    {
-      UInt ignore;
-      READ_CODE(8,ignore,"slice_header_extension_data_byte");
-    }
-  }
-  m_pcBitstream->readByteAlignment();
+
   return;
 }
@@ -1771,112 +1799,4 @@
 // ====================================================================================================================
 
-
-/** Parse PCM alignment zero bits.
-* \returns Void
-*/
-Void TDecCavlc::xReadPCMAlignZero( )
-{
-  UInt uiNumberOfBits = m_pcBitstream->getNumBitsUntilByteAligned();
-
-  if(uiNumberOfBits)
-  {
-    UInt uiBits;
-    UInt uiSymbol;
-
-    for(uiBits = 0; uiBits < uiNumberOfBits; uiBits++)
-    {
-      xReadFlag( uiSymbol );
-      assert( uiSymbol == 0 );
-    }
-  }
-}
-
-Void TDecCavlc::xReadUnaryMaxSymbol( UInt& ruiSymbol, UInt uiMaxSymbol )
-{
-  if (uiMaxSymbol == 0)
-  {
-    ruiSymbol = 0;
-    return;
-  }
-
-  xReadFlag( ruiSymbol );
-
-  if (ruiSymbol == 0 || uiMaxSymbol == 1)
-  {
-    return;
-  }
-
-  UInt uiSymbol = 0;
-  UInt uiCont;
-
-  do
-  {
-    xReadFlag( uiCont );
-    uiSymbol++;
-  }
-  while( uiCont && (uiSymbol < uiMaxSymbol-1) );
-
-  if( uiCont && (uiSymbol == uiMaxSymbol-1) )
-  {
-    uiSymbol++;
-  }
-
-  ruiSymbol = uiSymbol;
-}
-
-Void TDecCavlc::xReadExGolombLevel( UInt& ruiSymbol )
-{
-  UInt uiSymbol ;
-  UInt uiCount = 0;
-  do
-  {
-    xReadFlag( uiSymbol );
-    uiCount++;
-  }
-  while( uiSymbol && (uiCount != 13));
-
-  ruiSymbol = uiCount-1;
-
-  if( uiSymbol )
-  {
-    xReadEpExGolomb( uiSymbol, 0 );
-    ruiSymbol += uiSymbol+1;
-  }
-
-  return;
-}
-
-Void TDecCavlc::xReadEpExGolomb( UInt& ruiSymbol, UInt uiCount )
-{
-  UInt uiSymbol = 0;
-  UInt uiBit = 1;
-
-
-  while( uiBit )
-  {
-    xReadFlag( uiBit );
-    uiSymbol += uiBit << uiCount++;
-  }
-
-  uiCount--;
-  while( uiCount-- )
-  {
-    xReadFlag( uiBit );
-    uiSymbol += uiBit << uiCount;
-  }
-
-  ruiSymbol = uiSymbol;
-
-  return;
-}
-
-UInt TDecCavlc::xGetBit()
-{
-  UInt ruiCode;
-  m_pcBitstream->read( 1, ruiCode );
-  return ruiCode;
-}
-
-
 /** parse explicit wp tables
 * \param TComSlice* pcSlice
@@ -1895,8 +1815,10 @@
   // decode delta_luma_log2_weight_denom :
   READ_UVLC( uiLog2WeightDenomLuma, "luma_log2_weight_denom" );     // ue(v): luma_log2_weight_denom
+  assert( uiLog2WeightDenomLuma <= 7 );
   if( bChroma ) 
   {
     READ_SVLC( iDeltaDenom, "delta_chroma_log2_weight_denom" );     // se(v): delta_chroma_log2_weight_denom
     assert((iDeltaDenom + (Int)uiLog2WeightDenomLuma)>=0);
+    assert((iDeltaDenom + (Int)uiLog2WeightDenomLuma)<=7);
     uiLog2WeightDenomChroma = (UInt)(iDeltaDenom + uiLog2WeightDenomLuma);
   }
@@ -1937,6 +1859,10 @@
         Int iDeltaWeight;
         READ_SVLC( iDeltaWeight, "delta_luma_weight_lX" );  // se(v): delta_luma_weight_l0[i]
+        assert( iDeltaWeight >= -128 );
+        assert( iDeltaWeight <=  127 );
         wp[0].iWeight = (iDeltaWeight + (1<<wp[0].uiLog2WeightDenom));
         READ_SVLC( wp[0].iOffset, "luma_offset_lX" );       // se(v): luma_offset_l0[i]
+        assert( wp[0].iOffset >= -128 );
+        assert( wp[0].iOffset <=  127 );
       }
       else 
@@ -1953,8 +1879,12 @@
             Int iDeltaWeight;
             READ_SVLC( iDeltaWeight, "delta_chroma_weight_lX" );  // se(v): chroma_weight_l0[i][j]
+            assert( iDeltaWeight >= -128 );
+            assert( iDeltaWeight <=  127 );
             wp[j].iWeight = (iDeltaWeight + (1<<wp[1].uiLog2WeightDenom));
 
             Int iDeltaChroma;
             READ_SVLC( iDeltaChroma, "delta_chroma_offset_lX" );  // se(v): delta_chroma_offset_l0[i][j]
+            assert( iDeltaChroma >= -512 );
+            assert( iDeltaChroma <=  511 );
             Int pred = ( 128 - ( ( 128*wp[j].iWeight)>>(wp[j].uiLog2WeightDenom) ) );
             wp[j].iOffset = Clip3(-128, 127, (iDeltaChroma + pred) );
Index: branches/SHM-2.0-dev/source/Lib/TLibDecoder/TDecCAVLC.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 133)
@@ -61,14 +61,5 @@
   
 protected:
-  Void  xReadEpExGolomb       ( UInt& ruiSymbol, UInt uiCount );
-  Void  xReadExGolombLevel    ( UInt& ruiSymbol );
-  Void  xReadUnaryMaxSymbol   ( UInt& ruiSymbol, UInt uiMaxSymbol );
-  
-  Void  xReadPCMAlignZero     ();
-
-  UInt  xGetBit             ();
-  
   void  parseShortTermRefPicSet            (TComSPS* pcSPS, TComReferencePictureSet* pcRPS, Int idx);
-private:
   
 public:
Index: branches/SHM-2.0-dev/source/Lib/TLibDecoder/TDecSlice.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibDecoder/TDecSlice.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibDecoder/TDecSlice.h	(revision 133)
@@ -91,4 +91,5 @@
   Void      initCtxMem(  UInt i );
   Void      setCtxMem( TDecSbac* sb, Int b )   { CTXMem[b] = sb; }
+  Int       getCtxMemSize( )                   { return (Int)CTXMem.size(); }
 #if SVC_EXTENSION
   TDecTop*  getLayerDec   ( UInt LayerId )  { return m_ppcTDecTop[LayerId]; }  
Index: branches/SHM-2.0-dev/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibDecoder/TDecTop.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibDecoder/TDecTop.cpp	(revision 133)
@@ -231,5 +231,9 @@
   }
 
+#if L0323_DPB
+  m_iMaxRefPicNum = pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getTLayer())+pcSlice->getSPS()->getNumReorderPics(pcSlice->getTLayer());     // m_uiMaxDecPicBuffering has the space for the picture currently being decoded
+#else
   m_iMaxRefPicNum = pcSlice->getSPS()->getMaxDecPicBuffering(pcSlice->getTLayer())+pcSlice->getSPS()->getNumReorderPics(pcSlice->getTLayer()) + 1; // +1 to have space for the picture currently being decoded
+#endif
   if (m_cListPic.size() < (UInt)m_iMaxRefPicNum)
   {
@@ -405,5 +409,5 @@
   assert (sps != 0);
 
-  if( false == m_parameterSetManagerDecoder[m_layerId].activatePPS(m_apcSlicePilot->getPPSId(), m_apcSlicePilot->getIdrPicFlag()) )
+  if( false == m_parameterSetManagerDecoder[m_layerId].activatePPS(m_apcSlicePilot->getPPSId(), m_apcSlicePilot->isIRAP()) )
 #else
   m_parameterSetManagerDecoder.applyPrefetchedPS();
@@ -415,9 +419,26 @@
   assert (sps != 0);
 
-  if (false == m_parameterSetManagerDecoder.activatePPS(m_apcSlicePilot->getPPSId(),m_apcSlicePilot->getIdrPicFlag()))
+  if (false == m_parameterSetManagerDecoder.activatePPS(m_apcSlicePilot->getPPSId(),m_apcSlicePilot->isIRAP()))
 #endif
   {
     printf ("Parameter set activation failed!");
     assert (0);
+  }
+
+  if( pps->getDependentSliceSegmentsEnabledFlag() )
+  {
+    Int NumCtx = pps->getEntropyCodingSyncEnabledFlag()?2:1;
+
+    if (m_cSliceDecoder.getCtxMemSize() != NumCtx)
+    {
+      m_cSliceDecoder.initCtxMem(NumCtx);
+      for ( UInt st = 0; st < NumCtx; st++ )
+      {
+        TDecSbac* ctx = NULL;
+        ctx = new TDecSbac;
+        ctx->init( &m_cBinCABAC );
+        m_cSliceDecoder.setCtxMem( ctx, st );
+      }
+    }
   }
 
@@ -428,10 +449,17 @@
   pps->setMinCuDQPSize( sps->getMaxCUWidth() >> ( pps->getMaxCuDQPDepth()) );
 
-  for (Int i = 0; i < sps->getMaxCUDepth() - g_uiAddCUDepth; i++)
+  g_bitDepthY     = sps->getBitDepthY();
+  g_bitDepthC     = sps->getBitDepthC();
+  g_uiMaxCUWidth  = sps->getMaxCUWidth();
+  g_uiMaxCUHeight = sps->getMaxCUHeight();
+  g_uiMaxCUDepth  = sps->getMaxCUDepth();
+  g_uiAddCUDepth  = max (0, sps->getLog2MinCodingBlockSize() - (Int)sps->getQuadtreeTULog2MinSize() );
+
+  for (Int i = 0; i < sps->getLog2DiffMaxMinCodingBlockSize(); i++)
   {
     sps->setAMPAcc( i, sps->getUseAMP() );
   }
 
-  for (Int i = sps->getMaxCUDepth() - g_uiAddCUDepth; i < sps->getMaxCUDepth(); i++)
+  for (Int i = sps->getLog2DiffMaxMinCodingBlockSize(); i < sps->getMaxCUDepth(); i++)
   {
     sps->setAMPAcc( i, 0 );
@@ -439,6 +467,6 @@
 
   m_cSAO.destroy();
-  m_cSAO.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), g_uiMaxCUWidth, g_uiMaxCUHeight );
-  m_cLoopFilter.        create( g_uiMaxCUDepth );
+  m_cSAO.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight() );
+  m_cLoopFilter.create( sps->getMaxCUDepth() );
 }
 
@@ -467,10 +495,11 @@
 
   m_apcSlicePilot->setNalUnitType(nalu.m_nalUnitType);
-  if((m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TRAIL_N) ||
-     (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N) ||
-     (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_STSA_N))
-  {
-    m_apcSlicePilot->setTemporalLayerNonReferenceFlag(true);
-  }
+  Bool nonReferenceFlag = (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TRAIL_N ||
+                           m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TSA_N   ||
+                           m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_STSA_N  ||
+                           m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N  ||
+                           m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N);
+  m_apcSlicePilot->setTemporalLayerNonReferenceFlag(nonReferenceFlag);
+  
   m_apcSlicePilot->setReferenced(true); // Putting this as true ensures that picture is referenced the first time it is in an RPS
   m_apcSlicePilot->setTLayerInfo(nalu.m_temporalId);
@@ -482,5 +511,4 @@
 #endif
   if (m_apcSlicePilot->isNextSlice())
-  {
     // Skip pictures due to random access
     if (isRandomAccessSkipPicture(iSkipFrame, iPOCLastDisplay))
@@ -493,5 +521,4 @@
       return false;
     }
-  } 
 
   // exit when a new picture is found
@@ -506,5 +533,11 @@
   }
 #else
-  if (m_apcSlicePilot->isNextSlice() && m_apcSlicePilot->getPOC()!=m_prevPOC && !m_bFirstSliceInSequence)
+  //we should only get a different poc for a new picture (with CTU address==0)
+  if (m_apcSlicePilot->isNextSlice() && m_apcSlicePilot->getPOC()!=m_prevPOC && !m_bFirstSliceInSequence && (!m_apcSlicePilot->getSliceCurStartCUAddr()==0))
+  {
+    printf ("Warning, the first slice of a picture might have been lost!\n");
+  }
+  // exit when a new picture is found
+  if (m_apcSlicePilot->isNextSlice() && (m_apcSlicePilot->getSliceCurStartCUAddr() == 0 && !m_bFirstSliceInPicture) && !m_bFirstSliceInSequence )
   {
     if (m_prevPOC >= m_pocRandomAccess)
@@ -732,11 +765,11 @@
   if (bNextSlice)
   {
-    pcSlice->checkCRA(pcSlice->getRPS(), m_pocCRA, m_prevRAPisBLA );
+    pcSlice->checkCRA(pcSlice->getRPS(), m_pocCRA, m_prevRAPisBLA, m_cListPic );
     // Set reference list
 #if REF_LIST_BUGFIX
     if (m_layerId == 0)
-    {
-      pcSlice->setRefPicList( m_cListPic );
-    }
+#endif
+#if FIX1071
+    pcSlice->setRefPicList( m_cListPic, true );
 #else
     pcSlice->setRefPicList( m_cListPic );
@@ -839,4 +872,5 @@
     //---------------
     pcSlice->setRefPOCList();
+#if !L0034_COMBINED_LIST_CLEANUP
     pcSlice->setNoBackPredFlag( false );
     if ( pcSlice->getSliceType() == B_SLICE )
@@ -855,4 +889,5 @@
       }
     }
+#endif
   }
 
@@ -947,5 +982,5 @@
 {
 #if SVC_EXTENSION
-  if(nalUnitType == NAL_UNIT_SEI_SUFFIX)
+  if(nalUnitType == NAL_UNIT_SUFFIX_SEI)
   {
     m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManagerDecoder[m_layerId].getActiveSPS() );
@@ -967,5 +1002,5 @@
   }
 #else
-  if(nalUnitType == NAL_UNIT_SEI_SUFFIX)
+  if(nalUnitType == NAL_UNIT_SUFFIX_SEI)
   {
     m_seiReader.parseSEImessage( bs, m_pcPic->getSEIs(), nalUnitType, m_parameterSetManagerDecoder.getActiveSPS() );
@@ -1035,6 +1070,6 @@
       return false;
       
-    case NAL_UNIT_SEI:
-    case NAL_UNIT_SEI_SUFFIX:
+    case NAL_UNIT_PREFIX_SEI:
+    case NAL_UNIT_SUFFIX_SEI:
       xDecodeSEI( nalu.m_Bitstream, nalu.m_nalUnitType );
       return false;
@@ -1042,18 +1077,18 @@
     case NAL_UNIT_CODED_SLICE_TRAIL_R:
     case NAL_UNIT_CODED_SLICE_TRAIL_N:
-    case NAL_UNIT_CODED_SLICE_TLA:
+    case NAL_UNIT_CODED_SLICE_TLA_R:
     case NAL_UNIT_CODED_SLICE_TSA_N:
     case NAL_UNIT_CODED_SLICE_STSA_R:
     case NAL_UNIT_CODED_SLICE_STSA_N:
-    case NAL_UNIT_CODED_SLICE_BLA:
-    case NAL_UNIT_CODED_SLICE_BLANT:
+    case NAL_UNIT_CODED_SLICE_BLA_W_LP:
+    case NAL_UNIT_CODED_SLICE_BLA_W_RADL:
     case NAL_UNIT_CODED_SLICE_BLA_N_LP:
-    case NAL_UNIT_CODED_SLICE_IDR:
+    case NAL_UNIT_CODED_SLICE_IDR_W_RADL:
     case NAL_UNIT_CODED_SLICE_IDR_N_LP:
     case NAL_UNIT_CODED_SLICE_CRA:
     case NAL_UNIT_CODED_SLICE_RADL_N:
-    case NAL_UNIT_CODED_SLICE_DLP:
+    case NAL_UNIT_CODED_SLICE_RADL_R:
     case NAL_UNIT_CODED_SLICE_RASL_N:
-    case NAL_UNIT_CODED_SLICE_TFD:
+    case NAL_UNIT_CODED_SLICE_RASL_R:
 #if SVC_EXTENSION
       return xDecodeSlice(nalu, iSkipFrame, iPOCLastDisplay, curLayerId, bNewPOC);
@@ -1077,5 +1112,5 @@
 Bool TDecTop::isSkipPictureForBLA(Int& iPOCLastDisplay)
 {
-  if (m_prevRAPisBLA && m_apcSlicePilot->getPOC() < m_pocCRA && (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TFD || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N))
+  if (m_prevRAPisBLA && m_apcSlicePilot->getPOC() < m_pocCRA && (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N))
   {
     iPOCLastDisplay++;
@@ -1108,12 +1143,12 @@
   {
     if (   m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA
-        || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA
+        || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
         || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
-        || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLANT )
+        || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL )
     {
       // set the POC random access since we need to skip the reordered pictures in the case of CRA/CRANT/BLA/BLANT.
       m_pocRandomAccess = m_apcSlicePilot->getPOC();
     }
-    else if ( m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )
+    else if ( m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP )
     {
       m_pocRandomAccess = -MAX_INT; // no need to skip the reordered pictures in IDR, they are decodable.
@@ -1131,5 +1166,5 @@
   }
   // skip the reordered pictures, if necessary
-  else if (m_apcSlicePilot->getPOC() < m_pocRandomAccess && (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_TFD || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N))
+  else if (m_apcSlicePilot->getPOC() < m_pocRandomAccess && (m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R || m_apcSlicePilot->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N))
   {
     iPOCLastDisplay++;
Index: branches/SHM-2.0-dev/source/Lib/TLibEncoder/SEIwrite.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 133)
@@ -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: branches/SHM-2.0-dev/source/Lib/TLibEncoder/SEIwrite.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibEncoder/SEIwrite.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibEncoder/SEIwrite.h	(revision 133)
@@ -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: branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 133)
@@ -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" );
@@ -583,5 +578,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]" );
@@ -810,5 +809,32 @@
       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 (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");
@@ -1389,82 +1415,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: branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncCavlc.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncCavlc.h	(revision 133)
@@ -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: branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncCfg.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncCfg.h	(revision 133)
@@ -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: branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 133)
@@ -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;
@@ -411,5 +530,5 @@
     }
     // Set the nal unit type
-    pcSlice->setNalUnitType(getNalUnitType(pocCurr));
+    pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR));
 #if IDR_ALIGNMENT
     if (m_layerId > 0)
@@ -424,7 +543,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
@@ -434,5 +553,5 @@
     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 +561,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 +598,5 @@
         else
         {
-          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA);
+          pcSlice->setNalUnitType(NAL_UNIT_CODED_SLICE_TLA_R);
         }
       }
@@ -527,5 +654,5 @@
     if(m_layerId > 0)
     {
-      if( pcSlice->getNalUnitType() >= NAL_UNIT_CODED_SLICE_BLA && pcSlice->getNalUnitType() <= NAL_UNIT_CODED_SLICE_CRA )
+      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());
@@ -644,5 +771,5 @@
       pcSlice->setSliceType ( P_SLICE );
     }
-
+#if !L0034_COMBINED_LIST_CLEANUP
     if (pcSlice->getSliceType() != B_SLICE || !pcSlice->getSPS()->getUseLComb())
     {
@@ -656,4 +783,5 @@
       pcSlice->setNumRefIdx(REF_PIC_LIST_C, pcSlice->getNumRefIdx(REF_PIC_LIST_0));
     }
+#endif
 
     if (pcSlice->getSliceType() == B_SLICE)
@@ -683,4 +811,8 @@
       pcSlice->setCheckLDC(bLowDelay);  
     }
+    else
+    {
+      pcSlice->setCheckLDC(true);  
+    }
 
     uiColDir = 1-uiColDir;
@@ -689,4 +821,7 @@
     pcSlice->setRefPOCList();
 
+#if L0034_COMBINED_LIST_CLEANUP
+    pcSlice->setList1IdxToList0Idx();
+#else
     pcSlice->setNoBackPredFlag( false );
     if ( pcSlice->getSliceType() == B_SLICE && !pcSlice->getRefPicListCombinationFlag())
@@ -712,4 +847,5 @@
     }
     pcSlice->generateCombinedList();
+#endif
 
     if (m_pcEncTop->getTMVPModeId() == 2)
@@ -1027,4 +1163,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 );
 
@@ -1133,4 +1275,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 +1360,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 +1401,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,8 +1411,35 @@
       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
+
       m_lastBPSEI = m_totalCoded;
       m_cpbRemovalDelay = 0;
@@ -1241,5 +1451,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 +1463,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 +1654,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 +1687,5 @@
               if (ui+1 < pcSlice->getPPS()->getNumSubstreams())
               {
-                puiSubstreamSizes[ui] = pcSubstreamsOut[ui].getNumberOfWrittenBits();
+                puiSubstreamSizes[ui] = pcSubstreamsOut[ui].getNumberOfWrittenBits() + (pcSubstreamsOut[ui].countStartCodeEmulations()<<3);
               }
             }
@@ -1516,5 +1719,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 +1747,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 +1843,7 @@
         }
 #if SVC_EXTENSION
-        OutputNALUnit nalu(NAL_UNIT_SEI_SUFFIX, pcSlice->getTLayer(), m_layerId);
+        OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer(), m_layerId);
 #else
-        OutputNALUnit nalu(NAL_UNIT_SEI_SUFFIX, pcSlice->getTLayer());
+        OutputNALUnit nalu(NAL_UNIT_SUFFIX_SEI, pcSlice->getTLayer());
 #endif
 
@@ -1667,5 +1870,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 +2010,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 +2031,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 +2064,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 +2112,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 +2123,7 @@
 #if L0045_NON_NESTED_SEI_RESTRICTIONS
       xResetNonNestedSEIPresentFlags();
+#if K0180_SCALABLE_NESTING_SEI
+      xResetNestedSEIPresentFlags();
+#endif
 #endif
       pcPic->getPicYuvRec()->copyToPic(pcPicYuvRecOut);
@@ -2113,16 +2348,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 +2367,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 +2459,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;
@@ -2325,9 +2561,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 +2575,5 @@
     else if (m_pcCfg->getDecodingRefreshType() == 2)
     {
-      return NAL_UNIT_CODED_SLICE_IDR;
+      return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
     }
   }
@@ -2351,5 +2587,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 +2645,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 +2656,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 +2788,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: branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncGOP.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncGOP.h	(revision 133)
@@ -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: branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 133)
@@ -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: branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 133)
@@ -57,7 +57,4 @@
 {
 private:
-  Double            m_dLambdaLuma;
-  Double            m_dLambdaChroma;
-
   TEncEntropy*      m_pcEntropyCoder;
   TEncSbac***       m_pppcRDSbacCoder;              ///< for CABAC
Index: branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSbac.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSbac.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSbac.h	(revision 133)
@@ -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: branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 133)
@@ -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;
@@ -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 );
 
@@ -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)
@@ -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--;
Index: branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 133)
@@ -400,4 +400,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())
   {
@@ -1182,5 +1191,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 +1371,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 +1379,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 );
       }
     }
Index: branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSlice.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncSlice.h	(revision 133)
@@ -126,5 +126,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
Index: branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncTop.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncTop.cpp	(revision 133)
@@ -599,6 +599,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 +627,7 @@
 
   m_cSPS.setMaxTrSize   ( 1 << m_uiQuadtreeTULog2MaxSize );
-  
+#if !L0034_COMBINED_LIST_CLEANUP
   m_cSPS.setUseLComb    ( m_bUseLComb           );
+#endif
   
   Int i;
@@ -763,5 +773,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);
@@ -1036,4 +1061,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()
 {
Index: branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncTop.h	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibEncoder/TEncTop.h	(revision 133)
@@ -192,4 +192,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
Index: branches/SHM-2.0-dev/source/Lib/TLibEncoder/WeightPredAnalysis.cpp
===================================================================
--- branches/SHM-2.0-dev/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 131)
+++ branches/SHM-2.0-dev/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 133)
@@ -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);
         }
 
