Index: trunk/source/App/TAppDecoder/TAppDecCfg.cpp
===================================================================
--- trunk/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 588)
+++ trunk/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/TAppDecoder/TAppDecCfg.h
===================================================================
--- trunk/source/App/TAppDecoder/TAppDecCfg.h	(revision 588)
+++ trunk/source/App/TAppDecoder/TAppDecCfg.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/TAppDecoder/TAppDecTop.cpp
===================================================================
--- trunk/source/App/TAppDecoder/TAppDecTop.cpp	(revision 588)
+++ trunk/source/App/TAppDecoder/TAppDecTop.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/TAppDecoder/TAppDecTop.h
===================================================================
--- trunk/source/App/TAppDecoder/TAppDecTop.h	(revision 588)
+++ trunk/source/App/TAppDecoder/TAppDecTop.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/TAppDecoder/decmain.cpp
===================================================================
--- trunk/source/App/TAppDecoder/decmain.cpp	(revision 588)
+++ trunk/source/App/TAppDecoder/decmain.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/TAppDownConvert/DownConvert.cpp
===================================================================
--- trunk/source/App/TAppDownConvert/DownConvert.cpp	(revision 588)
+++ trunk/source/App/TAppDownConvert/DownConvert.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/TAppDownConvert/DownConvert.h
===================================================================
--- trunk/source/App/TAppDownConvert/DownConvert.h	(revision 588)
+++ trunk/source/App/TAppDownConvert/DownConvert.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/TAppDownConvert/TAppDownConvert.cpp
===================================================================
--- trunk/source/App/TAppDownConvert/TAppDownConvert.cpp	(revision 588)
+++ trunk/source/App/TAppDownConvert/TAppDownConvert.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/TAppEncoder/TAppEncCfg.cpp
===================================================================
--- trunk/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 588)
+++ trunk/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -104,6 +104,5 @@
 #if SVC_EXTENSION
   free(m_pBitstreamFile);
-#else
-  free(m_pchBitstreamFile);
+#else  
   if ( m_aidQP )
   {
@@ -126,4 +125,5 @@
   }
   free(m_pchInputFile);
+  free(m_pchBitstreamFile);
 #endif
 #if !SVC_EXTENSION  
@@ -626,10 +626,11 @@
   ("FrameRate,-fr",         m_iFrameRate,          0, "Frame rate")
 #endif //SVC_EXTENSION
+  ("FrameSkip,-fs",         m_FrameSkip,          0u, "Number of frames to skip at start of input YUV")
+  ("FramesToBeEncoded,f",   m_framesToBeEncoded,   0, "Number of frames to be encoded (default=all)")
 
   //Field coding parameters
   ("FieldCoding", m_isField, false, "Signals if it's a field based coding")
   ("TopFieldFirst, Tff", m_isTopFieldFirst, false, "In case of field based coding, signals whether if it's a top field first or not")
-  ("FrameSkip,-fs",         m_FrameSkip,          0u, "Number of frames to skip at start of input YUV")
-  ("FramesToBeEncoded,f",   m_framesToBeEncoded,   0, "Number of frames to be encoded (default=all)")
+  
   // Profile and level
   ("Profile", m_profile,   Profile::NONE, "Profile to be used when encoding (Incomplete)")
@@ -741,6 +742,4 @@
   ("RDOQTS",                        m_useRDOQTS,                true )
   ("RDpenalty",                     m_rdPenalty,                0,  "RD-penalty for 32x32 TU for intra in non-intra slices. 0:disbaled  1:RD-penalty  2:maximum RD-penalty")
-  // Entropy coding parameters
-  ("SBACRD",                         m_bUseSBACRD,                      true, "SBAC based RD estimation")
   
   // Deblocking filter parameters
@@ -759,7 +758,4 @@
   ("MaxNumOffsetsPerPic",      m_maxNumOffsetsPerPic,       2048,  "Max number of SAO offset per picture (Default: 2048)")   
   ("SAOLcuBoundary",           m_saoLcuBoundary,            false, "0: right/bottom LCU boundary areas skipped from SAO parameter estimation, 1: non-deblocked pixels are used for those areas")
-#if !HM_CLEANUP_SAO
-  ("SAOLcuBasedOptimization",  m_saoLcuBasedOptimization,   true,  "0: SAO picture-based optimization, 1: SAO LCU-based optimization ")
-#endif  
   ("SliceMode",                m_sliceMode,                0,     "0: Disable all Recon slice limits, 1: Enforce max # of LCUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
   ("SliceArgument",            m_sliceArgument,            0,     "Depending on SliceMode being:"
@@ -781,6 +777,4 @@
   ("PCMInputBitDepthFlag",     m_bPCMInputBitDepthFlag,     true)
   ("PCMFilterDisableFlag",     m_bPCMFilterDisableFlag,    false)
-
-  ("LosslessCuEnabled",        m_useLossless, false)
 
   ("WeightedPredP,-wpP",          m_useWeightedPred,               false,      "Use weighted prediction in P slices")
@@ -834,5 +828,5 @@
 
   ("TransquantBypassEnableFlag", m_TransquantBypassEnableFlag, false, "transquant_bypass_enable_flag indicator in PPS")
-  ("CUTransquantBypassFlagValue", m_CUTransquantBypassFlagValue, false, "Fixed cu_transquant_bypass_flag value, when transquant_bypass_enable_flag is enabled")
+  ("CUTransquantBypassFlagForce", m_CUTransquantBypassFlagForce, false, "Force transquant bypass mode, when transquant_bypass_enable_flag is enabled")
   ("RecalculateQPAccordingToLambda", m_recalculateQPAccordingToLambda, false, "Recalculate QP values according to lambda values. Do not suggest to be enabled in all intra case")
   ("StrongIntraSmoothing,-sis",      m_useStrongIntraSmoothing,           true, "Enable strong intra smoothing for 32x32 blocks")
@@ -1952,5 +1946,4 @@
   }
   xConfirmPara(errorGOP,"Invalid GOP structure given");
-
   m_maxTempLayer = 1;
   for(Int i=0; i<m_iGOPSize; i++) 
@@ -1960,5 +1953,5 @@
       m_maxTempLayer = m_GOPList[i].m_temporalId+1;
     }
-    xConfirmPara(m_GOPList[i].m_sliceType!='B'&&m_GOPList[i].m_sliceType!='P', "Slice type must be equal to B or P");
+    xConfirmPara(m_GOPList[i].m_sliceType!='B'&&m_GOPList[i].m_sliceType!='P'&&m_GOPList[i].m_sliceType!='I', "Slice type must be equal to B or P or I");
   }
   for(Int i=0; i<MAX_TLAYER; i++)
@@ -1973,5 +1966,4 @@
       m_maxDecPicBuffering[m_GOPList[i].m_temporalId] = m_GOPList[i].m_numRefPics + 1;
     }
-
     Int highestDecodingNumberWithLowerPOC = 0; 
     for(Int j=0; j<m_iGOPSize; j++)
@@ -2158,5 +2150,5 @@
 #endif
 
-  xConfirmPara(!m_TransquantBypassEnableFlag && m_CUTransquantBypassFlagValue, "CUTransquantBypassFlagValue cannot be 1 when TransquantBypassEnableFlag is 0");
+  xConfirmPara(!m_TransquantBypassEnableFlag && m_CUTransquantBypassFlagForce, "CUTransquantBypassFlagForce cannot be 1 when TransquantBypassEnableFlag is 0");
 
   xConfirmPara(m_log2ParallelMergeLevel < 2, "Log2ParallelMergeLevel should be larger than or equal to 2");
@@ -2440,5 +2432,4 @@
 #endif
   printf("HAD:%d ", m_bUseHADME           );
-  printf("SRD:%d ", m_bUseSBACRD          );
   printf("RDQ:%d ", m_useRDOQ            );
   printf("RDQTS:%d ", m_useRDOQTS        );
@@ -2472,8 +2463,12 @@
   printf("PCM:%d ", (m_usePCM && (1<<m_uiPCMLog2MinSize) <= m_uiMaxCUWidth)? 1 : 0);
 #endif
-#if !HM_CLEANUP_SAO
-  printf("SAOLcuBasedOptimization:%d ", (m_saoLcuBasedOptimization)?(1):(0));
-#endif
-  printf("LosslessCuEnabled:%d ", (m_useLossless)? 1:0 );
+  if (m_TransquantBypassEnableFlag && m_CUTransquantBypassFlagForce)
+  {
+    printf("TransQuantBypassEnabled: =1 ");
+  }
+  else
+  {
+    printf("TransQuantBypassEnabled:%d ", (m_TransquantBypassEnableFlag)? 1:0 );
+  }
   printf("WPP:%d ", (Int)m_useWeightedPred);
   printf("WPB:%d ", (Int)m_useWeightedBiPred);
Index: trunk/source/App/TAppEncoder/TAppEncCfg.h
===================================================================
--- trunk/source/App/TAppEncoder/TAppEncCfg.h	(revision 588)
+++ trunk/source/App/TAppEncoder/TAppEncCfg.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -179,12 +179,8 @@
   Bool      m_bPCMInputBitDepthFlag;                          ///< 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
 
-  // coding tool (lossless)
-  Bool      m_useLossless;                                    ///< flag for using lossless coding
+  // coding tool (SAO)
   Bool      m_bUseSAO; 
   Int       m_maxNumOffsetsPerPic;                            ///< SAO maximun number of offset per picture
   Bool      m_saoLcuBoundary;                                 ///< SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
-#if !HM_CLEANUP_SAO
-  Bool      m_saoLcuBasedOptimization;                        ///< SAO LCU-based optimization
-#endif
   // coding tools (loop filter)
   Bool      m_bLoopFilterDisable;                             ///< flag for using deblocking filter
@@ -202,5 +198,4 @@
 
   // coding tools (encoder-only parameters)
-  Bool      m_bUseSBACRD;                                     ///< flag for using RD optimization based on SBAC
   Bool      m_bUseASR;                                        ///< flag for using adaptive motion search range
   Bool      m_bUseHADME;                                      ///< flag for using HAD in sub-pel ME
@@ -307,5 +302,5 @@
 
   Bool      m_TransquantBypassEnableFlag;                     ///< transquant_bypass_enable_flag setting in PPS.
-  Bool      m_CUTransquantBypassFlagValue;                    ///< if transquant_bypass_enable_flag, the fixed value to use for the per-CU cu_transquant_bypass_flag.
+  Bool      m_CUTransquantBypassFlagForce;                    ///< if transquant_bypass_enable_flag, then, if true, all CU transquant bypass flags will be set to true.
 
   Bool      m_recalculateQPAccordingToLambda;                 ///< recalculate QP value according to the lambda value
Index: trunk/source/App/TAppEncoder/TAppEncTop.cpp
===================================================================
--- trunk/source/App/TAppEncoder/TAppEncTop.cpp	(revision 588)
+++ trunk/source/App/TAppEncoder/TAppEncTop.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -346,21 +346,12 @@
     m_acTEncTop[layer].setUseAdaptQpSelect             ( m_bUseAdaptQpSelect   );
 #endif
-
-    Int lowestQP;
-    lowestQP =  - 6*(g_bitDepthY - 8); // XXX: check
-
-    if ((m_iMaxDeltaQP == 0 ) && (m_acLayerCfg[layer].getIntQP() == lowestQP) && (m_useLossless == true))
-    {
-      m_bUseAdaptiveQP = false;
-    }
+    
     m_acTEncTop[layer].setUseAdaptiveQP                ( m_bUseAdaptiveQP  );
     m_acTEncTop[layer].setQPAdaptationRange            ( m_iQPAdaptationRange );
 
-    //====== Tool list ========
-    m_acTEncTop[layer].setUseSBACRD                    ( m_bUseSBACRD   );
+    //====== Tool list ========    
     m_acTEncTop[layer].setDeltaQpRD                    ( m_uiDeltaQpRD  );
     m_acTEncTop[layer].setUseASR                       ( m_bUseASR      );
-    m_acTEncTop[layer].setUseHADME                     ( m_bUseHADME    );
-    m_acTEncTop[layer].setUseLossless                  ( m_useLossless );
+    m_acTEncTop[layer].setUseHADME                     ( m_bUseHADME    );    
     m_acTEncTop[layer].setdQPs                         ( m_acLayerCfg[layer].getdQPs() );
     m_acTEncTop[layer].setUseRDOQ                      ( m_useRDOQ     );
@@ -444,7 +435,4 @@
 
     m_acTEncTop[layer].setSaoLcuBoundary (m_saoLcuBoundary);
-#if !HM_CLEANUP_SAO
-    m_acTEncTop[layer].setSaoLcuBasedOptimization (m_saoLcuBasedOptimization);
-#endif
     m_acTEncTop[layer].setPCMInputBitDepthFlag  ( m_bPCMInputBitDepthFlag);
     m_acTEncTop[layer].setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag);
@@ -540,5 +528,5 @@
 #endif
     m_acTEncTop[layer].setTransquantBypassEnableFlag(m_TransquantBypassEnableFlag);
-    m_acTEncTop[layer].setCUTransquantBypassFlagValue(m_CUTransquantBypassFlagValue);
+    m_acTEncTop[layer].setCUTransquantBypassFlagForceValue(m_CUTransquantBypassFlagForce);
     m_acTEncTop[layer].setUseRecalculateQPAccordingToLambda( m_recalculateQPAccordingToLambda );
     m_acTEncTop[layer].setUseStrongIntraSmoothing( m_useStrongIntraSmoothing );
@@ -680,20 +668,11 @@
 #endif
 
-  Int lowestQP;
-  lowestQP =  - 6*(g_bitDepthY - 8); // XXX: check
-
-  if ((m_iMaxDeltaQP == 0 ) && (m_iQP == lowestQP) && (m_useLossless == true))
-  {
-    m_bUseAdaptiveQP = false;
-  }
   m_cTEncTop.setUseAdaptiveQP                ( m_bUseAdaptiveQP  );
   m_cTEncTop.setQPAdaptationRange            ( m_iQPAdaptationRange );
 
   //====== Tool list ========
-  m_cTEncTop.setUseSBACRD                    ( m_bUseSBACRD   );
   m_cTEncTop.setDeltaQpRD                    ( m_uiDeltaQpRD  );
   m_cTEncTop.setUseASR                       ( m_bUseASR      );
   m_cTEncTop.setUseHADME                     ( m_bUseHADME    );
-  m_cTEncTop.setUseLossless                  ( m_useLossless );
   m_cTEncTop.setdQPs                         ( m_aidQP        );
   m_cTEncTop.setUseRDOQ                      ( m_useRDOQ     );
@@ -758,7 +737,4 @@
 
   m_cTEncTop.setSaoLcuBoundary (m_saoLcuBoundary);
-#if !HM_CLEANUP_SAO
-  m_cTEncTop.setSaoLcuBasedOptimization (m_saoLcuBasedOptimization);
-#endif
   m_cTEncTop.setPCMInputBitDepthFlag  ( m_bPCMInputBitDepthFlag);
   m_cTEncTop.setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag);
@@ -836,5 +812,5 @@
   m_cTEncTop.setForceIntraQP        ( m_RCForceIntraQP );
   m_cTEncTop.setTransquantBypassEnableFlag(m_TransquantBypassEnableFlag);
-  m_cTEncTop.setCUTransquantBypassFlagValue(m_CUTransquantBypassFlagValue);
+  m_cTEncTop.setCUTransquantBypassFlagForceValue(m_CUTransquantBypassFlagForce);
   m_cTEncTop.setUseRecalculateQPAccordingToLambda( m_recalculateQPAccordingToLambda );
   m_cTEncTop.setUseStrongIntraSmoothing( m_useStrongIntraSmoothing );
Index: trunk/source/App/TAppEncoder/TAppEncTop.h
===================================================================
--- trunk/source/App/TAppEncoder/TAppEncTop.h	(revision 588)
+++ trunk/source/App/TAppEncoder/TAppEncTop.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/TAppEncoder/encmain.cpp
===================================================================
--- trunk/source/App/TAppEncoder/encmain.cpp	(revision 588)
+++ trunk/source/App/TAppEncoder/encmain.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/utils/BitrateTargeting/ExtractBitrates.cpp
===================================================================
--- trunk/source/App/utils/BitrateTargeting/ExtractBitrates.cpp	(revision 588)
+++ trunk/source/App/utils/BitrateTargeting/ExtractBitrates.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/utils/BitrateTargeting/ExtractBitrates.h
===================================================================
--- trunk/source/App/utils/BitrateTargeting/ExtractBitrates.h	(revision 588)
+++ trunk/source/App/utils/BitrateTargeting/ExtractBitrates.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp
===================================================================
--- trunk/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp	(revision 588)
+++ trunk/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp
===================================================================
--- trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp	(revision 588)
+++ trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h
===================================================================
--- trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h	(revision 588)
+++ trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp
===================================================================
--- trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp	(revision 588)
+++ trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/utils/BitrateTargeting/RuntimeError.h
===================================================================
--- trunk/source/App/utils/BitrateTargeting/RuntimeError.h	(revision 588)
+++ trunk/source/App/utils/BitrateTargeting/RuntimeError.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/utils/BitrateTargeting/encode.shl
===================================================================
--- trunk/source/App/utils/BitrateTargeting/encode.shl	(revision 588)
+++ trunk/source/App/utils/BitrateTargeting/encode.shl	(revision 595)
@@ -4,5 +4,5 @@
 # granted under this license.  
 #
-# Copyright (c) 2010-2012, ITU/ISO/IEC
+# Copyright (c) 2010-2014, ITU/ISO/IEC
 # All rights reserved.
 #
Index: trunk/source/App/utils/BitrateTargeting/encodeCommand.sh
===================================================================
--- trunk/source/App/utils/BitrateTargeting/encodeCommand.sh	(revision 588)
+++ trunk/source/App/utils/BitrateTargeting/encodeCommand.sh	(revision 595)
@@ -6,5 +6,5 @@
 # granted under this license.  
 #
-# Copyright (c) 2010-2012, ITU/ISO/IEC
+# Copyright (c) 2010-2014, ITU/ISO/IEC
 # All rights reserved.
 #
Index: trunk/source/App/utils/BitrateTargeting/makefile
===================================================================
--- trunk/source/App/utils/BitrateTargeting/makefile	(revision 588)
+++ trunk/source/App/utils/BitrateTargeting/makefile	(revision 595)
@@ -4,5 +4,5 @@
 # granted under this license.  
 #
-# Copyright (c) 2010-2012, ITU/ISO/IEC
+# Copyright (c) 2010-2014, ITU/ISO/IEC
 # All rights reserved.
 #
Index: trunk/source/App/utils/BitrateTargeting/targetBitrates.sh
===================================================================
--- trunk/source/App/utils/BitrateTargeting/targetBitrates.sh	(revision 588)
+++ trunk/source/App/utils/BitrateTargeting/targetBitrates.sh	(revision 595)
@@ -6,5 +6,5 @@
 # granted under this license.  
 #
-# Copyright (c) 2010-2012, ITU/ISO/IEC
+# Copyright (c) 2010-2014, ITU/ISO/IEC
 # All rights reserved.
 #
Index: trunk/source/App/utils/annexBbytecount.cpp
===================================================================
--- trunk/source/App/utils/annexBbytecount.cpp	(revision 588)
+++ trunk/source/App/utils/annexBbytecount.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/App/utils/convert_NtoMbit_YCbCr.cpp
===================================================================
--- trunk/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 588)
+++ trunk/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2012, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TAppCommon/program_options_lite.cpp
===================================================================
--- trunk/source/Lib/TAppCommon/program_options_lite.cpp	(revision 588)
+++ trunk/source/Lib/TAppCommon/program_options_lite.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TAppCommon/program_options_lite.h
===================================================================
--- trunk/source/Lib/TAppCommon/program_options_lite.h	(revision 588)
+++ trunk/source/Lib/TAppCommon/program_options_lite.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/AccessUnit.h
===================================================================
--- trunk/source/Lib/TLibCommon/AccessUnit.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/AccessUnit.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/CommonDef.h
===================================================================
--- trunk/source/Lib/TLibCommon/CommonDef.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/CommonDef.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -40,4 +40,5 @@
 
 #include <algorithm>
+
 #if _MSC_VER > 1000
 // disable "signed and unsigned mismatch"
@@ -57,7 +58,7 @@
 #if SVC_EXTENSION
 #include <vector>
-#define NV_VERSION        "5.0 (HM-12.1)"                 ///< Current software version
+#define NV_VERSION        "5.0 (HM-13.0)"                 ///< Current software version
 #else
-#define NV_VERSION        "12.1"                ///< Current software version
+#define NV_VERSION        "13.0"                ///< Current software version
 #endif
 
Index: trunk/source/Lib/TLibCommon/ContextModel.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/ContextModel.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/ContextModel.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/ContextModel.h
===================================================================
--- trunk/source/Lib/TLibCommon/ContextModel.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/ContextModel.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/ContextModel3DBuffer.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/ContextModel3DBuffer.h
===================================================================
--- trunk/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/ContextTables.h
===================================================================
--- trunk/source/Lib/TLibCommon/ContextTables.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/ContextTables.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -42,6 +42,4 @@
 //! \ingroup TLibCommon
 //! \{
-#define FIX827 1 ///< Fix for issue #827: CABAC init tables
-#define FIX712 1 ///< Fix for issue #712: CABAC init tables
 
 // ====================================================================================================================
@@ -58,5 +56,4 @@
 
 #define NUM_PART_SIZE_CTX             4       ///< number of context models for partition size
-#define NUM_CU_AMP_CTX                1       ///< number of context models for partition size (AMP)
 #define NUM_PRED_MODE_CTX             1       ///< number of context models for prediction mode
 
@@ -69,5 +66,5 @@
 #define NUM_REF_NO_CTX                2       ///< number of context models for reference index
 #define NUM_TRANS_SUBDIV_FLAG_CTX     3       ///< number of context models for transform subdivision flags
-#define NUM_QT_CBF_CTX                5       ///< number of context models for QT CBF
+#define NUM_QT_CBF_CTX                4       ///< number of context models for QT CBF
 #define NUM_QT_ROOT_CBF_CTX           1       ///< number of context models for QT ROOT CBF
 #define NUM_DELTA_QP_CTX              3       ///< number of context models for dQP
@@ -88,5 +85,5 @@
 #define NUM_ABS_FLAG_CTX_CHROMA        2      ///< number of context models for greater than 2 flag of chroma
 
-#define NUM_MVP_IDX_CTX               2       ///< number of context models for MVP index
+#define NUM_MVP_IDX_CTX               1       ///< number of context models for MVP index
 
 #define NUM_SAO_MERGE_FLAG_CTX        1       ///< number of context models for SAO merge flags
@@ -146,15 +143,7 @@
 INIT_PART_SIZE[3][NUM_PART_SIZE_CTX] =  
 {
-  { 154,  139,  CNU,  CNU, }, 
-  { 154,  139,  CNU,  CNU, }, 
-  { 184,  CNU,  CNU,  CNU, }, 
-};
-
-static const UChar 
-INIT_CU_AMP_POS[3][NUM_CU_AMP_CTX] =  
-{
-  { 154, }, 
-  { 154, }, 
-  { CNU, }, 
+  { 154,  139,  154,  154 },
+  { 154,  139,  154,  154 },
+  { 184,  CNU,  CNU,  CNU },
 };
 
@@ -218,7 +207,7 @@
 INIT_QT_CBF[3][2*NUM_QT_CBF_CTX] =  
 {
-  { 153,  111,  CNU,  CNU,  CNU,  149,   92,  167,  CNU,  CNU, }, 
-  { 153,  111,  CNU,  CNU,  CNU,  149,  107,  167,  CNU,  CNU, }, 
-  { 111,  141,  CNU,  CNU,  CNU,   94,  138,  182,  CNU,  CNU, }, 
+  { 153,  111,  CNU,  CNU,   149,   92,  167,  154 },
+  { 153,  111,  CNU,  CNU,   149,  107,  167,  154 },
+  { 111,  141,  CNU,  CNU,    94,  138,  182,  154 },
 };
 
@@ -286,7 +275,7 @@
 INIT_MVP_IDX[3][NUM_MVP_IDX_CTX] =  
 {
-  { 168,  CNU, }, 
-  { 168,  CNU, }, 
-  { CNU,  CNU, }, 
+  { 168 },
+  { 168 },
+  { CNU }, 
 };
 
@@ -302,13 +291,7 @@
 INIT_SAO_TYPE_IDX[3][NUM_SAO_TYPE_IDX_CTX] = 
 {
-#if FIX827
   { 160, },
   { 185, },
   { 200, },
-#else
-  { 200, },
-  { 185, }, 
-  { 160, },
-#endif
 };
 
@@ -316,13 +299,7 @@
 INIT_TRANS_SUBDIV_FLAG[3][NUM_TRANS_SUBDIV_FLAG_CTX] =
 {
-#if FIX712
   { 224,  167,  122, },
   { 124,  138,   94, },
   { 153,  138,  138, },
-#else
-  { 153,  138,  138, },
-  { 124,  138,   94, },
-  { 224,  167,  122, },
-#endif
 };
 
Index: trunk/source/Lib/TLibCommon/NAL.h
===================================================================
--- trunk/source/Lib/TLibCommon/NAL.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/NAL.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/SEI.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/SEI.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/SEI.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/SEI.h
===================================================================
--- trunk/source/Lib/TLibCommon/SEI.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/SEI.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComBitCounter.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComBitCounter.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComBitCounter.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComBitStream.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComBitStream.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComBitStream.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComBitStream.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComBitStream.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComBitStream.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComCABACTables.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComCABACTables.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComCABACTables.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComCABACTables.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComDataCU.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComDataCU.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComDataCU.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -309,24 +309,5 @@
   }
 }
-#if !HM_CLEANUP_SAO
-const NDBFBlockInfo& NDBFBlockInfo::operator= (const NDBFBlockInfo& src)
-{
-  this->tileID = src.tileID;
-  this->sliceID= src.sliceID;
-  this->startSU= src.startSU;
-  this->endSU  = src.endSU;
-  this->widthSU= src.widthSU;
-  this->heightSU=src.heightSU;
-  this->posX   = src.posX;
-  this->posY   = src.posY;
-  this->width  = src.width;
-  this->height = src.height;
-  ::memcpy(this->isBorderAvailable, src.isBorderAvailable, sizeof(Bool)*((Int)NUM_SGU_BORDER));
-  this->allBordersAvailable = src.allBordersAvailable;
-
-  return *this;
-}
-
-#endif
+
 // ====================================================================================================================
 // Public member functions
@@ -547,5 +528,5 @@
 *- set last-coded qp value according to input last-coded qp 
 */
-Void TComDataCU::initEstData( UInt uiDepth, Int qp )
+Void TComDataCU::initEstData( UInt uiDepth, Int qp, Bool bTransquantBypass )
 {
   m_dTotalCost         = MAX_DOUBLE;
@@ -575,5 +556,5 @@
       m_pePartSize[ui] = SIZE_NONE;
       m_pePredMode[ui] = MODE_NONE;
-      m_CUTransquantBypass[ui] = false;
+      m_CUTransquantBypass[ui] = bTransquantBypass;
       m_pbIPCMFlag[ui] = 0;
       m_phQP[ui] = qp;
@@ -2550,5 +2531,4 @@
   TComDataCU* pcCULeft = 0;
   pcCULeft = getPULeft( uiLeftPartIdx, uiPartIdxLB );
-
   Bool isAvailableA1 = pcCULeft &&
   pcCULeft->isDiffMER(xP -1, yP+nPSH-1, xP, yP) &&
@@ -2582,5 +2562,4 @@
   TComDataCU* pcCUAbove = 0;
   pcCUAbove = getPUAbove( uiAbovePartIdx, uiPartIdxRT );
-
   Bool isAvailableB1 = pcCUAbove &&
   pcCUAbove->isDiffMER(xP+nPSW-1, yP-1, xP, yP) &&
@@ -2614,5 +2593,4 @@
   TComDataCU* pcCUAboveRight = 0;
   pcCUAboveRight = getPUAboveRight( uiAboveRightPartIdx, uiPartIdxRT );
-
   Bool isAvailableB0 = pcCUAboveRight &&
   pcCUAboveRight->isDiffMER(xP+nPSW, yP-1, xP, yP) &&
@@ -2645,5 +2623,4 @@
   TComDataCU* pcCULeftBottom = 0;
   pcCULeftBottom = this->getPUBelowLeft( uiLeftBottomPartIdx, uiPartIdxLB );
-
   Bool isAvailableA0 = pcCULeftBottom &&
   pcCULeftBottom->isDiffMER(xP-1, yP+nPSH, xP, yP) &&
@@ -2671,5 +2648,4 @@
     return;
   }
-
   // above left 
   if( iCount < 4 )
@@ -2678,5 +2654,4 @@
     TComDataCU* pcCUAboveLeft = 0;
     pcCUAboveLeft = getPUAboveLeft( uiAboveLeftPartIdx, uiAbsPartAddr );
-
     Bool isAvailableB2 = pcCUAboveLeft &&
     pcCUAboveLeft->isDiffMER(xP-1, yP-1, xP, yP) &&
@@ -3013,4 +2988,5 @@
     }
   }
+  
   // Above predictor search
   bAdded = xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE_RIGHT);
@@ -3025,8 +3001,6 @@
     xAddMVPCand( pInfo, eRefPicList, iRefIdx, uiPartIdxLT, MD_ABOVE_LEFT);
   }
-  bAdded = bAddedSmvp;
-  if (pInfo->iN==2) bAdded = true;
-
-  if(!bAdded)
+
+  if (!bAddedSmvp)
   {
     bAdded = xAddMVPCandOrder( pInfo, eRefPicList, iRefIdx, uiPartIdxRT, MD_ABOVE_RIGHT);
@@ -3626,375 +3600,4 @@
   return getPic()->getPicSym()->getInverseCUOrderMap(m_uiCUAddr)*(1<<(m_pcSlice->getSPS()->getMaxCUDepth()<<1))+m_uiAbsIdxInLCU; 
 }
-#if !HM_CLEANUP_SAO
-/** Set neighboring blocks availabilities for non-deblocked filtering 
- * \param numLCUInPicWidth number of LCUs in picture width
- * \param numLCUInPicHeight number of LCUs in picture height
- * \param numSUInLCUWidth number of SUs in LCU width
- * \param numSUInLCUHeight number of SUs in LCU height
- * \param picWidth picture width
- * \param picHeight picture height
- * \param bIndependentSliceBoundaryEnabled true for independent slice boundary enabled
- * \param bTopTileBoundary true means that top boundary coincides tile boundary
- * \param bDownTileBoundary true means that bottom boundary coincides tile boundary
- * \param bLeftTileBoundary true means that left boundary coincides tile boundary
- * \param bRightTileBoundary true means that right boundary coincides tile boundary
- * \param bIndependentTileBoundaryEnabled true for independent tile boundary enabled
- */
-Void TComDataCU::setNDBFilterBlockBorderAvailability(UInt numLCUInPicWidth, UInt /*numLCUInPicHeight*/, UInt numSUInLCUWidth, UInt numSUInLCUHeight, UInt picWidth, UInt picHeight
-                                                    ,std::vector<Bool>& LFCrossSliceBoundary
-                                                    ,Bool bTopTileBoundary, Bool bDownTileBoundary, Bool bLeftTileBoundary, Bool bRightTileBoundary
-                                                    ,Bool bIndependentTileBoundaryEnabled)
-{
-  UInt numSUInLCU = numSUInLCUWidth*numSUInLCUHeight;
-  Int* pSliceIDMapLCU = m_piSliceSUMap;
-  Bool onlyOneSliceInPic = ((Int)LFCrossSliceBoundary.size() == 1);
-  UInt uiLPelX, uiTPelY;
-  UInt width, height;
-  Bool bPicRBoundary, bPicBBoundary, bPicTBoundary, bPicLBoundary;
-  Bool bLCURBoundary= false, bLCUBBoundary= false, bLCUTBoundary= false, bLCULBoundary= false;
-  Bool* pbAvailBorder;
-  Bool* pbAvail;
-  UInt rTLSU, rBRSU, widthSU, heightSU;
-  UInt zRefSU;
-  Int* pRefID;
-  Int* pRefMapLCU;
-  UInt rTRefSU= 0, rBRefSU= 0, rLRefSU= 0, rRRefSU= 0;
-  Int* pRRefMapLCU= NULL;
-  Int* pLRefMapLCU= NULL;
-  Int* pTRefMapLCU= NULL;
-  Int* pBRefMapLCU= NULL;
-  Int  sliceID;
-  UInt numSGU = (UInt)m_vNDFBlock.size();
-
-  for(Int i=0; i< numSGU; i++)
-  {
-    NDBFBlockInfo& rSGU = m_vNDFBlock[i];
-
-    sliceID = rSGU.sliceID;
-    uiLPelX = rSGU.posX;
-    uiTPelY = rSGU.posY;
-    width   = rSGU.width;
-    height  = rSGU.height;
-    rTLSU     = g_auiZscanToRaster[ rSGU.startSU ];
-    rBRSU     = g_auiZscanToRaster[ rSGU.endSU   ];
-    widthSU   = rSGU.widthSU;
-    heightSU  = rSGU.heightSU;
-
-    pbAvailBorder = rSGU.isBorderAvailable;
-
-    bPicTBoundary= (uiTPelY == 0                       )?(true):(false);
-    bPicLBoundary= (uiLPelX == 0                       )?(true):(false);
-    bPicRBoundary= (!(uiLPelX+ width < picWidth )  )?(true):(false);
-    bPicBBoundary= (!(uiTPelY + height < picHeight))?(true):(false);
-
-    bLCULBoundary = (rTLSU % numSUInLCUWidth == 0)?(true):(false);
-    bLCURBoundary = ( (rTLSU+ widthSU) % numSUInLCUWidth == 0)?(true):(false);
-    bLCUTBoundary = ( (UInt)(rTLSU / numSUInLCUWidth)== 0)?(true):(false);
-    bLCUBBoundary = ( (UInt)(rBRSU / numSUInLCUWidth) == (numSUInLCUHeight-1) )?(true):(false);
-
-    //       SGU_L
-    pbAvail = &(pbAvailBorder[SGU_L]);
-    if(bPicLBoundary)
-    {
-      *pbAvail = false;
-    }
-    else if (onlyOneSliceInPic)
-    {
-      *pbAvail = true;
-    }
-    else
-    {
-      //      bLCULBoundary = (rTLSU % uiNumSUInLCUWidth == 0)?(true):(false);
-      if(bLCULBoundary)
-      {
-        rLRefSU     = rTLSU + numSUInLCUWidth -1;
-        zRefSU      = g_auiRasterToZscan[rLRefSU];
-        pRefMapLCU = pLRefMapLCU= (pSliceIDMapLCU - numSUInLCU);
-      }
-      else
-      {
-        zRefSU   = g_auiRasterToZscan[rTLSU - 1];
-        pRefMapLCU  = pSliceIDMapLCU;
-      }
-      pRefID = pRefMapLCU + zRefSU;
-      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
-    }
-
-    //       SGU_R
-    pbAvail = &(pbAvailBorder[SGU_R]);
-    if(bPicRBoundary)
-    {
-      *pbAvail = false;
-    }
-    else if (onlyOneSliceInPic)
-    {
-      *pbAvail = true;
-    }
-    else
-    {
-      //       bLCURBoundary = ( (rTLSU+ uiWidthSU) % uiNumSUInLCUWidth == 0)?(true):(false);
-      if(bLCURBoundary)
-      {
-        rRRefSU      = rTLSU + widthSU - numSUInLCUWidth;
-        zRefSU       = g_auiRasterToZscan[rRRefSU];
-        pRefMapLCU  = pRRefMapLCU= (pSliceIDMapLCU + numSUInLCU);
-      }
-      else
-      {
-        zRefSU       = g_auiRasterToZscan[rTLSU + widthSU];
-        pRefMapLCU  = pSliceIDMapLCU;
-      }
-      pRefID = pRefMapLCU + zRefSU;
-      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
-    }
-
-    //       SGU_T
-    pbAvail = &(pbAvailBorder[SGU_T]);
-    if(bPicTBoundary)
-    {
-      *pbAvail = false;
-    }
-    else if (onlyOneSliceInPic)
-    {
-      *pbAvail = true;
-    }
-    else
-    {
-      //      bLCUTBoundary = ( (UInt)(rTLSU / uiNumSUInLCUWidth)== 0)?(true):(false);
-      if(bLCUTBoundary)
-      {
-        rTRefSU      = numSUInLCU - (numSUInLCUWidth - rTLSU);
-        zRefSU       = g_auiRasterToZscan[rTRefSU];
-        pRefMapLCU  = pTRefMapLCU= (pSliceIDMapLCU - (numLCUInPicWidth*numSUInLCU));
-      }
-      else
-      {
-        zRefSU       = g_auiRasterToZscan[rTLSU - numSUInLCUWidth];
-        pRefMapLCU  = pSliceIDMapLCU;
-      }
-      pRefID = pRefMapLCU + zRefSU;
-      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
-    }
-
-    //       SGU_B
-    pbAvail = &(pbAvailBorder[SGU_B]);
-    if(bPicBBoundary)
-    {
-      *pbAvail = false;
-    }
-    else if (onlyOneSliceInPic)
-    {
-      *pbAvail = true;
-    }
-    else
-    {
-      //      bLCUBBoundary = ( (UInt)(rBRSU / uiNumSUInLCUWidth) == (uiNumSUInLCUHeight-1) )?(true):(false);
-      if(bLCUBBoundary)
-      {
-        rBRefSU      = rTLSU % numSUInLCUWidth;
-        zRefSU       = g_auiRasterToZscan[rBRefSU];
-        pRefMapLCU  = pBRefMapLCU= (pSliceIDMapLCU + (numLCUInPicWidth*numSUInLCU));
-      }
-      else
-      {
-        zRefSU       = g_auiRasterToZscan[rTLSU + (heightSU*numSUInLCUWidth)];
-        pRefMapLCU  = pSliceIDMapLCU;
-      }
-      pRefID = pRefMapLCU + zRefSU;
-      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
-    }
-
-    //       SGU_TL
-    pbAvail = &(pbAvailBorder[SGU_TL]);
-    if(bPicTBoundary || bPicLBoundary)
-    {
-      *pbAvail = false;
-    }
-    else if (onlyOneSliceInPic)
-    {
-      *pbAvail = true;
-    }
-    else
-    {
-      if(bLCUTBoundary && bLCULBoundary)
-      {
-        zRefSU       = numSUInLCU -1;
-        pRefMapLCU  = pSliceIDMapLCU - ( (numLCUInPicWidth+1)*numSUInLCU);
-      }
-      else if(bLCUTBoundary)
-      {
-        zRefSU       = g_auiRasterToZscan[ rTRefSU- 1];
-        pRefMapLCU  = pTRefMapLCU;
-      }
-      else if(bLCULBoundary)
-      {
-        zRefSU       = g_auiRasterToZscan[ rLRefSU- numSUInLCUWidth ];
-        pRefMapLCU  = pLRefMapLCU;
-      }
-      else //inside LCU
-      {
-        zRefSU       = g_auiRasterToZscan[ rTLSU - numSUInLCUWidth -1];
-        pRefMapLCU  = pSliceIDMapLCU;
-      }
-      pRefID = pRefMapLCU + zRefSU;
-      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
-    }
-
-    //       SGU_TR
-    pbAvail = &(pbAvailBorder[SGU_TR]);
-    if(bPicTBoundary || bPicRBoundary)
-    {
-      *pbAvail = false;
-    }
-    else if (onlyOneSliceInPic)
-    {
-      *pbAvail = true;
-    }
-    else
-    {
-      if(bLCUTBoundary && bLCURBoundary)
-      {
-        zRefSU      = g_auiRasterToZscan[numSUInLCU - numSUInLCUWidth];
-        pRefMapLCU  = pSliceIDMapLCU - ( (numLCUInPicWidth-1)*numSUInLCU);        
-      }
-      else if(bLCUTBoundary)
-      {
-        zRefSU       = g_auiRasterToZscan[ rTRefSU+ widthSU];
-        pRefMapLCU  = pTRefMapLCU;
-      }
-      else if(bLCURBoundary)
-      {
-        zRefSU       = g_auiRasterToZscan[ rRRefSU- numSUInLCUWidth ];
-        pRefMapLCU  = pRRefMapLCU;
-      }
-      else //inside LCU
-      {
-        zRefSU       = g_auiRasterToZscan[ rTLSU - numSUInLCUWidth +widthSU];
-        pRefMapLCU  = pSliceIDMapLCU;
-      }
-      pRefID = pRefMapLCU + zRefSU;
-      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
-    }
-
-    //       SGU_BL
-    pbAvail = &(pbAvailBorder[SGU_BL]);
-    if(bPicBBoundary || bPicLBoundary)
-    {
-      *pbAvail = false;
-    }
-    else if (onlyOneSliceInPic)
-    {
-      *pbAvail = true;
-    }
-    else
-    {
-      if(bLCUBBoundary && bLCULBoundary)
-      {
-        zRefSU      = g_auiRasterToZscan[numSUInLCUWidth - 1];
-        pRefMapLCU  = pSliceIDMapLCU + ( (numLCUInPicWidth-1)*numSUInLCU);        
-      }
-      else if(bLCUBBoundary)
-      {
-        zRefSU       = g_auiRasterToZscan[ rBRefSU - 1];
-        pRefMapLCU  = pBRefMapLCU;
-      }
-      else if(bLCULBoundary)
-      {
-        zRefSU       = g_auiRasterToZscan[ rLRefSU+ heightSU*numSUInLCUWidth ];
-        pRefMapLCU  = pLRefMapLCU;
-      }
-      else //inside LCU
-      {
-        zRefSU       = g_auiRasterToZscan[ rTLSU + heightSU*numSUInLCUWidth -1];
-        pRefMapLCU  = pSliceIDMapLCU;
-      }
-      pRefID = pRefMapLCU + zRefSU;
-      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
-    }
-
-    //       SGU_BR
-    pbAvail = &(pbAvailBorder[SGU_BR]);
-    if(bPicBBoundary || bPicRBoundary)
-    {
-      *pbAvail = false;
-    }
-    else if (onlyOneSliceInPic)
-    {
-      *pbAvail = true;
-    }
-    else
-    {
-      if(bLCUBBoundary && bLCURBoundary)
-      {
-        zRefSU = 0;
-        pRefMapLCU = pSliceIDMapLCU+ ( (numLCUInPicWidth+1)*numSUInLCU);
-      }
-      else if(bLCUBBoundary)
-      {
-        zRefSU      = g_auiRasterToZscan[ rBRefSU + widthSU];
-        pRefMapLCU = pBRefMapLCU;
-      }
-      else if(bLCURBoundary)
-      {
-        zRefSU      = g_auiRasterToZscan[ rRRefSU + (heightSU*numSUInLCUWidth)];
-        pRefMapLCU = pRRefMapLCU;
-      }
-      else //inside LCU
-      {
-        zRefSU      = g_auiRasterToZscan[ rTLSU + (heightSU*numSUInLCUWidth)+ widthSU];
-        pRefMapLCU = pSliceIDMapLCU;
-      }
-      pRefID = pRefMapLCU + zRefSU;
-      *pbAvail = (*pRefID == sliceID)?(true):((*pRefID > sliceID)?(LFCrossSliceBoundary[*pRefID]):(LFCrossSliceBoundary[sliceID]));
-    }
-
-    if(bIndependentTileBoundaryEnabled)
-    {
-      //left LCU boundary
-      if(!bPicLBoundary && bLCULBoundary)
-      {
-        if(bLeftTileBoundary)
-        {
-          pbAvailBorder[SGU_L] = pbAvailBorder[SGU_TL] = pbAvailBorder[SGU_BL] = false;
-        }
-      }
-      //right LCU boundary
-      if(!bPicRBoundary && bLCURBoundary)
-      {
-        if(bRightTileBoundary)
-        {
-          pbAvailBorder[SGU_R] = pbAvailBorder[SGU_TR] = pbAvailBorder[SGU_BR] = false;
-        }
-      }
-      //top LCU boundary
-      if(!bPicTBoundary && bLCUTBoundary)
-      {
-        if(bTopTileBoundary)
-        {
-          pbAvailBorder[SGU_T] = pbAvailBorder[SGU_TL] = pbAvailBorder[SGU_TR] = false;
-        }
-      }
-      //down LCU boundary
-      if(!bPicBBoundary && bLCUBBoundary)
-      {
-        if(bDownTileBoundary)
-        {
-          pbAvailBorder[SGU_B] = pbAvailBorder[SGU_BL] = pbAvailBorder[SGU_BR] = false;
-        }
-      }
-    }
-    rSGU.allBordersAvailable = true;
-    for(Int b=0; b< NUM_SGU_BORDER; b++)
-    {
-      if(pbAvailBorder[b] == false)
-      {
-        rSGU.allBordersAvailable = false;
-        break;
-      }
-    }
-  }
-}
-
-#endif
 
 #if SVC_EXTENSION
@@ -4077,4 +3680,4 @@
   rcMvFieldEnhance.setMvField( cMv, rcMvFieldBase.getRefIdx() );
 }
-#endif
+#endif //SVC_EXTENSION
 //! \}
Index: trunk/source/Lib/TLibCommon/TComDataCU.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComDataCU.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComDataCU.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -55,45 +55,4 @@
 //! \{
 
-#if !HM_CLEANUP_SAO
-// ====================================================================================================================
-// Non-deblocking in-loop filter processing block data structure
-// ====================================================================================================================
-
-/// Non-deblocking filter processing block border tag
-enum NDBFBlockBorderTag
-{
-  SGU_L = 0,
-  SGU_R,
-  SGU_T,
-  SGU_B,
-  SGU_TL,
-  SGU_TR,
-  SGU_BL,
-  SGU_BR,
-  NUM_SGU_BORDER
-};
-
-/// Non-deblocking filter processing block information
-struct NDBFBlockInfo
-{
-  Int   tileID;   //!< tile ID
-  Int   sliceID;  //!< slice ID
-  UInt  startSU;  //!< starting SU z-scan address in LCU
-  UInt  endSU;    //!< ending SU z-scan address in LCU
-  UInt  widthSU;  //!< number of SUs in width
-  UInt  heightSU; //!< number of SUs in height
-  UInt  posX;     //!< top-left X coordinate in picture
-  UInt  posY;     //!< top-left Y coordinate in picture
-  UInt  width;    //!< number of pixels in width
-  UInt  height;   //!< number of pixels in height
-  Bool  isBorderAvailable[NUM_SGU_BORDER];  //!< the border availabilities
-  Bool  allBordersAvailable;
-
-  NDBFBlockInfo():tileID(0), sliceID(0), startSU(0), endSU(0) {} //!< constructor
-  const NDBFBlockInfo& operator= (const NDBFBlockInfo& src);  //!< "=" operator
-};
-#endif
-
-
 // ====================================================================================================================
 // Class definition
@@ -161,8 +120,4 @@
   Pel*          m_pcIPCMSampleCr;     ///< PCM sample buffer (Cr)
 
-#if !HM_CLEANUP_SAO
-  Int*          m_piSliceSUMap;       ///< pointer of slice ID map
-  std::vector<NDBFBlockInfo> m_vNDFBlock;
-#endif
   // -------------------------------------------------------------------------------------------------------------------
   // neighbour access variables
@@ -241,5 +196,5 @@
   
   Void          initCU                ( TComPic* pcPic, UInt uiCUAddr );
-  Void          initEstData           ( UInt uiDepth, Int qp );
+  Void          initEstData           ( UInt uiDepth, Int qp, Bool bTransquantBypass );
   Void          initSubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth, Int qp );
   Void          setOutsideCUPart      ( UInt uiAbsPartIdx, UInt uiDepth );
@@ -392,20 +347,4 @@
   Void          setIPCMFlagSubParts   (Bool bIpcmFlag, UInt uiAbsPartIdx, UInt uiDepth);
 
-#if !HM_CLEANUP_SAO
-  /// get slice ID for SU
-  Int           getSUSliceID          (UInt uiIdx)              {return m_piSliceSUMap[uiIdx];      } 
-
-  /// get the pointer of slice ID map
-  Int*          getSliceSUMap         ()                        {return m_piSliceSUMap;             }
-
-  /// set the pointer of slice ID map
-  Void          setSliceSUMap         (Int *pi)                 {m_piSliceSUMap = pi;               }
-
-  std::vector<NDBFBlockInfo>* getNDBFilterBlocks()      {return &m_vNDFBlock;}
-  Void setNDBFilterBlockBorderAvailability(UInt numLCUInPicWidth, UInt numLCUInPicHeight, UInt numSUInLCUWidth, UInt numSUInLCUHeight, UInt picWidth, UInt picHeight
-                                          ,std::vector<Bool>& LFCrossSliceBoundary
-                                          ,Bool bTopTileBoundary, Bool bDownTileBoundary, Bool bLeftTileBoundary, Bool bRightTileBoundary
-                                          ,Bool bIndependentTileBoundaryEnabled );
-#endif
   // -------------------------------------------------------------------------------------------------------------------
   // member functions for accessing partition information
@@ -442,9 +381,4 @@
   
   Void          compressMV            ();
-  
-#if SVC_EXTENSION
-  Void          setLayerId (UInt layerId) { m_layerId = layerId; }
-  UInt          getLayerId ()               { return m_layerId; }
-#endif
   
   // -------------------------------------------------------------------------------------------------------------------
@@ -490,4 +424,5 @@
   Void          deriveLeftBottomIdxGeneral    ( UInt uiAbsPartIdx, UInt uiPartIdx, UInt& ruiPartIdxLB );
   
+  
   // -------------------------------------------------------------------------------------------------------------------
   // member functions for modes
@@ -497,7 +432,4 @@
   Bool          isSkipped ( UInt uiPartIdx );                                                     ///< SKIP (no residual)
   Bool          isBipredRestriction( UInt puIdx );
-#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
-  Bool          isInterLayerReference(UChar uhInterDir, TComMvField& cMvFieldL0, TComMvField& cMvFieldL1);
-#endif
 
   // -------------------------------------------------------------------------------------------------------------------
@@ -525,12 +457,19 @@
 
 #if SVC_EXTENSION
+  Void          setLayerId (UInt layerId) { m_layerId = layerId; }
+  UInt          getLayerId ()               { return m_layerId; }
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Bool          isInterLayerReference(UChar uhInterDir, TComMvField& cMvFieldL0, TComMvField& cMvFieldL1);
+#endif
 #if FAST_INTRA_SHVC
   Int           reduceSetOfIntraModes              (  UInt   uiAbsPartIdx, Int* uiIntraDirPred, Int &fullSetOfModes );
 #endif
-
 #if REF_IDX_ME_ZEROMV
   Bool xCheckZeroMVILRMerge(UChar uhInterDir, TComMvField& cMvFieldL0, TComMvField& cMvFieldL1);
   Bool xCheckZeroMVILRMvdL1Zero(Int iRefList, Int iRefIdx, Int MvpIdx);
 #endif
+  TComDataCU*   getBaseColCU( UInt refLayerIdc, UInt uiCuAbsPartIdx, UInt &uiCUAddrBase, UInt &uiAbsPartIdxBase, Int iMotionMapping = 0 );
+  TComDataCU*   getBaseColCU( UInt refLayerIdc, UInt uiPelX, UInt uiPelY, UInt &uiCUAddrBase, UInt &uiAbsPartIdxBase, Int iMotionMapping = 0 );
+  Void          scaleBaseMV( UInt refLayerIdc, TComMvField& rcMvFieldEnhance, TComMvField& rcMvFieldBase );
 #endif
 
@@ -546,9 +485,4 @@
   UInt          getCoefScanIdx(UInt uiAbsPartIdx, UInt uiWidth, Bool bIsLuma, Bool bIsIntra);
 
-#if SVC_EXTENSION
-  TComDataCU*   getBaseColCU( UInt refLayerIdc, UInt uiCuAbsPartIdx, UInt &uiCUAddrBase, UInt &uiAbsPartIdxBase, Int iMotionMapping = 0 );
-  TComDataCU*   getBaseColCU( UInt refLayerIdc, UInt uiPelX, UInt uiPelY, UInt &uiCUAddrBase, UInt &uiAbsPartIdxBase, Int iMotionMapping = 0 );
-  Void          scaleBaseMV( UInt refLayerIdc, TComMvField& rcMvFieldEnhance, TComMvField& rcMvFieldBase );
-#endif
 };
 
Index: trunk/source/Lib/TLibCommon/TComInterpolationFilter.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComInterpolationFilter.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComList.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComList.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComList.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComLoopFilter.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComLoopFilter.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComLoopFilter.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComLoopFilter.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComMotionInfo.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComMotionInfo.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComMotionInfo.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComMotionInfo.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComMv.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComMv.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComMv.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComPattern.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComPattern.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComPattern.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComPattern.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComPattern.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComPattern.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComPic.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComPic.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComPic.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -48,7 +48,4 @@
 TComPic::TComPic()
 : m_uiTLayer                              (0)
-#if SVC_EXTENSION
-, m_layerId( 0 )
-#endif
 , m_bUsedByCurr                           (false)
 , m_bIsLongTerm                           (false)
@@ -59,13 +56,8 @@
 , m_bNeededForOutput                      (false)
 , m_uiCurrSliceIdx                        (0)
-#if !HM_CLEANUP_SAO
-, m_pSliceSUMap                           (NULL)
-, m_pbValidSlice                          (NULL)
-, m_sliceGranularityForNDBFilter          (0)
-, m_bIndependentSliceBoundaryForNDBFilter (false)
-, m_bIndependentTileBoundaryForNDBFilter  (false)
-, m_pNDBFilterYuvTmp                      (NULL)
-#endif
 , m_bCheckLTMSB                           (false)
+#if SVC_EXTENSION
+, m_layerId( 0 )
+#endif
 {
 #if SVC_EXTENSION
@@ -214,5 +206,5 @@
   } 
 }
-#if HM_CLEANUP_SAO
+
 Bool  TComPic::getSAOMergeAvailability(Int currAddr, Int mergeAddr)
 {
@@ -221,341 +213,4 @@
   return (mergeCtbInSliceSeg && mergeCtbInTile);
 }
-#else
-/** Create non-deblocked filter information
- * \param pSliceStartAddress array for storing slice start addresses
- * \param numSlices number of slices in picture
- * \param sliceGranularityDepth slice granularity 
- * \param bNDBFilterCrossSliceBoundary cross-slice-boundary in-loop filtering; true for "cross".
- * \param numTiles number of tiles in picture
- * \param bNDBFilterCrossTileBoundary cross-tile-boundary in-loop filtering; true for "cross".
- */
-Void TComPic::createNonDBFilterInfo(std::vector<Int> sliceStartAddress, Int sliceGranularityDepth
-                                    ,std::vector<Bool>* LFCrossSliceBoundary
-                                    ,Int numTiles
-                                    ,Bool bNDBFilterCrossTileBoundary)
-{
-  UInt maxNumSUInLCU = getNumPartInCU();
-  UInt numLCUInPic   = getNumCUsInFrame();
-#if REPN_FORMAT_IN_VPS
-  UInt picWidth      = getSlice(0)->getPicWidthInLumaSamples();
-  UInt picHeight     = getSlice(0)->getPicHeightInLumaSamples();
-#else
-  UInt picWidth      = getSlice(0)->getSPS()->getPicWidthInLumaSamples();
-  UInt picHeight     = getSlice(0)->getSPS()->getPicHeightInLumaSamples();
-#endif
-  Int  numLCUsInPicWidth = getFrameWidthInCU();
-  Int  numLCUsInPicHeight= getFrameHeightInCU();
-  UInt maxNumSUInLCUWidth = getNumPartInWidth();
-  UInt maxNumSUInLCUHeight= getNumPartInHeight();
-  Int  numSlices = (Int) sliceStartAddress.size() - 1;
-  m_bIndependentSliceBoundaryForNDBFilter = false;
-  if(numSlices > 1)
-  {
-    for(Int s=0; s< numSlices; s++)
-    {
-      if((*LFCrossSliceBoundary)[s] == false)
-      {
-        m_bIndependentSliceBoundaryForNDBFilter = true;
-      }
-    }
-  }
-  m_sliceGranularityForNDBFilter = sliceGranularityDepth;
-  m_bIndependentTileBoundaryForNDBFilter  = (bNDBFilterCrossTileBoundary)?(false) :((numTiles > 1)?(true):(false));
-
-  m_pbValidSlice = new Bool[numSlices];
-  for(Int s=0; s< numSlices; s++)
-  {
-    m_pbValidSlice[s] = true;
-  }
-  m_pSliceSUMap = new Int[maxNumSUInLCU * numLCUInPic];
-
-  //initialization
-  for(UInt i=0; i< (maxNumSUInLCU * numLCUInPic); i++ )
-  {
-    m_pSliceSUMap[i] = -1;
-  }
-  for( UInt CUAddr = 0; CUAddr < numLCUInPic ; CUAddr++ )
-  {
-    TComDataCU* pcCU = getCU( CUAddr );
-    pcCU->setSliceSUMap(m_pSliceSUMap + (CUAddr* maxNumSUInLCU)); 
-    pcCU->getNDBFilterBlocks()->clear();
-  }
-  m_vSliceCUDataLink.clear();
-
-  m_vSliceCUDataLink.resize(numSlices);
-
-  UInt startAddr, endAddr, firstCUInStartLCU, startLCU, endLCU, lastCUInEndLCU, uiAddr;
-  UInt LPelX, TPelY, LCUX, LCUY;
-  UInt currSU;
-  UInt startSU, endSU;
-
-  for(Int s=0; s< numSlices; s++)
-  {
-    //1st step: decide the real start address
-    startAddr = sliceStartAddress[s];
-    endAddr   = sliceStartAddress[s+1] -1;
-
-    startLCU            = startAddr / maxNumSUInLCU;
-    firstCUInStartLCU   = startAddr % maxNumSUInLCU;
-
-    endLCU              = endAddr   / maxNumSUInLCU;
-    lastCUInEndLCU      = endAddr   % maxNumSUInLCU;   
-
-    uiAddr = m_apcPicSym->getCUOrderMap(startLCU);
-
-    LCUX      = getCU(uiAddr)->getCUPelX();
-    LCUY      = getCU(uiAddr)->getCUPelY();
-    LPelX     = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[firstCUInStartLCU] ];
-    TPelY     = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[firstCUInStartLCU] ];
-    currSU    = firstCUInStartLCU;
-
-    Bool bMoveToNextLCU = false;
-    Bool bSliceInOneLCU = (startLCU == endLCU);
-
-    while(!( LPelX < picWidth ) || !( TPelY < picHeight ))
-    {
-      currSU ++;
-
-      if(bSliceInOneLCU)
-      {
-        if(currSU > lastCUInEndLCU)
-        {
-          m_pbValidSlice[s] = false;
-          break;
-        }
-      }
-
-      if(currSU >= maxNumSUInLCU )
-      {
-        bMoveToNextLCU = true;
-        break;
-      }
-
-      LPelX = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[currSU] ];
-      TPelY = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[currSU] ];
-
-    }
-
-
-    if(!m_pbValidSlice[s])
-    {
-      continue;
-    }
-
-    if(currSU != firstCUInStartLCU)
-    {
-      if(!bMoveToNextLCU)
-      {
-        firstCUInStartLCU = currSU;
-      }
-      else
-      {
-        startLCU++;
-        firstCUInStartLCU = 0;
-        assert( startLCU < getNumCUsInFrame());
-      }
-      assert(startLCU*maxNumSUInLCU + firstCUInStartLCU < endAddr);
-    }
-
-
-    //2nd step: assign NonDBFilterInfo to each processing block
-    for(UInt i= startLCU; i <= endLCU; i++)
-    {
-      startSU = (i == startLCU)?(firstCUInStartLCU):(0);
-      endSU   = (i == endLCU  )?(lastCUInEndLCU   ):(maxNumSUInLCU -1);
-
-      uiAddr = m_apcPicSym->getCUOrderMap(i);
-      Int iTileID= m_apcPicSym->getTileIdxMap(uiAddr);
-
-      TComDataCU* pcCU = getCU(uiAddr);
-      m_vSliceCUDataLink[s].push_back(pcCU);
-
-      createNonDBFilterInfoLCU(iTileID, s, pcCU, startSU, endSU, m_sliceGranularityForNDBFilter, picWidth, picHeight);
-    }
-  }
-
-  //step 3: border availability
-  for(Int s=0; s< numSlices; s++)
-  {
-    if(!m_pbValidSlice[s])
-    {
-      continue;
-    }
-
-    for(Int i=0; i< m_vSliceCUDataLink[s].size(); i++)
-    {
-      TComDataCU* pcCU = m_vSliceCUDataLink[s][i];
-      uiAddr = pcCU->getAddr();
-
-      if(pcCU->getPic()==0)
-      {
-        continue;
-      }
-      Int iTileID= m_apcPicSym->getTileIdxMap(uiAddr);
-      Bool bTopTileBoundary = false, bDownTileBoundary= false, bLeftTileBoundary= false, bRightTileBoundary= false;
-
-      if(m_bIndependentTileBoundaryForNDBFilter)
-      {
-        //left
-        if( uiAddr % numLCUsInPicWidth != 0)
-        {
-          bLeftTileBoundary = ( m_apcPicSym->getTileIdxMap(uiAddr -1) != iTileID )?true:false;
-        }
-        //right
-        if( (uiAddr % numLCUsInPicWidth) != (numLCUsInPicWidth -1) )
-        {
-          bRightTileBoundary = ( m_apcPicSym->getTileIdxMap(uiAddr +1) != iTileID)?true:false;
-        }
-        //top
-        if( uiAddr >= numLCUsInPicWidth)
-        {
-          bTopTileBoundary = (m_apcPicSym->getTileIdxMap(uiAddr - numLCUsInPicWidth) !=  iTileID )?true:false;
-        }
-        //down
-        if( uiAddr + numLCUsInPicWidth < numLCUInPic )
-        {
-          bDownTileBoundary = (m_apcPicSym->getTileIdxMap(uiAddr + numLCUsInPicWidth) != iTileID)?true:false;
-        }
-
-      }
-
-      pcCU->setNDBFilterBlockBorderAvailability(numLCUsInPicWidth, numLCUsInPicHeight, maxNumSUInLCUWidth, maxNumSUInLCUHeight,picWidth, picHeight
-        , *LFCrossSliceBoundary
-        ,bTopTileBoundary, bDownTileBoundary, bLeftTileBoundary, bRightTileBoundary
-        ,m_bIndependentTileBoundaryForNDBFilter);
-
-    }
-
-  }
-
-  if( m_bIndependentSliceBoundaryForNDBFilter || m_bIndependentTileBoundaryForNDBFilter)
-  {
-    m_pNDBFilterYuvTmp = new TComPicYuv();
-#if AUXILIARY_PICTURES
-    m_pNDBFilterYuvTmp->create(picWidth, picHeight, getChromaFormat(), g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
-#else
-    m_pNDBFilterYuvTmp->create(picWidth, picHeight, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth);
-#endif
-
-  }
-
-}
-
-/** Create non-deblocked filter information for LCU
- * \param tileID tile index
- * \param sliceID slice index
- * \param pcCU CU data pointer
- * \param startSU start SU index in LCU
- * \param endSU end SU index in LCU
- * \param sliceGranularyDepth slice granularity
- * \param picWidth picture width
- * \param picHeight picture height
- */
-Void TComPic::createNonDBFilterInfoLCU(Int tileID, Int sliceID, TComDataCU* pcCU, UInt startSU, UInt endSU, Int sliceGranularyDepth, UInt picWidth, UInt picHeight)
-{
-  UInt LCUX          = pcCU->getCUPelX();
-  UInt LCUY          = pcCU->getCUPelY();
-  Int* pCUSliceMap    = pcCU->getSliceSUMap();
-  UInt maxNumSUInLCU = getNumPartInCU();
-  UInt maxNumSUInSGU = maxNumSUInLCU >> (sliceGranularyDepth << 1);
-  UInt maxNumSUInLCUWidth = getNumPartInWidth();
-  UInt LPelX, TPelY;
-  UInt currSU;
-
-
-  //get the number of valid NBFilterBLock
-  currSU   = startSU;
-  while(currSU <= endSU)
-  {
-    LPelX = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[currSU] ];
-    TPelY = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[currSU] ];
-
-    while(!( LPelX < picWidth ) || !( TPelY < picHeight ))
-    {
-      currSU += maxNumSUInSGU;
-      if(currSU >= maxNumSUInLCU || currSU > endSU)
-      {
-        break;
-      }
-      LPelX = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[currSU] ];
-      TPelY = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[currSU] ];
-    }
-
-    if(currSU >= maxNumSUInLCU || currSU > endSU)
-    {
-      break;
-    }
-
-    NDBFBlockInfo NDBFBlock;
-
-    NDBFBlock.tileID  = tileID;
-    NDBFBlock.sliceID = sliceID;
-    NDBFBlock.posY    = TPelY;
-    NDBFBlock.posX    = LPelX;
-    NDBFBlock.startSU = currSU;
-
-    UInt uiLastValidSU  = currSU;
-    UInt uiIdx, uiLPelX_su, uiTPelY_su;
-    for(uiIdx = currSU; uiIdx < currSU + maxNumSUInSGU; uiIdx++)
-    {
-      if(uiIdx > endSU)
-      {
-        break;        
-      }
-      uiLPelX_su   = LCUX + g_auiRasterToPelX[ g_auiZscanToRaster[uiIdx] ];
-      uiTPelY_su   = LCUY + g_auiRasterToPelY[ g_auiZscanToRaster[uiIdx] ];
-      if( !(uiLPelX_su < picWidth ) || !( uiTPelY_su < picHeight ))
-      {
-        continue;
-      }
-      pCUSliceMap[uiIdx] = sliceID;
-      uiLastValidSU = uiIdx;
-    }
-    NDBFBlock.endSU = uiLastValidSU;
-
-    UInt rTLSU = g_auiZscanToRaster[ NDBFBlock.startSU ];
-    UInt rBRSU = g_auiZscanToRaster[ NDBFBlock.endSU   ];
-    NDBFBlock.widthSU  = (rBRSU % maxNumSUInLCUWidth) - (rTLSU % maxNumSUInLCUWidth)+ 1;
-    NDBFBlock.heightSU = (UInt)(rBRSU / maxNumSUInLCUWidth) - (UInt)(rTLSU / maxNumSUInLCUWidth)+ 1;
-    NDBFBlock.width    = NDBFBlock.widthSU  * getMinCUWidth();
-    NDBFBlock.height   = NDBFBlock.heightSU * getMinCUHeight();
-
-    pcCU->getNDBFilterBlocks()->push_back(NDBFBlock);
-
-    currSU += maxNumSUInSGU;
-  }
-
-}
-
-/** destroy non-deblocked filter information for LCU
- */
-Void TComPic::destroyNonDBFilterInfo()
-{
-  if(m_pbValidSlice != NULL)
-  {
-    delete[] m_pbValidSlice;
-    m_pbValidSlice = NULL;
-  }
-
-  if(m_pSliceSUMap != NULL)
-  {
-    delete[] m_pSliceSUMap;
-    m_pSliceSUMap = NULL;
-  }
-  for( UInt CUAddr = 0; CUAddr < getNumCUsInFrame() ; CUAddr++ )
-  {
-    TComDataCU* pcCU = getCU( CUAddr );
-    pcCU->getNDBFilterBlocks()->clear();
-  }
-
-  if( m_bIndependentSliceBoundaryForNDBFilter || m_bIndependentTileBoundaryForNDBFilter)
-  {
-    m_pNDBFilterYuvTmp->destroy();
-    delete m_pNDBFilterYuvTmp;
-    m_pNDBFilterYuvTmp = NULL;
-  }
-
-}
-#endif
 
 #if SVC_EXTENSION
Index: trunk/source/Lib/TLibCommon/TComPic.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComPic.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComPic.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -61,7 +61,4 @@
 private:
   UInt                  m_uiTLayer;               //  Temporal layer
-#if SVC_EXTENSION
-  UInt                  m_layerId;              //  Layer ID
-#endif
   Bool                  m_bUsedByCurr;            //  Used by current picture
   Bool                  m_bIsLongTerm;            //  IS long term picture
@@ -75,12 +72,4 @@
   Bool                  m_bNeededForOutput;
   UInt                  m_uiCurrSliceIdx;         // Index of current slice
-#if !HM_CLEANUP_SAO
-  Int*                  m_pSliceSUMap;
-  Bool*                 m_pbValidSlice;
-  Int                   m_sliceGranularityForNDBFilter;
-  Bool                  m_bIndependentSliceBoundaryForNDBFilter;
-  Bool                  m_bIndependentTileBoundaryForNDBFilter;
-  TComPicYuv*           m_pNDBFilterYuvTmp;    //!< temporary picture buffer when non-cross slice/tile boundary in-loop filtering is enabled
-#endif
   Bool                  m_bCheckLTMSB;
   
@@ -96,4 +85,5 @@
   SEIMessages  m_SEIs; ///< Any SEI messages that have been received.  If !NULL we own the object.
 #if SVC_EXTENSION
+  UInt                  m_layerId;              //  Layer ID
   Bool                  m_bSpatialEnhLayer[MAX_LAYERS];       // whether current layer is a spatial enhancement layer,
   TComPicYuv*           m_pcFullPelBaseRec[MAX_LAYERS];    // upsampled base layer recontruction for difference domain inter prediction
@@ -125,24 +115,4 @@
   UInt          getTLayer()                { return m_uiTLayer;   }
   Void          setTLayer( UInt uiTLayer ) { m_uiTLayer = uiTLayer; }
-#if SVC_EXTENSION
-  Void          setLayerId (UInt layerId) { m_layerId = layerId; }
-  UInt          getLayerId ()               { return m_layerId; }
-  Bool          isSpatialEnhLayer(UInt refLayerIdc)             { return m_bSpatialEnhLayer[refLayerIdc]; }
-  Void          setSpatialEnhLayerFlag (UInt refLayerIdc, Bool b) { m_bSpatialEnhLayer[refLayerIdc] = b; }
-  Void          setFullPelBaseRec   (UInt refLayerIdc, TComPicYuv* p) { m_pcFullPelBaseRec[refLayerIdc] = p; }
-  TComPicYuv*   getFullPelBaseRec   (UInt refLayerIdc)  { return  m_pcFullPelBaseRec[refLayerIdc];  }
-#endif
-#if REF_IDX_ME_ZEROMV || ENCODER_FAST_MODE || REF_IDX_MFM
-  Bool          isILR( UInt currLayerId )   { return ( getIsLongTerm() && m_layerId < currLayerId ); }
-#endif
-
-#if REF_IDX_MFM
-  Void          copyUpsampledMvField  ( UInt refLayerIdc, TComPic* pcPicBase );
-  Void          initUpsampledMvField  ();
-#endif
-#if MFM_ENCCONSTRAINT
-  Bool          checkSameRefInfo();
-#endif
-
   Bool          getUsedByCurr()             { return m_bUsedByCurr; }
   Void          setUsedByCurr( Bool bUsed ) { m_bUsedByCurr = bUsed; }
@@ -178,7 +148,4 @@
   
   Int           getStride()           { return m_apcPicYuv[1]->getStride(); }
-#if AUXILIARY_PICTURES
-  ChromaFormat  getChromaFormat() const { return m_apcPicYuv[1]->getChromaFormat(); }
-#endif
   Int           getCStride()          { return m_apcPicYuv[1]->getCStride(); }
   
@@ -201,20 +168,5 @@
   Window&       getDefDisplayWindow()   { return m_defaultDisplayWindow; }
 
-#if HM_CLEANUP_SAO
   Bool          getSAOMergeAvailability(Int currAddr, Int mergeAddr);
-#else
-  Void          createNonDBFilterInfo   (std::vector<Int> sliceStartAddress, Int sliceGranularityDepth
-                                        ,std::vector<Bool>* LFCrossSliceBoundary
-                                        ,Int  numTiles = 1
-                                        ,Bool bNDBFilterCrossTileBoundary = true);
-  Void          createNonDBFilterInfoLCU(Int tileID, Int sliceID, TComDataCU* pcCU, UInt startSU, UInt endSU, Int sliceGranularyDepth, UInt picWidth, UInt picHeight);
-  Void          destroyNonDBFilterInfo();
-
-  Bool          getValidSlice                                  (Int sliceID)  {return m_pbValidSlice[sliceID];}
-  Bool          getIndependentSliceBoundaryForNDBFilter        ()             {return m_bIndependentSliceBoundaryForNDBFilter;}
-  Bool          getIndependentTileBoundaryForNDBFilter         ()             {return m_bIndependentTileBoundaryForNDBFilter; }
-  TComPicYuv*   getYuvPicBufferForIndependentBoundaryProcessing()             {return m_pNDBFilterYuvTmp;}
-  std::vector<TComDataCU*>& getOneSliceCUDataForNDBFilter      (Int sliceID) { return m_vSliceCUDataLink[sliceID];}
-#endif
 
   /* field coding parameters*/
@@ -239,4 +191,23 @@
 
 #if SVC_EXTENSION
+  Void          setLayerId (UInt layerId) { m_layerId = layerId; }
+  UInt          getLayerId ()               { return m_layerId; }
+  Bool          isSpatialEnhLayer(UInt refLayerIdc)             { return m_bSpatialEnhLayer[refLayerIdc]; }
+  Void          setSpatialEnhLayerFlag (UInt refLayerIdc, Bool b) { m_bSpatialEnhLayer[refLayerIdc] = b; }
+  Void          setFullPelBaseRec   (UInt refLayerIdc, TComPicYuv* p) { m_pcFullPelBaseRec[refLayerIdc] = p; }
+  TComPicYuv*   getFullPelBaseRec   (UInt refLayerIdc)  { return  m_pcFullPelBaseRec[refLayerIdc];  }
+#if REF_IDX_ME_ZEROMV || ENCODER_FAST_MODE || REF_IDX_MFM
+  Bool          isILR( UInt currLayerId )   { return ( getIsLongTerm() && m_layerId < currLayerId ); }
+#endif
+#if REF_IDX_MFM
+  Void          copyUpsampledMvField  ( UInt refLayerIdc, TComPic* pcPicBase );
+  Void          initUpsampledMvField  ();
+#endif
+#if MFM_ENCCONSTRAINT
+  Bool          checkSameRefInfo();
+#endif
+#if AUXILIARY_PICTURES
+  ChromaFormat  getChromaFormat() const { return m_apcPicYuv[1]->getChromaFormat(); }
+#endif
   Void  copyUpsampledPictureYuv(TComPicYuv*   pcPicYuvIn, TComPicYuv*   pcPicYuvOut); 
 #if AVC_SYNTAX
Index: trunk/source/Lib/TLibCommon/TComPicSym.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComPicSym.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComPicSym.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -67,7 +67,5 @@
 ,m_puiTileIdxMap(NULL)
 ,m_puiInverseCUOrderMap(NULL)
-#if HM_CLEANUP_SAO
 ,m_saoBlkParams(NULL)
-#endif
 {};
 
@@ -131,9 +129,5 @@
   }
 
-#if HM_CLEANUP_SAO
   m_saoBlkParams = new SAOBlkParam[m_uiNumCUsInFrame];
-#else
-  m_saoParam = NULL;
-#endif
 }
 
@@ -191,17 +185,8 @@
   m_puiInverseCUOrderMap = NULL;
   
-#if HM_CLEANUP_SAO
   if(m_saoBlkParams)
   {
     delete[] m_saoBlkParams; m_saoBlkParams = NULL;
   }
-#else
-  if (m_saoParam)
-  {
-    TComSampleAdaptiveOffset::freeSaoParam(m_saoParam);
-    delete m_saoParam;
-    m_saoParam = NULL;
-  }
-#endif
 }
 
@@ -347,6 +332,4 @@
 }
 
-
-#if HM_CLEANUP_SAO
 Void TComPicSym::deriveLoopFilterBoundaryAvailibility(Int ctu,
                                                       Bool& isLeftAvail,
@@ -419,10 +402,10 @@
       if(ctuAboveRigtht != NULL)
       {
-        Int curSliceStartTS  = getCUOrderMap(ctuCurr->getSlice()->getSliceCurStartCUAddr()/m_uiNumPartitions);
-        Int aboveRigthtSliceStartTS = getCUOrderMap(ctuAboveRigtht->getSlice()->getSliceCurStartCUAddr()/m_uiNumPartitions);
-
-        isAboveRightAvail = (curSliceStartTS == aboveRigthtSliceStartTS)?(true):
+        Int curSliceStartEncOrder  = ctuCurr->getSlice()->getSliceCurStartCUAddr();
+        Int aboveRigthtSliceStartEncOrder = ctuAboveRigtht->getSlice()->getSliceCurStartCUAddr();
+
+        isAboveRightAvail = (curSliceStartEncOrder == aboveRigthtSliceStartEncOrder)?(true):
           (
-          (curSliceStartTS > aboveRigthtSliceStartTS)?(ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag())
+          (curSliceStartEncOrder > aboveRigthtSliceStartEncOrder)?(ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag())
           :(ctuAboveRigtht->getSlice()->getLFCrossSliceBoundaryFlag())
           );          
@@ -431,10 +414,10 @@
       if(ctuBelowLeft != NULL)
       {
-        Int curSliceStartTS       = getCUOrderMap(ctuCurr->getSlice()->getSliceCurStartCUAddr()/m_uiNumPartitions);
-        Int belowLeftSliceStartTS = getCUOrderMap(ctuBelowLeft->getSlice()->getSliceCurStartCUAddr()/m_uiNumPartitions);
-
-        isBelowLeftAvail = (curSliceStartTS == belowLeftSliceStartTS)?(true):
+        Int curSliceStartEncOrder  = ctuCurr->getSlice()->getSliceCurStartCUAddr();
+        Int belowLeftSliceStartEncOrder = ctuBelowLeft->getSlice()->getSliceCurStartCUAddr();
+
+        isBelowLeftAvail = (curSliceStartEncOrder == belowLeftSliceStartEncOrder)?(true):
           (
-          (curSliceStartTS > belowLeftSliceStartTS)?(ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag())
+          (curSliceStartEncOrder > belowLeftSliceStartEncOrder)?(ctuCurr->getSlice()->getLFCrossSliceBoundaryFlag())
           :(ctuBelowLeft->getSlice()->getLFCrossSliceBoundaryFlag())
           );
@@ -456,11 +439,4 @@
 
 }
-#else
-Void TComPicSym::allocSaoParam(TComSampleAdaptiveOffset *sao)
-{
-  m_saoParam = new SAOParam;
-  sao->allocSaoParam(m_saoParam);
-}
-#endif
 
 TComTile::TComTile()
Index: trunk/source/Lib/TLibCommon/TComPicSym.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComPicSym.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComPicSym.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -105,4 +105,9 @@
   UInt*         m_puiCUOrderMap;       //the map of LCU raster scan address relative to LCU encoding order 
   UInt*         m_puiTileIdxMap;       //the map of the tile index relative to LCU raster scan address 
+  UInt*         m_puiInverseCUOrderMap;
+
+  SAOBlkParam *m_saoBlkParams;
+
+#if SVC_EXTENSION
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
   Int*          m_piTileSetIdxMap;     //the map of the tile set index relative to LCU raster scan address
@@ -110,10 +115,4 @@
   Bool*         m_pbSkippedTileSetFlag;
 #endif
-  UInt*         m_puiInverseCUOrderMap;
-
-#if HM_CLEANUP_SAO
-  SAOBlkParam *m_saoBlkParams;
-#else
-  SAOParam *m_saoParam;
 #endif
 
@@ -130,15 +129,4 @@
   UInt        getNumberOfCUsInFrame()   { return m_uiNumCUsInFrame;  }
   TComDataCU*&  getCU( UInt uiCUAddr )  { return m_apcTComDataCU[uiCUAddr];     }
-  
-#if LAYER_CTB
-  UInt        getMaxCUWidth()           { return m_uiMaxCUWidth;                }
-  UInt        getMaxCUHeight()          { return m_uiMaxCUHeight;               }
-#endif
-
-#if AVC_SYNTAX
-  UInt        getMaxCUWidth()           { return m_uiMaxCUWidth;                }
-  UInt        getMaxCUHeight()          { return m_uiMaxCUHeight;               }
-  UInt        getMaxDepth()             { return m_uhTotalDepth;               }
-#endif
   
   Void        setSlice(TComSlice* p, UInt i) { m_apcTComSlice[i] = p;           }
@@ -158,4 +146,24 @@
   UInt         getCUOrderMap( Int encCUOrder )                       { return *(m_puiCUOrderMap + (encCUOrder>=m_uiNumCUsInFrame ? m_uiNumCUsInFrame : encCUOrder)); }
   UInt         getTileIdxMap( Int i )                                { return *(m_puiTileIdxMap + i); }
+  Void         setInverseCUOrderMap( Int cuAddr, Int encCUOrder )    { *(m_puiInverseCUOrderMap + cuAddr) = encCUOrder; }
+  UInt         getInverseCUOrderMap( Int cuAddr )                    { return *(m_puiInverseCUOrderMap + (cuAddr>=m_uiNumCUsInFrame ? m_uiNumCUsInFrame : cuAddr)); }
+  UInt         getPicSCUEncOrder( UInt SCUAddr );
+  UInt         getPicSCUAddr( UInt SCUEncOrder );
+  Void         xCreateTComTileArray();
+  Void         xInitTiles();
+  UInt         xCalculateNxtCUAddr( UInt uiCurrCUAddr );
+  SAOBlkParam* getSAOBlkParam() { return m_saoBlkParams;}
+  Void deriveLoopFilterBoundaryAvailibility(Int ctu, Bool& isLeftAvail,Bool& isRightAvail,Bool& isAboveAvail,Bool& isBelowAvail,Bool& isAboveLeftAvail,Bool& isAboveRightAvail,Bool& isBelowLeftAvail,Bool& isBelowRightAvail);
+
+#if SVC_EXTENSION
+#if LAYER_CTB
+  UInt        getMaxCUWidth()           { return m_uiMaxCUWidth;                }
+  UInt        getMaxCUHeight()          { return m_uiMaxCUHeight;               }
+#endif
+#if AVC_SYNTAX
+  UInt        getMaxCUWidth()           { return m_uiMaxCUWidth;                }
+  UInt        getMaxCUHeight()          { return m_uiMaxCUHeight;               }
+  UInt        getMaxDepth()             { return m_uhTotalDepth;               }
+#endif
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
   Void         setTileSetIdxMap( Int i, Int tileSetIdx, UChar setType, Bool skipFlag )
@@ -169,20 +177,5 @@
   Bool         getSkippedTileSetFlag( Int i )                        { return *(m_pbSkippedTileSetFlag + i); }
 #endif
-  Void         setInverseCUOrderMap( Int cuAddr, Int encCUOrder )    { *(m_puiInverseCUOrderMap + cuAddr) = encCUOrder; }
-  UInt         getInverseCUOrderMap( Int cuAddr )                    { return *(m_puiInverseCUOrderMap + (cuAddr>=m_uiNumCUsInFrame ? m_uiNumCUsInFrame : cuAddr)); }
-  UInt         getPicSCUEncOrder( UInt SCUAddr );
-  UInt         getPicSCUAddr( UInt SCUEncOrder );
-  Void         xCreateTComTileArray();
-  Void         xInitTiles();
-  UInt         xCalculateNxtCUAddr( UInt uiCurrCUAddr );
-#if HM_CLEANUP_SAO
-  SAOBlkParam* getSAOBlkParam() { return m_saoBlkParams;}
-  Void deriveLoopFilterBoundaryAvailibility(Int ctu, Bool& isLeftAvail,Bool& isRightAvail,Bool& isAboveAvail,Bool& isBelowAvail,Bool& isAboveLeftAvail,Bool& isAboveRightAvail,Bool& isBelowLeftAvail,Bool& isBelowRightAvail);
-#else
-  Void allocSaoParam(TComSampleAdaptiveOffset *sao);
-  SAOParam *getSaoParam() { return m_saoParam; }
-#endif
-
-
+#endif //SVC_EXTENSION
 };// END CLASS DEFINITION TComPicSym
 
Index: trunk/source/Lib/TLibCommon/TComPicYuv.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComPicYuv.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComPicYuv.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComPicYuv.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -75,7 +75,4 @@
   Int   m_iPicWidth;            ///< Width of picture
   Int   m_iPicHeight;           ///< Height of picture
-#if AUXILIARY_PICTURES
-  ChromaFormat m_chromaFormatIDC; ////< Chroma Format
-#endif
   
   Int   m_iCuWidth;             ///< Width of Coding Unit (CU)
@@ -91,13 +88,17 @@
   Int   m_iChromaMarginY;
   
+  Bool  m_bIsBorderExtended;
+
+#if SVC_EXTENSION
+#if AUXILIARY_PICTURES
+  ChromaFormat m_chromaFormatIDC; ////< Chroma Format
+#endif
 #if SVC_UPSAMPLING
   Window  m_conformanceWindow;
 #endif
-
 #if M0040_ADAPTIVE_RESOLUTION_CHANGE
   Bool    m_isReconstructed;
 #endif
-
-  Bool  m_bIsBorderExtended;
+#endif //SVC_EXTENSION
   
 protected:
@@ -136,11 +137,4 @@
   Int   getWidth    ()     { return  m_iPicWidth;    }
   Int   getHeight   ()     { return  m_iPicHeight;   }
-#if AUXILIARY_PICTURES
-  ChromaFormat  getChromaFormat   ()                     const { return m_chromaFormatIDC; }
-#endif
-  
-#if SVC_EXTENSION
-  Void   setHeight   ( Int iPicHeight )     { m_iPicHeight = iPicHeight; }
-#endif
 
   Int   getStride   ()     { return (m_iPicWidth     ) + (m_iLumaMarginX  <<1); }
@@ -172,9 +166,4 @@
   Pel*  getCrAddr   ( Int iCuAddr, Int uiAbsZorderIdx ) { return m_piPicOrgV + m_cuOffsetC[iCuAddr] + m_buOffsetC[g_auiZscanToRaster[uiAbsZorderIdx]]; }
   
-#if SVC_UPSAMPLING
-  Window& getConformanceWindow()                           { return  m_conformanceWindow;             }
-  Void    setConformanceWindow(Window& conformanceWindow ) { m_conformanceWindow = conformanceWindow; }
-#endif
-
   // ------------------------------------------------------------------------------------------------
   //  Miscellaneous
@@ -193,15 +182,23 @@
   Void  dump (Char* pFileName, Bool bAdd = false);
 
+  // Set border extension flag
+  Void  setBorderExtension(Bool b) { m_bIsBorderExtended = b; }
+  
+#if SVC_EXTENSION
+  Void   setHeight   ( Int iPicHeight )     { m_iPicHeight = iPicHeight; }
+#if SVC_UPSAMPLING
+  Window& getConformanceWindow()                           { return  m_conformanceWindow;             }
+  Void    setConformanceWindow(Window& conformanceWindow ) { m_conformanceWindow = conformanceWindow; }
+#endif
 #if M0040_ADAPTIVE_RESOLUTION_CHANGE
   Void  setReconstructed(Bool x) { m_isReconstructed = x;    }
   Bool  isReconstructed()        { return m_isReconstructed; }
 #endif
-
 #if AUXILIARY_PICTURES
+  ChromaFormat  getChromaFormat   ()                     const { return m_chromaFormatIDC; }
   Void convertToMonochrome();
 #endif
-
-  // Set border extension flag
-  Void  setBorderExtension(Bool b) { m_bIsBorderExtended = b; }
+#endif //SVC_EXTENSION
+
 };// END CLASS DEFINITION TComPicYuv
 
Index: trunk/source/Lib/TLibCommon/TComPicYuvMD5.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComPrediction.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComPrediction.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComPrediction.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -408,4 +408,5 @@
 }
 
+
 Void TComPrediction::motionCompensation ( TComDataCU* pcCU, TComYuv* pcYuvPred, RefPicList eRefPicList, Int iPartIdx )
 {
Index: trunk/source/Lib/TLibCommon/TComPrediction.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComPrediction.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComPrediction.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComRdCost.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComRdCost.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComRdCost.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -410,6 +410,8 @@
     }
   }
-  else if ( ( (iWidth % 4) == 0 ) && ( (iHeight % 4) == 0 ) )
-  {
+  else
+  {
+    assert(iWidth % 4 == 0 && iHeight % 4 == 0);
+    
     for ( y=0; y<iHeight; y+= 4 )
     {
@@ -420,16 +422,4 @@
       pi0 += iStride0*4;
       pi1 += iStride1*4;
-    }
-  }
-  else
-  {
-    for ( y=0; y<iHeight; y+= 2 )
-    {
-      for ( x=0; x<iWidth; x+= 2 )
-      {
-        uiSum += xCalcHADs8x8( &pi0[x], &pi1[x], iStride0, iStride1, 1 );
-      }
-      pi0 += iStride0*2;
-      pi1 += iStride1*2;
     }
   }
Index: trunk/source/Lib/TLibCommon/TComRdCost.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComRdCost.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComRdCost.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComRom.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComRom.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComRom.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -86,14 +86,5 @@
 // Data structure related table & variable
 // ====================================================================================================================
-#if LAYER_CTB
-UInt g_auiLayerMaxCUWidth[MAX_LAYERS];
-UInt g_auiLayerMaxCUHeight[MAX_LAYERS];
-UInt g_auiLayerMaxCUDepth[MAX_LAYERS];
-UInt g_auiLayerAddCUDepth[MAX_LAYERS];
-UInt g_auiLayerZscanToRaster[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
-UInt g_auiLayerRasterToZscan[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
-UInt g_auiLayerRasterToPelX[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
-UInt g_auiLayerRasterToPelY[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
-#endif
+
 UInt g_uiMaxCUWidth  = MAX_CU_SIZE;
 UInt g_uiMaxCUHeight = MAX_CU_SIZE;
@@ -106,9 +97,4 @@
 
 UInt g_auiPUOffset[8] = { 0, 8, 4, 4, 2, 10, 1, 5};
-
-#if FAST_INTRA_SHVC
-UInt g_reducedSetIntraModes[NUM_INTRA_MODE-1] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; 
-UInt g_predefSetIntraModes[NUM_INTRA_MODE-1] = {26,10,18,34,2,22,14,30,6,24,12,28,8,20,16,32,4,17,19,15,21,13,23,11,25,9,27,7,29,5,31,3,33,0,2};
-#endif
 
 Void initZscanToRaster ( Int iMaxDepth, Int iDepth, UInt uiStartVal, UInt*& rpuiCurrIdx )
@@ -321,14 +307,5 @@
 UInt g_uiPCMBitDepthLuma     = 8;    // PCM bit-depth
 UInt g_uiPCMBitDepthChroma   = 8;    // PCM bit-depth
-#if O0194_DIFFERENT_BITDEPTH_EL_BL
-Int  g_bitDepthYLayer[MAX_LAYERS];
-Int  g_bitDepthCLayer[MAX_LAYERS];
-
-UInt g_uiPCMBitDepthLumaDec[MAX_LAYERS];    // PCM bit-depth
-UInt g_uiPCMBitDepthChromaDec[MAX_LAYERS];    // PCM bit-depth
-#endif
-#if O0194_WEIGHTED_PREDICTION_CGS
-void * g_refWeightACDCParam; // type=wpACDCParam
-#endif
+
 // ====================================================================================================================
 // Misc.
@@ -528,4 +505,18 @@
 
 #if SVC_EXTENSION
+#if FAST_INTRA_SHVC
+UInt g_reducedSetIntraModes[NUM_INTRA_MODE-1] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; 
+UInt g_predefSetIntraModes[NUM_INTRA_MODE-1] = {26,10,18,34,2,22,14,30,6,24,12,28,8,20,16,32,4,17,19,15,21,13,23,11,25,9,27,7,29,5,31,3,33,0,2};
+#endif
+#if O0194_DIFFERENT_BITDEPTH_EL_BL
+Int  g_bitDepthYLayer[MAX_LAYERS];
+Int  g_bitDepthCLayer[MAX_LAYERS];
+
+UInt g_uiPCMBitDepthLumaDec[MAX_LAYERS];    // PCM bit-depth
+UInt g_uiPCMBitDepthChromaDec[MAX_LAYERS];    // PCM bit-depth
+#endif
+#if O0194_WEIGHTED_PREDICTION_CGS
+void * g_refWeightACDCParam; // type=wpACDCParam
+#endif
 Int g_mvScalingFactor  [MAX_LAYERS][2] = {{0,0}, {0,0}};
 Int g_posScalingFactor [MAX_LAYERS][2] = {{0,0}, {0,0}};
@@ -571,5 +562,15 @@
   };
 }
+#if LAYER_CTB
+UInt g_auiLayerMaxCUWidth[MAX_LAYERS];
+UInt g_auiLayerMaxCUHeight[MAX_LAYERS];
+UInt g_auiLayerMaxCUDepth[MAX_LAYERS];
+UInt g_auiLayerAddCUDepth[MAX_LAYERS];
+UInt g_auiLayerZscanToRaster[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+UInt g_auiLayerRasterToZscan[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+UInt g_auiLayerRasterToPelX[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+UInt g_auiLayerRasterToPelY[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
 #endif
+#endif //SVC_EXTENSION
 
 //! \}
Index: trunk/source/Lib/TLibCommon/TComRom.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComRom.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComRom.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -81,14 +81,4 @@
 
 // global variable (LCU width/height, max. CU depth)
-#if LAYER_CTB
-extern       UInt g_auiLayerMaxCUWidth[MAX_LAYERS];
-extern       UInt g_auiLayerMaxCUHeight[MAX_LAYERS];
-extern       UInt g_auiLayerMaxCUDepth[MAX_LAYERS];
-extern       UInt g_auiLayerAddCUDepth[MAX_LAYERS];
-extern       UInt g_auiLayerZscanToRaster[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
-extern       UInt g_auiLayerRasterToZscan[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
-extern       UInt g_auiLayerRasterToPelX[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
-extern       UInt g_auiLayerRasterToPelY[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
-#endif
 extern       UInt g_uiMaxCUWidth;
 extern       UInt g_uiMaxCUHeight;
@@ -139,9 +129,4 @@
 
 extern const UChar  g_aucIntraModeNumFast[ MAX_CU_DEPTH ];
-
-#if FAST_INTRA_SHVC
-extern       UInt  g_reducedSetIntraModes[NUM_INTRA_MODE-1];
-extern       UInt  g_predefSetIntraModes[NUM_INTRA_MODE-1];
-#endif
 
 // ====================================================================================================================
@@ -287,8 +272,22 @@
 
 #if SVC_EXTENSION
+#if FAST_INTRA_SHVC
+extern       UInt  g_reducedSetIntraModes[NUM_INTRA_MODE-1];
+extern       UInt  g_predefSetIntraModes[NUM_INTRA_MODE-1];
+#endif
 extern Int g_mvScalingFactor  [MAX_LAYERS][2];
 extern Int g_posScalingFactor [MAX_LAYERS][2];
 std::string NaluToStr( NalUnitType nalu );
-#endif
+#if LAYER_CTB
+extern       UInt g_auiLayerMaxCUWidth[MAX_LAYERS];
+extern       UInt g_auiLayerMaxCUHeight[MAX_LAYERS];
+extern       UInt g_auiLayerMaxCUDepth[MAX_LAYERS];
+extern       UInt g_auiLayerAddCUDepth[MAX_LAYERS];
+extern       UInt g_auiLayerZscanToRaster[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+extern       UInt g_auiLayerRasterToZscan[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+extern       UInt g_auiLayerRasterToPelX[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+extern       UInt g_auiLayerRasterToPelY[MAX_LAYERS][ MAX_NUM_SPU_W*MAX_NUM_SPU_W ];
+#endif
+#endif //SVC_EXTENSION
 
 //! \}
Index: trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -44,5 +44,4 @@
 //! \ingroup TLibCommon
 //! \{
-#if HM_CLEANUP_SAO
 UInt g_saoMaxOffsetQVal[NUM_SAO_COMPONENTS]; 
 
@@ -698,1326 +697,5 @@
   return pBuf;
 }
-#else
-
-SAOParam::~SAOParam()
-{
-  for (Int i = 0 ; i<3; i++)
-  {
-    if (psSaoPart[i])
-    {
-      delete [] psSaoPart[i];
-    }
-  }
-}
-
-// ====================================================================================================================
-// Tables
-// ====================================================================================================================
-
-TComSampleAdaptiveOffset::TComSampleAdaptiveOffset()
-{
-  m_pClipTable = NULL;
-  m_pClipTableBase = NULL;
-  m_pChromaClipTable = NULL;
-  m_pChromaClipTableBase = NULL;
-  m_iOffsetBo = NULL;
-  m_iChromaOffsetBo = NULL;
-  m_lumaTableBo = NULL;
-  m_chromaTableBo = NULL;
-  m_iUpBuff1 = NULL;
-  m_iUpBuff2 = NULL;
-  m_iUpBufft = NULL;
-  ipSwap = NULL;
-
-  m_pTmpU1 = NULL;
-  m_pTmpU2 = NULL;
-  m_pTmpL1 = NULL;
-  m_pTmpL2 = NULL;
-}
-
-TComSampleAdaptiveOffset::~TComSampleAdaptiveOffset()
-{
-
-}
-
-const Int TComSampleAdaptiveOffset::m_aiNumCulPartsLevel[5] =
-{
-  1,   //level 0
-  5,   //level 1
-  21,  //level 2
-  85,  //level 3
-  341, //level 4
-};
-
-const UInt TComSampleAdaptiveOffset::m_auiEoTable[9] =
-{
-  1, //0    
-  2, //1   
-  0, //2
-  3, //3
-  4, //4
-  0, //5  
-  0, //6  
-  0, //7 
-  0
-};
-
-const Int TComSampleAdaptiveOffset::m_iNumClass[MAX_NUM_SAO_TYPE] =
-{
-  SAO_EO_LEN,
-  SAO_EO_LEN,
-  SAO_EO_LEN,
-  SAO_EO_LEN,
-  SAO_BO_LEN
-};
-
-const UInt TComSampleAdaptiveOffset::m_uiMaxDepth = SAO_MAX_DEPTH;
-
-
-/** convert Level Row Col to Idx
- * \param   level,  row,  col
- */
-Int  TComSampleAdaptiveOffset::convertLevelRowCol2Idx(Int level, Int row, Int col)
-{
-  Int idx;
-  if (level == 0)
-  {
-    idx = 0;
-  }
-  else if (level == 1)
-  {
-    idx = 1 + row*2 + col;
-  }
-  else if (level == 2)
-  {
-    idx = 5 + row*4 + col;
-  }
-  else if (level == 3)
-  {
-    idx = 21 + row*8 + col;
-  }
-  else // (level == 4)
-  {
-    idx = 85 + row*16 + col;
-  }
-  return idx;
-}
-
-/** create SampleAdaptiveOffset memory.
- * \param 
- */
-Void TComSampleAdaptiveOffset::create( UInt uiSourceWidth, UInt uiSourceHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight )
-{
-  m_iPicWidth  = uiSourceWidth;
-  m_iPicHeight = uiSourceHeight;
-
-  m_uiMaxCUWidth  = uiMaxCUWidth;
-  m_uiMaxCUHeight = uiMaxCUHeight;
-
-  m_iNumCuInWidth  = m_iPicWidth / m_uiMaxCUWidth;
-  m_iNumCuInWidth += ( m_iPicWidth % m_uiMaxCUWidth ) ? 1 : 0;
-
-  m_iNumCuInHeight  = m_iPicHeight / m_uiMaxCUHeight;
-  m_iNumCuInHeight += ( m_iPicHeight % m_uiMaxCUHeight ) ? 1 : 0;
-
-  Int iMaxSplitLevelHeight = (Int)(logf((Float)m_iNumCuInHeight)/logf(2.0));
-  Int iMaxSplitLevelWidth  = (Int)(logf((Float)m_iNumCuInWidth )/logf(2.0));
-
-  m_uiMaxSplitLevel = (iMaxSplitLevelHeight < iMaxSplitLevelWidth)?(iMaxSplitLevelHeight):(iMaxSplitLevelWidth);
-  m_uiMaxSplitLevel = (m_uiMaxSplitLevel< m_uiMaxDepth)?(m_uiMaxSplitLevel):(m_uiMaxDepth);
-  /* various structures are overloaded to store per component data.
-   * m_iNumTotalParts must allow for sufficient storage in any allocated arrays */
-  m_iNumTotalParts  = max(3,m_aiNumCulPartsLevel[m_uiMaxSplitLevel]);
-
-  UInt uiPixelRangeY = 1 << g_bitDepthY;
-  UInt uiBoRangeShiftY = g_bitDepthY - SAO_BO_BITS;
-
-  m_lumaTableBo = new Pel [uiPixelRangeY];
-  for (Int k2=0; k2<uiPixelRangeY; k2++)
-  {
-    m_lumaTableBo[k2] = 1 + (k2>>uiBoRangeShiftY);
-  }
-
-  UInt uiPixelRangeC = 1 << g_bitDepthC;
-  UInt uiBoRangeShiftC = g_bitDepthC - SAO_BO_BITS;
-
-  m_chromaTableBo = new Pel [uiPixelRangeC];
-  for (Int k2=0; k2<uiPixelRangeC; k2++)
-  {
-    m_chromaTableBo[k2] = 1 + (k2>>uiBoRangeShiftC);
-  }
-
-  m_iUpBuff1 = new Int[m_iPicWidth+2];
-  m_iUpBuff2 = new Int[m_iPicWidth+2];
-  m_iUpBufft = new Int[m_iPicWidth+2];
-
-  m_iUpBuff1++;
-  m_iUpBuff2++;
-  m_iUpBufft++;
-  Pel i;
-
-  UInt uiMaxY  = (1 << g_bitDepthY) - 1;;
-  UInt uiMinY  = 0;
-
-  Int iCRangeExt = uiMaxY>>1;
-
-  m_pClipTableBase = new Pel[uiMaxY+2*iCRangeExt];
-  m_iOffsetBo      = new Int[uiMaxY+2*iCRangeExt];
-
-  for(i=0;i<(uiMinY+iCRangeExt);i++)
-  {
-    m_pClipTableBase[i] = uiMinY;
-  }
-
-  for(i=uiMinY+iCRangeExt;i<(uiMaxY+  iCRangeExt);i++)
-  {
-    m_pClipTableBase[i] = i-iCRangeExt;
-  }
-
-  for(i=uiMaxY+iCRangeExt;i<(uiMaxY+2*iCRangeExt);i++)
-  {
-    m_pClipTableBase[i] = uiMaxY;
-  }
-
-  m_pClipTable = &(m_pClipTableBase[iCRangeExt]);
-
-  UInt uiMaxC  = (1 << g_bitDepthC) - 1;
-  UInt uiMinC  = 0;
-
-  Int iCRangeExtC = uiMaxC>>1;
-
-  m_pChromaClipTableBase = new Pel[uiMaxC+2*iCRangeExtC];
-  m_iChromaOffsetBo      = new Int[uiMaxC+2*iCRangeExtC];
-
-  for(i=0;i<(uiMinC+iCRangeExtC);i++)
-  {
-    m_pChromaClipTableBase[i] = uiMinC;
-  }
-
-  for(i=uiMinC+iCRangeExtC;i<(uiMaxC+  iCRangeExtC);i++)
-  {
-    m_pChromaClipTableBase[i] = i-iCRangeExtC;
-  }
-
-  for(i=uiMaxC+iCRangeExtC;i<(uiMaxC+2*iCRangeExtC);i++)
-  {
-    m_pChromaClipTableBase[i] = uiMaxC;
-  }
-
-  m_pChromaClipTable = &(m_pChromaClipTableBase[iCRangeExtC]);
-
-  m_pTmpL1 = new Pel [m_uiMaxCUHeight+1];
-  m_pTmpL2 = new Pel [m_uiMaxCUHeight+1];
-  m_pTmpU1 = new Pel [m_iPicWidth];
-  m_pTmpU2 = new Pel [m_iPicWidth];
-}
-
-/** destroy SampleAdaptiveOffset memory.
- * \param 
- */
-Void TComSampleAdaptiveOffset::destroy()
-{
-  if (m_pClipTableBase)
-  {
-    delete [] m_pClipTableBase; m_pClipTableBase = NULL;
-  }
-  if (m_iOffsetBo)
-  {
-    delete [] m_iOffsetBo; m_iOffsetBo = NULL;
-  }
-  if (m_lumaTableBo)
-  {
-    delete[] m_lumaTableBo; m_lumaTableBo = NULL;
-  }
-
-  if (m_pChromaClipTableBase)
-  {
-    delete [] m_pChromaClipTableBase; m_pChromaClipTableBase = NULL;
-  }
-  if (m_iChromaOffsetBo)
-  {
-    delete [] m_iChromaOffsetBo; m_iChromaOffsetBo = NULL;
-  }
-  if (m_chromaTableBo)
-  {
-    delete[] m_chromaTableBo; m_chromaTableBo = NULL;
-  }
-
-  if (m_iUpBuff1)
-  {
-    m_iUpBuff1--;
-    delete [] m_iUpBuff1; m_iUpBuff1 = NULL;
-  }
-  if (m_iUpBuff2)
-  {
-    m_iUpBuff2--;
-    delete [] m_iUpBuff2; m_iUpBuff2 = NULL;
-  }
-  if (m_iUpBufft)
-  {
-    m_iUpBufft--;
-    delete [] m_iUpBufft; m_iUpBufft = NULL;
-  }
-  if (m_pTmpL1)
-  {
-    delete [] m_pTmpL1; m_pTmpL1 = NULL;
-  }
-  if (m_pTmpL2)
-  {
-    delete [] m_pTmpL2; m_pTmpL2 = NULL;
-  }
-  if (m_pTmpU1)
-  {
-    delete [] m_pTmpU1; m_pTmpU1 = NULL;
-  }
-  if (m_pTmpU2)
-  {
-    delete [] m_pTmpU2; m_pTmpU2 = NULL;
-  }
-}
-
-/** allocate memory for SAO parameters
- * \param    *pcSaoParam
- */
-Void TComSampleAdaptiveOffset::allocSaoParam(SAOParam *pcSaoParam)
-{
-  pcSaoParam->iMaxSplitLevel = m_uiMaxSplitLevel;
-  pcSaoParam->psSaoPart[0] = new SAOQTPart[ m_aiNumCulPartsLevel[pcSaoParam->iMaxSplitLevel] ];
-  initSAOParam(pcSaoParam, 0, 0, 0, -1, 0, m_iNumCuInWidth-1,  0, m_iNumCuInHeight-1,0);
-  pcSaoParam->psSaoPart[1] = new SAOQTPart[ m_aiNumCulPartsLevel[pcSaoParam->iMaxSplitLevel] ];
-  pcSaoParam->psSaoPart[2] = new SAOQTPart[ m_aiNumCulPartsLevel[pcSaoParam->iMaxSplitLevel] ];
-  initSAOParam(pcSaoParam, 0, 0, 0, -1, 0, m_iNumCuInWidth-1,  0, m_iNumCuInHeight-1,1);
-  initSAOParam(pcSaoParam, 0, 0, 0, -1, 0, m_iNumCuInWidth-1,  0, m_iNumCuInHeight-1,2);
-  pcSaoParam->numCuInWidth  = m_iNumCuInWidth;
-  pcSaoParam->numCuInHeight = m_iNumCuInHeight;
-  pcSaoParam->saoLcuParam[0] = new SaoLcuParam [m_iNumCuInHeight*m_iNumCuInWidth];
-  pcSaoParam->saoLcuParam[1] = new SaoLcuParam [m_iNumCuInHeight*m_iNumCuInWidth];
-  pcSaoParam->saoLcuParam[2] = new SaoLcuParam [m_iNumCuInHeight*m_iNumCuInWidth];
-}
-
-/** initialize SAO parameters
- * \param    *pcSaoParam,  iPartLevel,  iPartRow,  iPartCol,  iParentPartIdx,  StartCUX,  EndCUX,  StartCUY,  EndCUY,  iYCbCr
- */
-Void TComSampleAdaptiveOffset::initSAOParam(SAOParam *pcSaoParam, Int iPartLevel, Int iPartRow, Int iPartCol, Int iParentPartIdx, Int StartCUX, Int EndCUX, Int StartCUY, Int EndCUY, Int iYCbCr)
-{
-  Int j;
-  Int iPartIdx = convertLevelRowCol2Idx(iPartLevel, iPartRow, iPartCol);
-
-  SAOQTPart* pSaoPart;
-
-  pSaoPart = &(pcSaoParam->psSaoPart[iYCbCr][iPartIdx]);
-
-  pSaoPart->PartIdx   = iPartIdx;
-  pSaoPart->PartLevel = iPartLevel;
-  pSaoPart->PartRow   = iPartRow;
-  pSaoPart->PartCol   = iPartCol;
-
-  pSaoPart->StartCUX  = StartCUX;
-  pSaoPart->EndCUX    = EndCUX;
-  pSaoPart->StartCUY  = StartCUY;
-  pSaoPart->EndCUY    = EndCUY;
-
-  pSaoPart->UpPartIdx = iParentPartIdx;
-  pSaoPart->iBestType   = -1;
-  pSaoPart->iLength     =  0;
-
-  pSaoPart->subTypeIdx = 0;
-
-  for (j=0;j<MAX_NUM_SAO_OFFSETS;j++)
-  {
-    pSaoPart->iOffset[j] = 0;
-  }
-
-  if(pSaoPart->PartLevel != m_uiMaxSplitLevel)
-  {
-    Int DownLevel    = (iPartLevel+1 );
-    Int DownRowStart = (iPartRow << 1);
-    Int DownColStart = (iPartCol << 1);
-
-    Int iDownRowIdx, iDownColIdx;
-    Int NumCUWidth,  NumCUHeight;
-    Int NumCULeft;
-    Int NumCUTop;
-
-    Int DownStartCUX, DownStartCUY;
-    Int DownEndCUX, DownEndCUY;
-
-    NumCUWidth  = EndCUX - StartCUX +1;
-    NumCUHeight = EndCUY - StartCUY +1;
-    NumCULeft   = (NumCUWidth  >> 1);
-    NumCUTop    = (NumCUHeight >> 1);
-
-    DownStartCUX= StartCUX;
-    DownEndCUX  = DownStartCUX + NumCULeft - 1;
-    DownStartCUY= StartCUY;
-    DownEndCUY  = DownStartCUY + NumCUTop  - 1;
-    iDownRowIdx = DownRowStart + 0;
-    iDownColIdx = DownColStart + 0;
-
-    pSaoPart->DownPartsIdx[0]= convertLevelRowCol2Idx(DownLevel, iDownRowIdx, iDownColIdx);
-
-    initSAOParam(pcSaoParam, DownLevel, iDownRowIdx, iDownColIdx, iPartIdx, DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY, iYCbCr);
-
-    DownStartCUX = StartCUX + NumCULeft;
-    DownEndCUX   = EndCUX;
-    DownStartCUY = StartCUY;
-    DownEndCUY   = DownStartCUY + NumCUTop -1;
-    iDownRowIdx  = DownRowStart + 0;
-    iDownColIdx  = DownColStart + 1;
-
-    pSaoPart->DownPartsIdx[1] = convertLevelRowCol2Idx(DownLevel, iDownRowIdx, iDownColIdx);
-
-    initSAOParam(pcSaoParam, DownLevel, iDownRowIdx, iDownColIdx, iPartIdx,  DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY, iYCbCr);
-
-    DownStartCUX = StartCUX;
-    DownEndCUX   = DownStartCUX + NumCULeft -1;
-    DownStartCUY = StartCUY + NumCUTop;
-    DownEndCUY   = EndCUY;
-    iDownRowIdx  = DownRowStart + 1;
-    iDownColIdx  = DownColStart + 0;
-
-    pSaoPart->DownPartsIdx[2] = convertLevelRowCol2Idx(DownLevel, iDownRowIdx, iDownColIdx);
-
-    initSAOParam(pcSaoParam, DownLevel, iDownRowIdx, iDownColIdx, iPartIdx, DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY, iYCbCr);
-
-    DownStartCUX = StartCUX+ NumCULeft;
-    DownEndCUX   = EndCUX;
-    DownStartCUY = StartCUY + NumCUTop;
-    DownEndCUY   = EndCUY;
-    iDownRowIdx  = DownRowStart + 1;
-    iDownColIdx  = DownColStart + 1;
-
-    pSaoPart->DownPartsIdx[3] = convertLevelRowCol2Idx(DownLevel, iDownRowIdx, iDownColIdx);
-
-    initSAOParam(pcSaoParam, DownLevel, iDownRowIdx, iDownColIdx, iPartIdx,DownStartCUX, DownEndCUX, DownStartCUY, DownEndCUY, iYCbCr);
-  }
-  else
-  {
-    pSaoPart->DownPartsIdx[0]=pSaoPart->DownPartsIdx[1]= pSaoPart->DownPartsIdx[2]= pSaoPart->DownPartsIdx[3]= -1; 
-  }
-}
-
-/** free memory of SAO parameters
- * \param   pcSaoParam
- */
-Void TComSampleAdaptiveOffset::freeSaoParam(SAOParam *pcSaoParam)
-{
-  delete [] pcSaoParam->psSaoPart[0];
-  delete [] pcSaoParam->psSaoPart[1];
-  delete [] pcSaoParam->psSaoPart[2];
-  pcSaoParam->psSaoPart[0] = 0;
-  pcSaoParam->psSaoPart[1] = 0;
-  pcSaoParam->psSaoPart[2] = 0;
-  if( pcSaoParam->saoLcuParam[0]) 
-  {
-    delete [] pcSaoParam->saoLcuParam[0]; pcSaoParam->saoLcuParam[0] = NULL;
-  }
-  if( pcSaoParam->saoLcuParam[1]) 
-  {
-    delete [] pcSaoParam->saoLcuParam[1]; pcSaoParam->saoLcuParam[1] = NULL;
-  }
-  if( pcSaoParam->saoLcuParam[2]) 
-  {
-    delete [] pcSaoParam->saoLcuParam[2]; pcSaoParam->saoLcuParam[2] = NULL;
-  }
-} 
-
-/** reset SAO parameters
- * \param   pcSaoParam
- */
-Void TComSampleAdaptiveOffset::resetSAOParam(SAOParam *pcSaoParam)
-{
-  Int iNumComponet = 3;
-  for(Int c=0; c<iNumComponet; c++)
-  {
-if (c<2)
-  {
-    pcSaoParam->bSaoFlag[c] = 0;
-  }
-    for(Int i=0; i< m_aiNumCulPartsLevel[m_uiMaxSplitLevel]; i++)
-    {
-      pcSaoParam->psSaoPart[c][i].iBestType     = -1;
-      pcSaoParam->psSaoPart[c][i].iLength       =  0;
-      pcSaoParam->psSaoPart[c][i].bSplit        = false; 
-      pcSaoParam->psSaoPart[c][i].bProcessed    = false;
-      pcSaoParam->psSaoPart[c][i].dMinCost      = MAX_DOUBLE;
-      pcSaoParam->psSaoPart[c][i].iMinDist      = MAX_INT;
-      pcSaoParam->psSaoPart[c][i].iMinRate      = MAX_INT;
-      pcSaoParam->psSaoPart[c][i].subTypeIdx    = 0;
-      for (Int j=0;j<MAX_NUM_SAO_OFFSETS;j++)
-      {
-        pcSaoParam->psSaoPart[c][i].iOffset[j] = 0;
-        pcSaoParam->psSaoPart[c][i].iOffset[j] = 0;
-        pcSaoParam->psSaoPart[c][i].iOffset[j] = 0;
-      }
-    }
-    pcSaoParam->oneUnitFlag[0]   = 0;
-    pcSaoParam->oneUnitFlag[1]   = 0;
-    pcSaoParam->oneUnitFlag[2]   = 0;
-    resetLcuPart(pcSaoParam->saoLcuParam[0]);
-    resetLcuPart(pcSaoParam->saoLcuParam[1]);
-    resetLcuPart(pcSaoParam->saoLcuParam[2]);
-  }
-}
-
-/** get the sign of input variable
- * \param   x
- */
-inline Int xSign(Int x)
-{
-  return ((x >> 31) | ((Int)( (((UInt) -x)) >> 31)));
-}
-
-/** initialize variables for SAO process
- * \param  pcPic picture data pointer
- */
-Void TComSampleAdaptiveOffset::createPicSaoInfo(TComPic* pcPic)
-{
-  m_pcPic   = pcPic;
-  m_bUseNIF = ( pcPic->getIndependentSliceBoundaryForNDBFilter() || pcPic->getIndependentTileBoundaryForNDBFilter() );
-  if(m_bUseNIF)
-  {
-    m_pcYuvTmp = pcPic->getYuvPicBufferForIndependentBoundaryProcessing();
-  }
-}
-
-Void TComSampleAdaptiveOffset::destroyPicSaoInfo()
-{
-
-}
-
-/** sample adaptive offset process for one LCU
- * \param   iAddr, iSaoType, iYCbCr
- */
-Void TComSampleAdaptiveOffset::processSaoCu(Int iAddr, Int iSaoType, Int iYCbCr)
-{
-  if(!m_bUseNIF)
-  {
-    processSaoCuOrg( iAddr, iSaoType, iYCbCr);
-  }
-  else
-  {  
-    Int  isChroma = (iYCbCr != 0)? 1:0;
-    Int  stride   = (iYCbCr != 0)?(m_pcPic->getCStride()):(m_pcPic->getStride());
-    Pel* pPicRest = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr);
-    Pel* pPicDec  = getPicYuvAddr(m_pcYuvTmp, iYCbCr);
-
-    std::vector<NDBFBlockInfo>& vFilterBlocks = *(m_pcPic->getCU(iAddr)->getNDBFilterBlocks());
-
-    //variables
-    UInt  xPos, yPos, width, height;
-    Bool* pbBorderAvail;
-    UInt  posOffset;
-
-    for(Int i=0; i< vFilterBlocks.size(); i++)
-    {
-      xPos        = vFilterBlocks[i].posX   >> isChroma;
-      yPos        = vFilterBlocks[i].posY   >> isChroma;
-      width       = vFilterBlocks[i].width  >> isChroma;
-      height      = vFilterBlocks[i].height >> isChroma;
-      pbBorderAvail = vFilterBlocks[i].isBorderAvailable;
-
-      posOffset = (yPos* stride) + xPos;
-
-      processSaoBlock(pPicDec+ posOffset, pPicRest+ posOffset, stride, iSaoType, width, height, pbBorderAvail, iYCbCr);
-    }
-  }
-}
-
-/** Perform SAO for non-cross-slice or non-cross-tile process
- * \param  pDec to-be-filtered block buffer pointer
- * \param  pRest filtered block buffer pointer
- * \param  stride picture buffer stride
- * \param  saoType SAO offset type
- * \param  xPos x coordinate
- * \param  yPos y coordinate
- * \param  width block width
- * \param  height block height
- * \param  pbBorderAvail availabilities of block border pixels
- */
-Void TComSampleAdaptiveOffset::processSaoBlock(Pel* pDec, Pel* pRest, Int stride, Int saoType, UInt width, UInt height, Bool* pbBorderAvail, Int iYCbCr)
-{
-  //variables
-  Int startX, startY, endX, endY, x, y;
-  Int signLeft,signRight,signDown,signDown1;
-  UInt edgeType;
-  Pel *pClipTbl = (iYCbCr==0)?m_pClipTable:m_pChromaClipTable;
-  Int *pOffsetBo = (iYCbCr==0)?m_iOffsetBo: m_iChromaOffsetBo;
-
-  switch (saoType)
-  {
-  case SAO_EO_0: // dir: -
-    {
-
-      startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
-      endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
-      for (y=0; y< height; y++)
-      {
-        signLeft = xSign(pDec[startX] - pDec[startX-1]);
-        for (x=startX; x< endX; x++)
-        {
-          signRight =  xSign(pDec[x] - pDec[x+1]); 
-          edgeType =  signRight + signLeft + 2;
-          signLeft  = -signRight;
-
-          pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
-        }
-        pDec  += stride;
-        pRest += stride;
-      }
-      break;
-    }
-  case SAO_EO_1: // dir: |
-    {
-      startY = (pbBorderAvail[SGU_T]) ? 0 : 1;
-      endY   = (pbBorderAvail[SGU_B]) ? height : height-1;
-      if (!pbBorderAvail[SGU_T])
-      {
-        pDec  += stride;
-        pRest += stride;
-      }
-      for (x=0; x< width; x++)
-      {
-        m_iUpBuff1[x] = xSign(pDec[x] - pDec[x-stride]);
-      }
-      for (y=startY; y<endY; y++)
-      {
-        for (x=0; x< width; x++)
-        {
-          signDown  = xSign(pDec[x] - pDec[x+stride]); 
-          edgeType = signDown + m_iUpBuff1[x] + 2;
-          m_iUpBuff1[x]= -signDown;
-
-          pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
-        }
-        pDec  += stride;
-        pRest += stride;
-      }
-      break;
-    }
-  case SAO_EO_2: // dir: 135
-    {
-      Int posShift= stride + 1;
-
-      startX = (pbBorderAvail[SGU_L]) ? 0 : 1 ;
-      endX   = (pbBorderAvail[SGU_R]) ? width : (width-1);
-
-      //prepare 2nd line upper sign
-      pDec += stride;
-      for (x=startX; x< endX+1; x++)
-      {
-        m_iUpBuff1[x] = xSign(pDec[x] - pDec[x- posShift]);
-      }
-
-      //1st line
-      pDec -= stride;
-      if(pbBorderAvail[SGU_TL])
-      {
-        x= 0;
-        edgeType      =  xSign(pDec[x] - pDec[x- posShift]) - m_iUpBuff1[x+1] + 2;
-        pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
-
-      }
-      if(pbBorderAvail[SGU_T])
-      {
-        for(x= 1; x< endX; x++)
-        {
-          edgeType      =  xSign(pDec[x] - pDec[x- posShift]) - m_iUpBuff1[x+1] + 2;
-          pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
-        }
-      }
-      pDec   += stride;
-      pRest  += stride;
-
-
-      //middle lines
-      for (y= 1; y< height-1; y++)
-      {
-        for (x=startX; x<endX; x++)
-        {
-          signDown1      =  xSign(pDec[x] - pDec[x+ posShift]) ;
-          edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
-          pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
-
-          m_iUpBufft[x+1] = -signDown1; 
-        }
-        m_iUpBufft[startX] = xSign(pDec[stride+startX] - pDec[startX-1]);
-
-        ipSwap     = m_iUpBuff1;
-        m_iUpBuff1 = m_iUpBufft;
-        m_iUpBufft = ipSwap;
-
-        pDec  += stride;
-        pRest += stride;
-      }
-
-      //last line
-      if(pbBorderAvail[SGU_B])
-      {
-        for(x= startX; x< width-1; x++)
-        {
-          edgeType =  xSign(pDec[x] - pDec[x+ posShift]) + m_iUpBuff1[x] + 2;
-          pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
-        }
-      }
-      if(pbBorderAvail[SGU_BR])
-      {
-        x= width -1;
-        edgeType =  xSign(pDec[x] - pDec[x+ posShift]) + m_iUpBuff1[x] + 2;
-        pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
-      }
-      break;
-    } 
-  case SAO_EO_3: // dir: 45
-    {
-      Int  posShift     = stride - 1;
-      startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
-      endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
-
-      //prepare 2nd line upper sign
-      pDec += stride;
-      for (x=startX-1; x< endX; x++)
-      {
-        m_iUpBuff1[x] = xSign(pDec[x] - pDec[x- posShift]);
-      }
-
-
-      //first line
-      pDec -= stride;
-      if(pbBorderAvail[SGU_T])
-      {
-        for(x= startX; x< width -1; x++)
-        {
-          edgeType = xSign(pDec[x] - pDec[x- posShift]) -m_iUpBuff1[x-1] + 2;
-          pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
-        }
-      }
-      if(pbBorderAvail[SGU_TR])
-      {
-        x= width-1;
-        edgeType = xSign(pDec[x] - pDec[x- posShift]) -m_iUpBuff1[x-1] + 2;
-        pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
-      }
-      pDec  += stride;
-      pRest += stride;
-
-      //middle lines
-      for (y= 1; y< height-1; y++)
-      {
-        for(x= startX; x< endX; x++)
-        {
-          signDown1      =  xSign(pDec[x] - pDec[x+ posShift]) ;
-          edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
-
-          pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
-          m_iUpBuff1[x-1] = -signDown1; 
-        }
-        m_iUpBuff1[endX-1] = xSign(pDec[endX-1 + stride] - pDec[endX]);
-
-        pDec  += stride;
-        pRest += stride;
-      }
-
-      //last line
-      if(pbBorderAvail[SGU_BL])
-      {
-        x= 0;
-        edgeType = xSign(pDec[x] - pDec[x+ posShift]) + m_iUpBuff1[x] + 2;
-        pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
-
-      }
-      if(pbBorderAvail[SGU_B])
-      {
-        for(x= 1; x< endX; x++)
-        {
-          edgeType = xSign(pDec[x] - pDec[x+ posShift]) + m_iUpBuff1[x] + 2;
-          pRest[x] = pClipTbl[pDec[x] + m_iOffsetEo[edgeType]];
-        }
-      }
-      break;
-    }   
-  case SAO_BO:
-    {
-      for (y=0; y< height; y++)
-      {
-        for (x=0; x< width; x++)
-        {
-          pRest[x] = pOffsetBo[pDec[x]];
-        }
-        pRest += stride;
-        pDec  += stride;
-      }
-      break;
-    }
-  default: break;
-  }
-
-}
-
-/** sample adaptive offset process for one LCU crossing LCU boundary
- * \param   iAddr, iSaoType, iYCbCr
- */
-Void TComSampleAdaptiveOffset::processSaoCuOrg(Int iAddr, Int iSaoType, Int iYCbCr)
-{
-  Int x,y;
-  TComDataCU *pTmpCu = m_pcPic->getCU(iAddr);
-  Pel* pRec;
-  Int  iStride;
-  Int  iLcuWidth  = m_uiMaxCUWidth;
-  Int  iLcuHeight = m_uiMaxCUHeight;
-  UInt uiLPelX    = pTmpCu->getCUPelX();
-  UInt uiTPelY    = pTmpCu->getCUPelY();
-  UInt uiRPelX;
-  UInt uiBPelY;
-  Int  iSignLeft;
-  Int  iSignRight;
-  Int  iSignDown;
-  Int  iSignDown1;
-  Int  iSignDown2;
-  UInt uiEdgeType;
-  Int iPicWidthTmp;
-  Int iPicHeightTmp;
-  Int iStartX;
-  Int iStartY;
-  Int iEndX;
-  Int iEndY;
-  Int iIsChroma = (iYCbCr!=0)? 1:0;
-  Int iShift;
-  Int iCuHeightTmp;
-  Pel *pTmpLSwap;
-  Pel *pTmpL;
-  Pel *pTmpU;
-  Pel *pClipTbl = NULL;
-  Int *pOffsetBo = NULL;
-
-  iPicWidthTmp  = m_iPicWidth  >> iIsChroma;
-  iPicHeightTmp = m_iPicHeight >> iIsChroma;
-  iLcuWidth     = iLcuWidth    >> iIsChroma;
-  iLcuHeight    = iLcuHeight   >> iIsChroma;
-  uiLPelX       = uiLPelX      >> iIsChroma;
-  uiTPelY       = uiTPelY      >> iIsChroma;
-  uiRPelX       = uiLPelX + iLcuWidth  ;
-  uiBPelY       = uiTPelY + iLcuHeight ;
-  uiRPelX       = uiRPelX > iPicWidthTmp  ? iPicWidthTmp  : uiRPelX;
-  uiBPelY       = uiBPelY > iPicHeightTmp ? iPicHeightTmp : uiBPelY;
-  iLcuWidth     = uiRPelX - uiLPelX;
-  iLcuHeight    = uiBPelY - uiTPelY;
-
-  if(pTmpCu->getPic()==0)
-  {
-    return;
-  }
-  if (iYCbCr == 0)
-  {
-    pRec       = m_pcPic->getPicYuvRec()->getLumaAddr(iAddr);
-    iStride    = m_pcPic->getStride();
-  } 
-  else if (iYCbCr == 1)
-  {
-    pRec       = m_pcPic->getPicYuvRec()->getCbAddr(iAddr);
-    iStride    = m_pcPic->getCStride();
-  }
-  else 
-  {
-    pRec       = m_pcPic->getPicYuvRec()->getCrAddr(iAddr);
-    iStride    = m_pcPic->getCStride();
-  }
-
-//   if (iSaoType!=SAO_BO_0 || iSaoType!=SAO_BO_1)
-  {
-    iCuHeightTmp = (m_uiMaxCUHeight >> iIsChroma);
-    iShift = (m_uiMaxCUWidth>> iIsChroma)-1;
-    for (Int i=0;i<iCuHeightTmp+1;i++)
-    {
-      m_pTmpL2[i] = pRec[iShift];
-      pRec += iStride;
-    }
-    pRec -= (iStride*(iCuHeightTmp+1));
-
-    pTmpL = m_pTmpL1; 
-    pTmpU = &(m_pTmpU1[uiLPelX]); 
-  }
-
-  pClipTbl = (iYCbCr==0)? m_pClipTable:m_pChromaClipTable;
-  pOffsetBo = (iYCbCr==0)? m_iOffsetBo:m_iChromaOffsetBo;
-
-  switch (iSaoType)
-  {
-  case SAO_EO_0: // dir: -
-    {
-      iStartX = (uiLPelX == 0) ? 1 : 0;
-      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
-      for (y=0; y<iLcuHeight; y++)
-      {
-        iSignLeft = xSign(pRec[iStartX] - pTmpL[y]);
-        for (x=iStartX; x< iEndX; x++)
-        {
-          iSignRight =  xSign(pRec[x] - pRec[x+1]); 
-          uiEdgeType =  iSignRight + iSignLeft + 2;
-          iSignLeft  = -iSignRight;
-
-          pRec[x] = pClipTbl[pRec[x] + m_iOffsetEo[uiEdgeType]];
-        }
-        pRec += iStride;
-      }
-      break;
-    }
-  case SAO_EO_1: // dir: |
-    {
-      iStartY = (uiTPelY == 0) ? 1 : 0;
-      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight;
-      if (uiTPelY == 0)
-      {
-        pRec += iStride;
-      }
-      for (x=0; x< iLcuWidth; x++)
-      {
-        m_iUpBuff1[x] = xSign(pRec[x] - pTmpU[x]);
-      }
-      for (y=iStartY; y<iEndY; y++)
-      {
-        for (x=0; x<iLcuWidth; x++)
-        {
-          iSignDown  = xSign(pRec[x] - pRec[x+iStride]); 
-          uiEdgeType = iSignDown + m_iUpBuff1[x] + 2;
-          m_iUpBuff1[x]= -iSignDown;
-
-          pRec[x] = pClipTbl[pRec[x] + m_iOffsetEo[uiEdgeType]];
-        }
-        pRec += iStride;
-      }
-      break;
-    }
-  case SAO_EO_2: // dir: 135
-    {
-      iStartX = (uiLPelX == 0)            ? 1 : 0;
-      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
-
-      iStartY = (uiTPelY == 0) ?             1 : 0;
-      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight;
-
-      if (uiTPelY == 0)
-      {
-        pRec += iStride;
-      }
-
-      for (x=iStartX; x<iEndX; x++)
-      {
-        m_iUpBuff1[x] = xSign(pRec[x] - pTmpU[x-1]);
-      }
-      for (y=iStartY; y<iEndY; y++)
-      {
-        iSignDown2 = xSign(pRec[iStride+iStartX] - pTmpL[y]);
-        for (x=iStartX; x<iEndX; x++)
-        {
-          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride+1]) ;
-          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
-          m_iUpBufft[x+1] = -iSignDown1; 
-          pRec[x] = pClipTbl[pRec[x] + m_iOffsetEo[uiEdgeType]];
-        }
-        m_iUpBufft[iStartX] = iSignDown2;
-
-        ipSwap     = m_iUpBuff1;
-        m_iUpBuff1 = m_iUpBufft;
-        m_iUpBufft = ipSwap;
-
-        pRec += iStride;
-      }
-      break;
-    } 
-  case SAO_EO_3: // dir: 45
-    {
-      iStartX = (uiLPelX == 0) ? 1 : 0;
-      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth;
-
-      iStartY = (uiTPelY == 0) ? 1 : 0;
-      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight;
-
-      if (iStartY == 1)
-      {
-        pRec += iStride;
-      }
-
-      for (x=iStartX-1; x<iEndX; x++)
-      {
-        m_iUpBuff1[x] = xSign(pRec[x] - pTmpU[x+1]);
-      }
-      for (y=iStartY; y<iEndY; y++)
-      {
-        x=iStartX;
-        iSignDown1      =  xSign(pRec[x] - pTmpL[y+1]) ;
-        uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
-        m_iUpBuff1[x-1] = -iSignDown1; 
-        pRec[x] = pClipTbl[pRec[x] + m_iOffsetEo[uiEdgeType]];
-        for (x=iStartX+1; x<iEndX; x++)
-        {
-          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride-1]) ;
-          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
-          m_iUpBuff1[x-1] = -iSignDown1; 
-          pRec[x] = pClipTbl[pRec[x] + m_iOffsetEo[uiEdgeType]];
-        }
-        m_iUpBuff1[iEndX-1] = xSign(pRec[iEndX-1 + iStride] - pRec[iEndX]);
-
-        pRec += iStride;
-      } 
-      break;
-    }   
-  case SAO_BO:
-    {
-      for (y=0; y<iLcuHeight; y++)
-      {
-        for (x=0; x<iLcuWidth; x++)
-        {
-          pRec[x] = pOffsetBo[pRec[x]];
-        }
-        pRec += iStride;
-      }
-      break;
-    }
-  default: break;
-  }
-//   if (iSaoType!=SAO_BO_0 || iSaoType!=SAO_BO_1)
-  {
-    pTmpLSwap = m_pTmpL1;
-    m_pTmpL1  = m_pTmpL2;
-    m_pTmpL2  = pTmpLSwap;
-  }
-}
-/** Sample adaptive offset process
- * \param pcPic, pcSaoParam  
- */
-Void TComSampleAdaptiveOffset::SAOProcess(SAOParam* pcSaoParam)
-{
-  {
-    m_uiSaoBitIncreaseY = max(g_bitDepthY - 10, 0);
-    m_uiSaoBitIncreaseC = max(g_bitDepthC - 10, 0);
-
-    if(m_bUseNIF)
-    {
-      m_pcPic->getPicYuvRec()->copyToPic(m_pcYuvTmp);
-    }
-    if (m_saoLcuBasedOptimization)
-    {
-      pcSaoParam->oneUnitFlag[0] = 0;  
-      pcSaoParam->oneUnitFlag[1] = 0;  
-      pcSaoParam->oneUnitFlag[2] = 0;  
-    }
-    Int iY  = 0;
-    {
-      processSaoUnitAll( pcSaoParam->saoLcuParam[iY], pcSaoParam->oneUnitFlag[iY], iY);
-    }
-    {
-       processSaoUnitAll( pcSaoParam->saoLcuParam[1], pcSaoParam->oneUnitFlag[1], 1);//Cb
-       processSaoUnitAll( pcSaoParam->saoLcuParam[2], pcSaoParam->oneUnitFlag[2], 2);//Cr
-    }
-    m_pcPic = NULL;
-  }
-}
-
-Pel* TComSampleAdaptiveOffset::getPicYuvAddr(TComPicYuv* pcPicYuv, Int iYCbCr, Int iAddr)
-{
-  switch (iYCbCr)
-  {
-  case 0:
-    return pcPicYuv->getLumaAddr(iAddr);
-    break;
-  case 1:
-    return pcPicYuv->getCbAddr(iAddr);
-    break;
-  case 2:
-    return pcPicYuv->getCrAddr(iAddr);
-    break;
-  default:
-    return NULL;
-    break;
-  }
-}
-/** Process SAO all units 
- * \param saoLcuParam SAO LCU parameters
- * \param oneUnitFlag one unit flag
- * \param yCbCr color componet index
- */
-Void TComSampleAdaptiveOffset::processSaoUnitAll(SaoLcuParam* saoLcuParam, Bool oneUnitFlag, Int yCbCr)
-{
-  Pel *pRec;
-  Int picWidthTmp;
-
-  if (yCbCr == 0)
-  {
-    pRec        = m_pcPic->getPicYuvRec()->getLumaAddr();
-    picWidthTmp = m_iPicWidth;
-  } 
-  else if (yCbCr == 1)
-  {
-    pRec        = m_pcPic->getPicYuvRec()->getCbAddr();
-    picWidthTmp = m_iPicWidth>>1;
-  }
-  else 
-  {
-    pRec        = m_pcPic->getPicYuvRec()->getCrAddr();
-    picWidthTmp = m_iPicWidth>>1;
-  }
-
-  memcpy(m_pTmpU1, pRec, sizeof(Pel)*picWidthTmp);
-
-  Int  i;
-  UInt edgeType;
-  Pel* ppLumaTable = NULL;
-  Pel* pClipTable = NULL;
-  Int* pOffsetBo = NULL;
-  Int  typeIdx;
-
-  Int offset[LUMA_GROUP_NUM+1];
-  Int idxX;
-  Int idxY;
-  Int addr;
-  Int frameWidthInCU = m_pcPic->getFrameWidthInCU();
-  Int frameHeightInCU = m_pcPic->getFrameHeightInCU();
-  Int stride;
-  Pel *tmpUSwap;
-  Int isChroma = (yCbCr == 0) ? 0:1;
-  Bool mergeLeftFlag;
-  Int saoBitIncrease = (yCbCr == 0) ? m_uiSaoBitIncreaseY : m_uiSaoBitIncreaseC;
-
-  pOffsetBo = (yCbCr==0) ? m_iOffsetBo : m_iChromaOffsetBo;
-
-  offset[0] = 0;
-  for (idxY = 0; idxY< frameHeightInCU; idxY++)
-  { 
-    addr = idxY * frameWidthInCU;
-    if (yCbCr == 0)
-    {
-      pRec  = m_pcPic->getPicYuvRec()->getLumaAddr(addr);
-      stride = m_pcPic->getStride();
-      picWidthTmp = m_iPicWidth;
-    }
-    else if (yCbCr == 1)
-    {
-      pRec  = m_pcPic->getPicYuvRec()->getCbAddr(addr);
-      stride = m_pcPic->getCStride();
-      picWidthTmp = m_iPicWidth>>1;
-    }
-    else
-    {
-      pRec  = m_pcPic->getPicYuvRec()->getCrAddr(addr);
-      stride = m_pcPic->getCStride();
-      picWidthTmp = m_iPicWidth>>1;
-    }
-
-    //     pRec += iStride*(m_uiMaxCUHeight-1);
-    for (i=0;i<(m_uiMaxCUHeight>>isChroma)+1;i++)
-    {
-      m_pTmpL1[i] = pRec[0];
-      pRec+=stride;
-    }
-    pRec-=(stride<<1);
-
-    memcpy(m_pTmpU2, pRec, sizeof(Pel)*picWidthTmp);
-
-    for (idxX = 0; idxX < frameWidthInCU; idxX++)
-    {
-      addr = idxY * frameWidthInCU + idxX;
-
-      if (oneUnitFlag)
-      {
-        typeIdx = saoLcuParam[0].typeIdx;
-        mergeLeftFlag = (addr == 0)? 0:1;
-      }
-      else
-      {
-        typeIdx = saoLcuParam[addr].typeIdx;
-        mergeLeftFlag = saoLcuParam[addr].mergeLeftFlag;
-      }
-      if (typeIdx>=0)
-      {
-        if (!mergeLeftFlag)
-        {
-
-          if (typeIdx == SAO_BO)
-          {
-            for (i=0; i<SAO_MAX_BO_CLASSES+1;i++)
-            {
-              offset[i] = 0;
-            }
-            for (i=0; i<saoLcuParam[addr].length; i++)
-            {
-              offset[ (saoLcuParam[addr].subTypeIdx +i)%SAO_MAX_BO_CLASSES  +1] = saoLcuParam[addr].offset[i] << saoBitIncrease;
-            }
-
-            ppLumaTable = (yCbCr==0)?m_lumaTableBo:m_chromaTableBo;
-            pClipTable = (yCbCr==0)?m_pClipTable:m_pChromaClipTable;
-
-            Int bitDepth = (yCbCr==0) ? g_bitDepthY : g_bitDepthC;
-            for (i=0;i<(1<<bitDepth);i++)
-            {
-              pOffsetBo[i] = pClipTable[i + offset[ppLumaTable[i]]];
-            }
-
-          }
-          if (typeIdx == SAO_EO_0 || typeIdx == SAO_EO_1 || typeIdx == SAO_EO_2 || typeIdx == SAO_EO_3)
-          {
-            for (i=0;i<saoLcuParam[addr].length;i++)
-            {
-              offset[i+1] = saoLcuParam[addr].offset[i] << saoBitIncrease;
-            }
-            for (edgeType=0;edgeType<6;edgeType++)
-            {
-              m_iOffsetEo[edgeType]= offset[m_auiEoTable[edgeType]];
-            }
-          }
-        }
-        processSaoCu(addr, typeIdx, yCbCr);
-      }
-      else
-      {
-        if (idxX != (frameWidthInCU-1))
-        {
-          if (yCbCr == 0)
-          {
-            pRec  = m_pcPic->getPicYuvRec()->getLumaAddr(addr);
-            stride = m_pcPic->getStride();
-          }
-          else if (yCbCr == 1)
-          {
-            pRec  = m_pcPic->getPicYuvRec()->getCbAddr(addr);
-            stride = m_pcPic->getCStride();
-          }
-          else
-          {
-            pRec  = m_pcPic->getPicYuvRec()->getCrAddr(addr);
-            stride = m_pcPic->getCStride();
-          }
-          Int widthShift = m_uiMaxCUWidth>>isChroma;
-          for (i=0;i<(m_uiMaxCUHeight>>isChroma)+1;i++)
-          {
-            m_pTmpL1[i] = pRec[widthShift-1];
-            pRec+=stride;
-          }
-        }
-      }
-    }
-    tmpUSwap = m_pTmpU1;
-    m_pTmpU1 = m_pTmpU2;
-    m_pTmpU2 = tmpUSwap;
-  }
-
-}
-/** Reset SAO LCU part 
- * \param saoLcuParam
- */
-Void TComSampleAdaptiveOffset::resetLcuPart(SaoLcuParam* saoLcuParam)
-{
-  Int i,j;
-  for (i=0;i<m_iNumCuInWidth*m_iNumCuInHeight;i++)
-  {
-    saoLcuParam[i].mergeUpFlag     =  1;
-    saoLcuParam[i].mergeLeftFlag =  0;
-    saoLcuParam[i].partIdx   =  0;
-    saoLcuParam[i].typeIdx      = -1;
-    for (j=0;j<MAX_NUM_SAO_OFFSETS;j++)
-    {
-      saoLcuParam[i].offset[j] = 0;
-    }
-    saoLcuParam[i].subTypeIdx = 0;
-  }
-}
-
-/** convert QP part to SAO unit 
-* \param saoParam SAO parameter 
-* \param partIdx SAO part index
-* \param yCbCr color component index
- */
-Void TComSampleAdaptiveOffset::convertQT2SaoUnit(SAOParam *saoParam, UInt partIdx, Int yCbCr)
-{
-
-  SAOQTPart*  saoPart= &(saoParam->psSaoPart[yCbCr][partIdx]);
-  if (!saoPart->bSplit)
-  {
-    convertOnePart2SaoUnit(saoParam, partIdx, yCbCr);
-    return;
-  }
-
-  if (saoPart->PartLevel < m_uiMaxSplitLevel)
-  {
-    convertQT2SaoUnit(saoParam, saoPart->DownPartsIdx[0], yCbCr);
-    convertQT2SaoUnit(saoParam, saoPart->DownPartsIdx[1], yCbCr);
-    convertQT2SaoUnit(saoParam, saoPart->DownPartsIdx[2], yCbCr);
-    convertQT2SaoUnit(saoParam, saoPart->DownPartsIdx[3], yCbCr);
-  }
-}
-/** convert one SAO part to SAO unit 
-* \param saoParam SAO parameter 
-* \param partIdx SAO part index
-* \param yCbCr color component index
- */
-Void TComSampleAdaptiveOffset::convertOnePart2SaoUnit(SAOParam *saoParam, UInt partIdx, Int yCbCr)
-{
-  Int j;
-  Int idxX;
-  Int idxY;
-  Int addr;
-  Int frameWidthInCU = m_pcPic->getFrameWidthInCU();
-  SAOQTPart* saoQTPart = saoParam->psSaoPart[yCbCr];
-  SaoLcuParam* saoLcuParam = saoParam->saoLcuParam[yCbCr];
-
-  for (idxY = saoQTPart[partIdx].StartCUY; idxY<= saoQTPart[partIdx].EndCUY; idxY++)
-  {
-    for (idxX = saoQTPart[partIdx].StartCUX; idxX<= saoQTPart[partIdx].EndCUX; idxX++)
-    {
-      addr = idxY * frameWidthInCU + idxX;
-      saoLcuParam[addr].partIdxTmp = (Int)partIdx; 
-      saoLcuParam[addr].typeIdx    = saoQTPart[partIdx].iBestType;
-      saoLcuParam[addr].subTypeIdx = saoQTPart[partIdx].subTypeIdx;
-      if (saoLcuParam[addr].typeIdx!=-1)
-      {
-        saoLcuParam[addr].length    = saoQTPart[partIdx].iLength;
-        for (j=0;j<MAX_NUM_SAO_OFFSETS;j++)
-        {
-          saoLcuParam[addr].offset[j] = saoQTPart[partIdx].iOffset[j];
-        }
-      }
-      else
-      {
-        saoLcuParam[addr].length    = 0;
-        saoLcuParam[addr].subTypeIdx = saoQTPart[partIdx].subTypeIdx;
-        for (j=0;j<MAX_NUM_SAO_OFFSETS;j++)
-        {
-          saoLcuParam[addr].offset[j] = 0;
-        }
-      }
-    }
-  }
-}
-
-Void TComSampleAdaptiveOffset::resetSaoUnit(SaoLcuParam* saoUnit)
-{
-  saoUnit->partIdx       = 0;
-  saoUnit->partIdxTmp    = 0;
-  saoUnit->mergeLeftFlag = 0;
-  saoUnit->mergeUpFlag   = 0;
-  saoUnit->typeIdx       = -1;
-  saoUnit->length        = 0;
-  saoUnit->subTypeIdx    = 0;
-
-  for (Int i=0;i<4;i++)
-  {
-    saoUnit->offset[i] = 0;
-  }
-}
-
-Void TComSampleAdaptiveOffset::copySaoUnit(SaoLcuParam* saoUnitDst, SaoLcuParam* saoUnitSrc )
-{
-  saoUnitDst->mergeLeftFlag = saoUnitSrc->mergeLeftFlag;
-  saoUnitDst->mergeUpFlag   = saoUnitSrc->mergeUpFlag;
-  saoUnitDst->typeIdx       = saoUnitSrc->typeIdx;
-  saoUnitDst->length        = saoUnitSrc->length;
-
-  saoUnitDst->subTypeIdx  = saoUnitSrc->subTypeIdx;
-  for (Int i=0;i<4;i++)
-  {
-    saoUnitDst->offset[i] = saoUnitSrc->offset[i];
-  }
-}
-#endif
+
 /** PCM LF disable process. 
  * \param pcPic picture (TComPic) pointer
Index: trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -45,6 +45,4 @@
 //! \{
 
-
-#if HM_CLEANUP_SAO
 // ====================================================================================================================
 // Constants
@@ -105,107 +103,4 @@
 
 };
-#else
-
-// ====================================================================================================================
-// Constants
-// ====================================================================================================================
-
-#define SAO_MAX_DEPTH                 4
-#define SAO_BO_BITS                   5
-#define LUMA_GROUP_NUM                (1<<SAO_BO_BITS)
-#define MAX_NUM_SAO_OFFSETS           4
-#define MAX_NUM_SAO_CLASS             33
-// ====================================================================================================================
-// Class definition
-// ====================================================================================================================
-
-/// Sample Adaptive Offset class
-class TComSampleAdaptiveOffset
-{
-protected:
-  TComPic*          m_pcPic;
-
-  static const UInt m_uiMaxDepth;
-  static const Int m_aiNumCulPartsLevel[5];
-  static const UInt m_auiEoTable[9];
-  Int *m_iOffsetBo;
-  Int *m_iChromaOffsetBo;
-  Int m_iOffsetEo[LUMA_GROUP_NUM];
-
-  Int  m_iPicWidth;
-  Int  m_iPicHeight;
-  UInt m_uiMaxSplitLevel;
-  UInt m_uiMaxCUWidth;
-  UInt m_uiMaxCUHeight;
-  Int  m_iNumCuInWidth;
-  Int  m_iNumCuInHeight;
-  Int  m_iNumTotalParts;
-  static const Int m_iNumClass[MAX_NUM_SAO_TYPE];
-
-  UInt m_uiSaoBitIncreaseY;
-  UInt m_uiSaoBitIncreaseC;  //for chroma
-  UInt m_uiQP;
-
-  Pel   *m_pClipTable;
-  Pel   *m_pClipTableBase;
-  Pel   *m_lumaTableBo;
-  Pel   *m_pChromaClipTable;
-  Pel   *m_pChromaClipTableBase;
-  Pel   *m_chromaTableBo;
-  Int   *m_iUpBuff1;
-  Int   *m_iUpBuff2;
-  Int   *m_iUpBufft;
-  Int   *ipSwap;
-  Bool  m_bUseNIF;       //!< true for performing non-cross slice boundary ALF
-  TComPicYuv* m_pcYuvTmp;    //!< temporary picture buffer pointer when non-across slice/tile boundary SAO is enabled
-
-  Pel* m_pTmpU1;
-  Pel* m_pTmpU2;
-  Pel* m_pTmpL1;
-  Pel* m_pTmpL2;
-  Int     m_maxNumOffsetsPerPic;
-  Bool    m_saoLcuBoundary;
-  Bool    m_saoLcuBasedOptimization;
-
-  Void xPCMRestoration        (TComPic* pcPic);
-  Void xPCMCURestoration      (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth);
-  Void xPCMSampleRestoration  (TComDataCU* pcCU, UInt uiAbsZorderIdx, UInt uiDepth, TextType ttText);
-public:
-  TComSampleAdaptiveOffset         ();
-  virtual ~TComSampleAdaptiveOffset();
-
-  Void create( UInt uiSourceWidth, UInt uiSourceHeight, UInt uiMaxCUWidth, UInt uiMaxCUHeight );
-  Void destroy ();
-
-  Int  convertLevelRowCol2Idx(Int level, Int row, Int col);
-
-  Void initSAOParam   (SAOParam *pcSaoParam, Int iPartLevel, Int iPartRow, Int iPartCol, Int iParentPartIdx, Int StartCUX, Int EndCUX, Int StartCUY, Int EndCUY, Int iYCbCr);
-  Void allocSaoParam  (SAOParam* pcSaoParam);
-  Void resetSAOParam  (SAOParam *pcSaoParam);
-  static Void freeSaoParam   (SAOParam *pcSaoParam);
-  
-  Void SAOProcess(SAOParam* pcSaoParam);
-  Void processSaoCu(Int iAddr, Int iSaoType, Int iYCbCr);
-  Pel* getPicYuvAddr(TComPicYuv* pcPicYuv, Int iYCbCr,Int iAddr = 0);
-
-  Void processSaoCuOrg(Int iAddr, Int iPartIdx, Int iYCbCr);  //!< LCU-basd SAO process without slice granularity 
-  Void createPicSaoInfo(TComPic* pcPic);
-  Void destroyPicSaoInfo();
-  Void processSaoBlock(Pel* pDec, Pel* pRest, Int stride, Int iSaoType, UInt width, UInt height, Bool* pbBorderAvail, Int iYCbCr);
-
-  Void resetLcuPart(SaoLcuParam* saoLcuParam);
-  Void convertQT2SaoUnit(SAOParam* saoParam, UInt partIdx, Int yCbCr);
-  Void convertOnePart2SaoUnit(SAOParam *saoParam, UInt partIdx, Int yCbCr);
-  Void processSaoUnitAll(SaoLcuParam* saoLcuParam, Bool oneUnitFlag, Int yCbCr);
-  Void setSaoLcuBoundary (Bool bVal)  {m_saoLcuBoundary = bVal;}
-  Bool getSaoLcuBoundary ()           {return m_saoLcuBoundary;}
-  Void setSaoLcuBasedOptimization (Bool bVal)  {m_saoLcuBasedOptimization = bVal;}
-  Bool getSaoLcuBasedOptimization ()           {return m_saoLcuBasedOptimization;}
-  Void resetSaoUnit(SaoLcuParam* saoUnit);
-  Void copySaoUnit(SaoLcuParam* saoUnitDst, SaoLcuParam* saoUnitSrc );
-  Void PCMLFDisableProcess    ( TComPic* pcPic);                        ///< interface function for ALF process 
-};
-
-#endif
 
 //! \}
Index: trunk/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComSlice.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComSlice.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -143,7 +143,5 @@
   initWpAcDcParam();
   m_saoEnabledFlag = false;
-#if HM_CLEANUP_SAO
   m_saoEnabledFlagChroma = false;
-#endif
 }
 
@@ -987,5 +985,7 @@
 {
   TComPic*                 rpcPic;
+#if !FIX1172
   setAssociatedIRAPPOC(pocCRA);
+#endif
   Int pocCurr = getPOC(); 
 
@@ -1277,4 +1277,10 @@
   {
     rpcPic = *(iterPic++);
+#if BUGFIX_INTRAPERIOD
+    if(!rpcPic->getReconMark())
+    {
+      continue;
+    }
+#endif
     if (rpcPic->getPOC() == this->getPOC())
     {
@@ -1373,4 +1379,6 @@
   }
 }
+
+
 
 /** Function for applying picture marking based on the Reference Picture Set in pReferencePictureSet.
@@ -2176,21 +2184,21 @@
 {
   // For layer 0
-  setNumLayersInIdList(0, 1);
-  setLayerSetLayerIdList(0, 0, 0);
-
+  m_numLayerInIdList[0] = 1;
+  m_layerSetLayerIdList[0][0] = 0;
+  
   // For other layers
   Int i, m, n;
-  for( i = 1; i <= getNumLayerSets() - 1; i++ )
+  for( i = 1; i <= m_numLayerSets - 1; i++ )
   {
     n = 0;
-    for( m = 0; m <= this->getMaxLayerId(); m++)
-    {
-      if(this->getLayerIdIncludedFlag(i, m))
-      {
-        setLayerSetLayerIdList(i, n, m);
+    for( m = 0; m <= m_maxLayerId; m++)
+    {
+      if( m_layerIdIncludedFlag[i][m] )
+      {
+        m_layerSetLayerIdList[i][n] = m;
         n++;
       }
     }
-    setNumLayersInIdList(i, n);
+    m_numLayerInIdList[i] = n;
   }
 }
@@ -2505,5 +2513,4 @@
 , m_qpBDOffsetY               (  0)
 , m_qpBDOffsetC               (  0)
-, m_useLossless               (false)
 , m_uiPCMBitDepthLuma         (  8)
 , m_uiPCMBitDepthChroma       (  8)
Index: trunk/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComSlice.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComSlice.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -714,5 +714,5 @@
   UInt    getNumReorderPics(UInt tLayer)                        { return m_numReorderPics[tLayer]; }
   
-  Void    setMaxDecPicBuffering(UInt v, UInt tLayer)            { m_uiMaxDecPicBuffering[tLayer] = v;    }
+  Void    setMaxDecPicBuffering(UInt v, UInt tLayer)            { assert(tLayer < MAX_TLAYER); m_uiMaxDecPicBuffering[tLayer] = v;    }
   UInt    getMaxDecPicBuffering(UInt tLayer)                    { return m_uiMaxDecPicBuffering[tLayer]; }
   
@@ -1320,6 +1320,4 @@
   Int         m_qpBDOffsetC;
 
-  Bool        m_useLossless;
-
   UInt        m_uiPCMBitDepthLuma;
   UInt        m_uiPCMBitDepthChroma;
@@ -1340,7 +1338,5 @@
   Bool        m_scalingListEnabledFlag;
   Bool        m_scalingListPresentFlag;
-
   TComScalingList*     m_scalingList;   //!< ScalingList class pointer
-
   UInt        m_uiMaxDecPicBuffering[MAX_TLAYER]; 
   UInt        m_uiMaxLatencyIncrease[MAX_TLAYER];  // Really max latency increase plus 1 (value 0 expresses no limit)
@@ -1456,8 +1452,4 @@
   UInt getMaxTrSize   ()         { return  m_uiMaxTrSize;   }
   
-  // Tool list
-  Bool getUseLossless ()         { return m_useLossless; }
-  Void setUseLossless ( Bool b ) { m_useLossless  = b; }
-  
   // AMP accuracy
   Int       getAMPAcc   ( UInt uiDepth ) { return m_iAMPAcc[uiDepth]; }
@@ -1499,7 +1491,6 @@
 #endif
   TComScalingList* getScalingList ()       { return m_scalingList; }               //!< get ScalingList class pointer in SPS
-
   UInt getMaxDecPicBuffering  (UInt tlayer)            { return m_uiMaxDecPicBuffering[tlayer]; }
-  Void setMaxDecPicBuffering  ( UInt ui, UInt tlayer ) { m_uiMaxDecPicBuffering[tlayer] = ui;   }
+  Void setMaxDecPicBuffering  ( UInt ui, UInt tlayer ) { assert(tlayer < MAX_TLAYER);  m_uiMaxDecPicBuffering[tlayer] = ui;   }
   UInt getMaxLatencyIncrease  (UInt tlayer)            { return m_uiMaxLatencyIncrease[tlayer];   }
   Void setMaxLatencyIncrease  ( UInt ui , UInt tlayer) { m_uiMaxLatencyIncrease[tlayer] = ui;      }
Index: trunk/source/Lib/TLibCommon/TComTrQuant.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -1082,5 +1082,5 @@
     UInt uiLog2TrSize = g_aucConvertToBit[ iWidth ] + 2;
     Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eTType];
-    assert(scalingListType < 6);
+    assert(scalingListType < SCALING_LIST_NUM);
     Int *piQuantCoeff = 0;
     piQuantCoeff = getQuantCoeff(scalingListType,m_cQP.m_iRem,uiLog2TrSize-2);
@@ -1321,5 +1321,5 @@
     Pel* pResi = rpcResidual + uiAddr;
     Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eTxt];
-    assert(scalingListType < 6);
+    assert(scalingListType < SCALING_LIST_NUM);
     invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), eTxt, REG_DCT, pResi, uiStride, rpcCoeff, uiWidth, uiHeight, scalingListType, pcCU->getTransformSkip(uiAbsPartIdx, eTxt) );
   }
@@ -1522,5 +1522,5 @@
   const UInt uiMaxNumCoeff       = uiWidth * uiHeight;
   Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eTType];
-  assert(scalingListType < 6);
+  assert(scalingListType < SCALING_LIST_NUM);
   
   Int iQBits = QUANT_SHIFT + m_cQP.m_iPer + iTransformShift;                   // Right shift of non-RDOQ quantizer;  level = (coeff*uiQ + offset)>>q_bits
Index: trunk/source/Lib/TLibCommon/TComTrQuant.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComTrQuant.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComTrQuant.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComWeightPrediction.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComWeightPrediction.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TComYuv.cpp
===================================================================
--- trunk/source/Lib/TLibCommon/TComYuv.cpp	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComYuv.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -604,7 +604,7 @@
     {
 #if DISABLING_CLIP_FOR_BIPREDME
-      pDst[x ] = (pDst[x ]<<1) - pSrc[x ] ;
+      pDst[x ] = 2 * pDst[x] - pSrc[x];
 #else
-      pDst[x ] = Clip( (pDst[x ]<<1) - pSrc[x ] );
+      pDst[x ] = ClipY(2 * pDst[x] - pSrc[x]);
 #endif
     }
@@ -624,9 +624,9 @@
     {
 #if DISABLING_CLIP_FOR_BIPREDME
-      pDstU[x ] = (pDstU[x ]<<1) - pSrcU[x ] ;
-      pDstV[x ] = (pDstV[x ]<<1) - pSrcV[x ] ;
+      pDstU[x ] = 2 * pDstU[x] - pSrcU[x];
+      pDstV[x ] = 2 * pDstV[x] - pSrcV[x];
 #else
-      pDstU[x ] = Clip( (pDstU[x ]<<1) - pSrcU[x ] );
-      pDstV[x ] = Clip( (pDstV[x ]<<1) - pSrcV[x ] );
+      pDstU[x ] = ClipC(2 * pDstU[x] - pSrcU[x]);
+      pDstV[x ] = ClipC(2 * pDstV[x] - pSrcV[x]);
 #endif
     }
Index: trunk/source/Lib/TLibCommon/TComYuv.h
===================================================================
--- trunk/source/Lib/TLibCommon/TComYuv.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TComYuv.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibCommon/TypeDef.h
===================================================================
--- trunk/source/Lib/TLibCommon/TypeDef.h	(revision 588)
+++ trunk/source/Lib/TLibCommon/TypeDef.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -59,4 +59,7 @@
 #define RESOLUTION_BASED_DPB             1      ///< JCTVC-P0192: Assign layers to sub-DPBs based on the rep_format() signaled in the VPS
 #define SUB_BITSTREAM_PROPERTY_SEI       1      ///< JCTVC-P0204: Sub-bitstream property SEI message
+#if SUB_BITSTREAM_PROPERTY_SEI
+#define MAX_SUB_STREAMS                  1024
+#endif
 #define O0109_O0199_FLAGS_TO_VUI         1      ///< JCTVC-O0109, O0199: move single_layer_for_non_irap_flag and higher_layer_flag to vps_vui
 #define O0109_VIEW_ID_LEN                1      ///< JCTVC-O0109: view_id_len_minus1 to view_id_len, and add constraint (1<<view_id_len) is greater than or equal to NumViews
@@ -112,4 +115,7 @@
 #if VPS_EXTNS
 #define VPS_EXTN_MASK_AND_DIM_INFO       1      ///< Include avc_base_layer_flag, splitting_flag, scalability mask and dimension related info
+#if VPS_EXTN_MASK_AND_DIM_INFO
+#define MAX_VPS_NUM_SCALABILITY_TYPES    16
+#endif
 #define VPS_EXTN_OP_LAYER_SETS           1      ///< Include output layer sets in VPS extension
 #define VPS_EXTN_PROFILE_INFO            1      ///< Include profile information for layer sets in VPS extension
@@ -222,4 +228,13 @@
 #define O0149_CROSS_LAYER_BLA_FLAG       1      ///< JCTVC-O0149: signal cross_layer_bla_flag in slice header
 
+#if VIEW_ID_RELATED_SIGNALING
+/// scalability types
+enum ScalabilityType
+{
+  VIEW_ORDER_INDEX  = 1,
+  SCALABILITY_ID = 2,
+};
+#endif
+
 #else
 #define SYNTAX_OUTPUT                    0
@@ -229,9 +244,8 @@
 //! \ingroup TLibCommon
 //! \{
-
-#define HM_CLEANUP_SAO                  1  ///< JCTVC-N0230, 1) three SAO encoder-only software bugfixes. 2) new SAO implementation without picture quadtree, fine-grained slice legacies, and other redundancies.
-#if HM_CLEANUP_SAO  
+#define BUGFIX_INTRAPERIOD 1
 #define SAO_ENCODE_ALLOW_USE_PREDEBLOCK 1
-#endif
+
+#define FIX1172 1 ///< fix ticket #1172
 
 #define MAX_NUM_PICS_IN_SOP           1024
@@ -240,9 +254,6 @@
 #define MAX_NESTING_NUM_LAYER       64
 
-#if VPS_EXTN_MASK_AND_DIM_INFO
-#define MAX_VPS_NUM_SCALABILITY_TYPES             16
-#endif
+#if VPS_RENAME
 #define MAX_VPS_OP_LAYER_SETS_PLUS1               3
-#if VPS_RENAME
 #define MAX_VPS_LAYER_SETS_PLUS1                  1024
 #define MAX_VPS_LAYER_ID_PLUS1                    MAX_LAYERS
@@ -253,8 +264,4 @@
 #endif
 
-#if SUB_BITSTREAM_PROPERTY_SEI
-#define MAX_SUB_STREAMS                           1024
-#endif
-
 #define MAX_CPB_CNT                     32  ///< Upper bound of (cpb_cnt_minus1 + 1)
 #if O0137_MAX_LAYERID
@@ -277,7 +284,4 @@
 #define C1FLAG_NUMBER               8 // maximum number of largerThan1 flag coded in one chunk :  16 in HM5
 #define C2FLAG_NUMBER               1 // maximum number of largerThan2 flag coded in one chunk:  16 in HM5 
-#if !HM_CLEANUP_SAO
-#define REMOVE_SAO_LCU_ENC_CONSTRAINTS_3 1  ///< disable the encoder constraint that conditionally disable SAO for chroma for entire slice in interleaved mode
-#endif
 #define SAO_ENCODING_CHOICE              1  ///< I0184: picture early termination
 #if SAO_ENCODING_CHOICE
@@ -383,5 +387,9 @@
 typedef       bool                Bool;
 
+#ifdef __arm__
+typedef       signed char         Char;
+#else
 typedef       char                Char;
+#endif
 typedef       unsigned char       UChar;
 typedef       short               Short;
@@ -432,5 +440,4 @@
 };
 
-#if HM_CLEANUP_SAO
 enum SAOComponentIdx
 {
@@ -523,78 +530,4 @@
 };
 
-
-#else
-#define NUM_DOWN_PART 4
-
-enum SAOTypeLen
-{
-  SAO_EO_LEN    = 4, 
-  SAO_BO_LEN    = 4,
-  SAO_MAX_BO_CLASSES = 32
-};
-
-enum SAOType
-{
-  SAO_EO_0 = 0, 
-  SAO_EO_1,
-  SAO_EO_2, 
-  SAO_EO_3,
-  SAO_BO,
-  MAX_NUM_SAO_TYPE
-};
-
-typedef struct _SaoQTPart
-{
-  Int         iBestType;
-  Int         iLength;
-  Int         subTypeIdx ;                 ///< indicates EO class or BO band position
-  Int         iOffset[4];
-  Int         StartCUX;
-  Int         StartCUY;
-  Int         EndCUX;
-  Int         EndCUY;
-
-  Int         PartIdx;
-  Int         PartLevel;
-  Int         PartCol;
-  Int         PartRow;
-
-  Int         DownPartsIdx[NUM_DOWN_PART];
-  Int         UpPartIdx;
-
-  Bool        bSplit;
-
-  //---- encoder only start -----//
-  Bool        bProcessed;
-  Double      dMinCost;
-  Int64       iMinDist;
-  Int         iMinRate;
-  //---- encoder only end -----//
-} SAOQTPart;
-
-typedef struct _SaoLcuParam
-{
-  Bool       mergeUpFlag;
-  Bool       mergeLeftFlag;
-  Int        typeIdx;
-  Int        subTypeIdx;                  ///< indicates EO class or BO band position
-  Int        offset[4];
-  Int        partIdx;
-  Int        partIdxTmp;
-  Int        length;
-} SaoLcuParam;
-
-struct SAOParam
-{
-  Bool       bSaoFlag[2];
-  SAOQTPart* psSaoPart[3];
-  Int        iMaxSplitLevel;
-  Bool         oneUnitFlag[3];
-  SaoLcuParam* saoLcuParam[3];
-  Int          numCuInHeight;
-  Int          numCuInWidth;
-  ~SAOParam();
-};
-#endif
 /// parameters for deblocking filter
 typedef struct _LFCUParam
@@ -788,12 +721,4 @@
   };
 }
-#if VIEW_ID_RELATED_SIGNALING
-/// scalability types
-  enum ScalabilityType
-  {
-    VIEW_ORDER_INDEX  = 1,
-    SCALABILITY_ID = 2,
-  };
-#endif
 //! \}
 
Index: trunk/source/Lib/TLibDecoder/AnnexBread.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/AnnexBread.cpp	(revision 588)
+++ trunk/source/Lib/TLibDecoder/AnnexBread.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibDecoder/AnnexBread.h
===================================================================
--- trunk/source/Lib/TLibDecoder/AnnexBread.h	(revision 588)
+++ trunk/source/Lib/TLibDecoder/AnnexBread.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibDecoder/NALread.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/NALread.cpp	(revision 588)
+++ trunk/source/Lib/TLibDecoder/NALread.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -70,4 +70,5 @@
         break;
       }
+      assert(*it_read <= 0x03);
     }
     zeroCount = (*it_read == 0x00) ? zeroCount+1 : 0;
Index: trunk/source/Lib/TLibDecoder/NALread.h
===================================================================
--- trunk/source/Lib/TLibDecoder/NALread.h	(revision 588)
+++ trunk/source/Lib/TLibDecoder/NALread.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibDecoder/SEIread.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/SEIread.cpp	(revision 588)
+++ trunk/source/Lib/TLibDecoder/SEIread.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -93,4 +93,11 @@
     fprintf( g_hTrace, "===========Tone Mapping Info SEI message ===========\n");
     break;
+  case SEI::SOP_DESCRIPTION:
+    fprintf( g_hTrace, "=========== SOP Description SEI message ===========\n");
+    break;
+  case SEI::SCALABLE_NESTING:
+    fprintf( g_hTrace, "=========== Scalable Nesting SEI message ===========\n");
+    break;
+#if SVC_EXTENSION
 #if LAYERS_NOT_PRESENT_SEI
   case SEI::LAYERS_NOT_PRESENT:
@@ -98,7 +105,4 @@
     break;
 #endif
-  case SEI::SOP_DESCRIPTION:
-    fprintf( g_hTrace, "=========== SOP Description SEI message ===========\n");
-    break;
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
   case SEI::INTER_LAYER_CONSTRAINED_TILE_SETS:
@@ -111,7 +115,5 @@
       break;
 #endif
-  case SEI::SCALABLE_NESTING:
-    fprintf( g_hTrace, "=========== Scalable Nesting SEI message ===========\n");
-    break;
+#endif //SVC_EXTENSION
   default:
     fprintf( g_hTrace, "=========== Unknown SEI message ===========\n");
@@ -259,33 +261,8 @@
       xParseSEIToneMappingInfo((SEIToneMappingInfo&) *sei, payloadSize);
       break;
-#if LAYERS_NOT_PRESENT_SEI
-    case SEI::LAYERS_NOT_PRESENT:
-      if (!vps)
-      {
-        printf ("Warning: Found Layers not present SEI message, but no active VPS is available. Ignoring.");
-      }
-      else
-      {
-        sei = new SEILayersNotPresent;
-        xParseSEILayersNotPresent((SEILayersNotPresent&) *sei, payloadSize, vps);
-      }
-      break;
-#endif
     case SEI::SOP_DESCRIPTION:
       sei = new SEISOPDescription;
       xParseSEISOPDescription((SEISOPDescription&) *sei, payloadSize);
       break;
-#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
-    case SEI::INTER_LAYER_CONSTRAINED_TILE_SETS:
-      sei = new SEIInterLayerConstrainedTileSets;
-      xParseSEIInterLayerConstrainedTileSets((SEIInterLayerConstrainedTileSets&) *sei, payloadSize);
-      break;
-#endif
-#if SUB_BITSTREAM_PROPERTY_SEI
-   case SEI::SUB_BITSTREAM_PROPERTY:
-     sei = new SEISubBitstreamProperty;
-     xParseSEISubBitstreamProperty((SEISubBitstreamProperty&) *sei);
-     break;
-#endif
     case SEI::SCALABLE_NESTING:
       sei = new SEIScalableNesting;
@@ -295,4 +272,31 @@
       xParseSEIScalableNesting((SEIScalableNesting&) *sei, nalUnitType, payloadSize, sps);
 #endif
+#if SVC_EXTENSION
+#if LAYERS_NOT_PRESENT_SEI
+    case SEI::LAYERS_NOT_PRESENT:
+      if (!vps)
+      {
+        printf ("Warning: Found Layers not present SEI message, but no active VPS is available. Ignoring.");
+      }
+      else
+      {
+        sei = new SEILayersNotPresent;
+        xParseSEILayersNotPresent((SEILayersNotPresent&) *sei, payloadSize, vps);
+      }
+      break;
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+    case SEI::INTER_LAYER_CONSTRAINED_TILE_SETS:
+      sei = new SEIInterLayerConstrainedTileSets;
+      xParseSEIInterLayerConstrainedTileSets((SEIInterLayerConstrainedTileSets&) *sei, payloadSize);
+      break;
+#endif
+#if SUB_BITSTREAM_PROPERTY_SEI
+   case SEI::SUB_BITSTREAM_PROPERTY:
+     sei = new SEISubBitstreamProperty;
+     xParseSEISubBitstreamProperty((SEISubBitstreamProperty&) *sei);
+     break;
+#endif
+#endif //SVC_EXTENSION
       break;
     default:
@@ -499,5 +503,10 @@
   if( !pHRD->getSubPicCpbParamsPresentFlag() )
   {
-    READ_FLAG( code, "rap_cpb_params_present_flag" );                   sei.m_rapCpbParamsPresentFlag = code;
+    READ_FLAG( code, "irap_cpb_params_present_flag" );                   sei.m_rapCpbParamsPresentFlag = code;
+  }
+  if( sei.m_rapCpbParamsPresentFlag )
+  {
+    READ_CODE( pHRD->getCpbRemovalDelayLengthMinus1() + 1, code, "cpb_delay_offset" );      sei.m_cpbDelayOffset = code;
+    READ_CODE( pHRD->getDpbOutputDelayLengthMinus1()  + 1, code, "dpb_delay_offset" );      sei.m_dpbDelayOffset = code;
   }
   //read splicing flag and cpb_removal_delay_delta
@@ -506,9 +515,4 @@
   READ_CODE( ( pHRD->getCpbRemovalDelayLengthMinus1() + 1 ), code, "au_cpb_removal_delay_delta_minus1" );
   sei.m_auCpbRemovalDelayDelta = code + 1;
-  if( sei.m_rapCpbParamsPresentFlag )
-  {
-    READ_CODE( pHRD->getCpbRemovalDelayLengthMinus1() + 1, code, "cpb_delay_offset" );      sei.m_cpbDelayOffset = code;
-    READ_CODE( pHRD->getDpbOutputDelayLengthMinus1()  + 1, code, "dpb_delay_offset" );      sei.m_dpbDelayOffset = code;
-  }
   for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
   {
@@ -752,25 +756,4 @@
 }
 
-#if LAYERS_NOT_PRESENT_SEI
-Void SEIReader::xParseSEILayersNotPresent(SEILayersNotPresent &sei, UInt payloadSize, TComVPS *vps)
-{
-  UInt uiCode;
-  UInt i = 0;
-
-  READ_UVLC( uiCode,           "lp_sei_active_vps_id" ); sei.m_activeVpsId = uiCode;
-  assert(vps->getVPSId() == sei.m_activeVpsId);
-  sei.m_vpsMaxLayers = vps->getMaxLayers();
-  for (; i < sei.m_vpsMaxLayers; i++)
-  {
-    READ_FLAG( uiCode,         "layer_not_present_flag"   ); sei.m_layerNotPresentFlag[i] = uiCode ? true : false;
-  }
-  for (; i < MAX_LAYERS; i++)
-  {
-    sei.m_layerNotPresentFlag[i] = false;
-  }
-  xParseByteAlign();
-}
-#endif
-
 Void SEIReader::xParseSEISOPDescription(SEISOPDescription &sei, UInt payloadSize)
 {
@@ -797,65 +780,4 @@
 }
 
-#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
-Void SEIReader::xParseSEIInterLayerConstrainedTileSets (SEIInterLayerConstrainedTileSets &sei, UInt payloadSize)
-{
-  UInt uiCode;
-
-  READ_FLAG( uiCode, "il_all_tiles_exact_sample_value_match_flag"   ); sei.m_ilAllTilesExactSampleValueMatchFlag = uiCode;
-  READ_FLAG( uiCode, "il_one_tile_per_tile_set_flag"                ); sei.m_ilOneTilePerTileSetFlag = uiCode;
-  if( !sei.m_ilOneTilePerTileSetFlag )
-  {
-    READ_UVLC( uiCode, "il_num_sets_in_message_minus1"                ); sei.m_ilNumSetsInMessageMinus1 = uiCode;
-    if( sei.m_ilNumSetsInMessageMinus1 )
-    {
-      READ_FLAG( uiCode, "skipped_tile_set_present_flag"                ); sei.m_skippedTileSetPresentFlag = uiCode;
-    }
-    else
-    {
-      sei.m_skippedTileSetPresentFlag = false;
-    }
-    UInt numSignificantSets = sei.m_ilNumSetsInMessageMinus1 - (sei.m_skippedTileSetPresentFlag ? 1 : 0) + 1;
-    for( UInt i = 0; i < numSignificantSets; i++ )
-    {
-      READ_UVLC( uiCode, "ilcts_id"                                     ); sei.m_ilctsId[i] = uiCode;
-      READ_UVLC( uiCode, "il_num_tile_rects_in_set_minus1"              ) ;sei.m_ilNumTileRectsInSetMinus1[i] = uiCode;
-      for( UInt j = 0; j <= sei.m_ilNumTileRectsInSetMinus1[i]; j++ )
-      {
-        READ_UVLC( uiCode, "il_top_left_tile_index"                       ); sei.m_ilTopLeftTileIndex[i][j] = uiCode;
-        READ_UVLC( uiCode, "il_bottom_right_tile_index"                   ); sei.m_ilBottomRightTileIndex[i][j] = uiCode;
-      }
-      READ_CODE( 2, uiCode, "ilc_idc"                                   ); sei.m_ilcIdc[i] = uiCode;
-      if( sei.m_ilAllTilesExactSampleValueMatchFlag )
-      {
-        READ_FLAG( uiCode, "il_exact_sample_value_match_flag"             ); sei.m_ilExactSampleValueMatchFlag[i] = uiCode;
-      }
-    }
-  }
-  else
-  {
-    READ_CODE( 2, uiCode, "all_tiles_ilc_idc"                         ); sei.m_allTilesIlcIdc = uiCode;
-  }
-
-  xParseByteAlign();
-}
-#endif
-#if SUB_BITSTREAM_PROPERTY_SEI
-Void SEIReader::xParseSEISubBitstreamProperty(SEISubBitstreamProperty &sei)
-{
-  UInt uiCode;
-  READ_CODE( 4, uiCode, "active_vps_id" );                      sei.m_activeVpsId = uiCode;
-  READ_UVLC(    uiCode, "num_additional_sub_streams_minus1" );  sei.m_numAdditionalSubStreams = uiCode + 1;
-
-  for( Int i = 0; i < sei.m_numAdditionalSubStreams; i++ )
-  {
-    READ_CODE(  2, uiCode, "sub_bitstream_mode[i]"           ); sei.m_subBitstreamMode[i] = uiCode;
-    READ_UVLC(     uiCode, "output_layer_set_idx_to_vps[i]"  ); sei.m_outputLayerSetIdxToVps[i] = uiCode;
-    READ_CODE(  3, uiCode, "highest_sub_layer_id[i]"         ); sei.m_highestSublayerId[i] = uiCode;
-    READ_CODE( 16, uiCode, "avg_bit_rate[i]"                 ); sei.m_avgBitRate[i] = uiCode;
-    READ_CODE( 16, uiCode, "max_bit_rate[i]"                 ); sei.m_maxBitRate[i] = uiCode;
-  }
-  xParseByteAlign();
-}
-#endif
 #if LAYERS_NOT_PRESENT_SEI
 Void SEIReader::xParseSEIScalableNesting(SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, TComVPS *vps, TComSPS *sps)
@@ -925,3 +847,88 @@
   }
 }
+
+#if SVC_EXTENSION
+#if LAYERS_NOT_PRESENT_SEI
+Void SEIReader::xParseSEILayersNotPresent(SEILayersNotPresent &sei, UInt payloadSize, TComVPS *vps)
+{
+  UInt uiCode;
+  UInt i = 0;
+
+  READ_UVLC( uiCode,           "lp_sei_active_vps_id" ); sei.m_activeVpsId = uiCode;
+  assert(vps->getVPSId() == sei.m_activeVpsId);
+  sei.m_vpsMaxLayers = vps->getMaxLayers();
+  for (; i < sei.m_vpsMaxLayers; i++)
+  {
+    READ_FLAG( uiCode,         "layer_not_present_flag"   ); sei.m_layerNotPresentFlag[i] = uiCode ? true : false;
+  }
+  for (; i < MAX_LAYERS; i++)
+  {
+    sei.m_layerNotPresentFlag[i] = false;
+  }
+  xParseByteAlign();
+}
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+Void SEIReader::xParseSEIInterLayerConstrainedTileSets (SEIInterLayerConstrainedTileSets &sei, UInt payloadSize)
+{
+  UInt uiCode;
+
+  READ_FLAG( uiCode, "il_all_tiles_exact_sample_value_match_flag"   ); sei.m_ilAllTilesExactSampleValueMatchFlag = uiCode;
+  READ_FLAG( uiCode, "il_one_tile_per_tile_set_flag"                ); sei.m_ilOneTilePerTileSetFlag = uiCode;
+  if( !sei.m_ilOneTilePerTileSetFlag )
+  {
+    READ_UVLC( uiCode, "il_num_sets_in_message_minus1"                ); sei.m_ilNumSetsInMessageMinus1 = uiCode;
+    if( sei.m_ilNumSetsInMessageMinus1 )
+    {
+      READ_FLAG( uiCode, "skipped_tile_set_present_flag"                ); sei.m_skippedTileSetPresentFlag = uiCode;
+    }
+    else
+    {
+      sei.m_skippedTileSetPresentFlag = false;
+    }
+    UInt numSignificantSets = sei.m_ilNumSetsInMessageMinus1 - (sei.m_skippedTileSetPresentFlag ? 1 : 0) + 1;
+    for( UInt i = 0; i < numSignificantSets; i++ )
+    {
+      READ_UVLC( uiCode, "ilcts_id"                                     ); sei.m_ilctsId[i] = uiCode;
+      READ_UVLC( uiCode, "il_num_tile_rects_in_set_minus1"              ) ;sei.m_ilNumTileRectsInSetMinus1[i] = uiCode;
+      for( UInt j = 0; j <= sei.m_ilNumTileRectsInSetMinus1[i]; j++ )
+      {
+        READ_UVLC( uiCode, "il_top_left_tile_index"                       ); sei.m_ilTopLeftTileIndex[i][j] = uiCode;
+        READ_UVLC( uiCode, "il_bottom_right_tile_index"                   ); sei.m_ilBottomRightTileIndex[i][j] = uiCode;
+      }
+      READ_CODE( 2, uiCode, "ilc_idc"                                   ); sei.m_ilcIdc[i] = uiCode;
+      if( sei.m_ilAllTilesExactSampleValueMatchFlag )
+      {
+        READ_FLAG( uiCode, "il_exact_sample_value_match_flag"             ); sei.m_ilExactSampleValueMatchFlag[i] = uiCode;
+      }
+    }
+  }
+  else
+  {
+    READ_CODE( 2, uiCode, "all_tiles_ilc_idc"                         ); sei.m_allTilesIlcIdc = uiCode;
+  }
+
+  xParseByteAlign();
+}
+#endif
+#if SUB_BITSTREAM_PROPERTY_SEI
+Void SEIReader::xParseSEISubBitstreamProperty(SEISubBitstreamProperty &sei)
+{
+  UInt uiCode;
+  READ_CODE( 4, uiCode, "active_vps_id" );                      sei.m_activeVpsId = uiCode;
+  READ_UVLC(    uiCode, "num_additional_sub_streams_minus1" );  sei.m_numAdditionalSubStreams = uiCode + 1;
+
+  for( Int i = 0; i < sei.m_numAdditionalSubStreams; i++ )
+  {
+    READ_CODE(  2, uiCode, "sub_bitstream_mode[i]"           ); sei.m_subBitstreamMode[i] = uiCode;
+    READ_UVLC(     uiCode, "output_layer_set_idx_to_vps[i]"  ); sei.m_outputLayerSetIdxToVps[i] = uiCode;
+    READ_CODE(  3, uiCode, "highest_sub_layer_id[i]"         ); sei.m_highestSublayerId[i] = uiCode;
+    READ_CODE( 16, uiCode, "avg_bit_rate[i]"                 ); sei.m_avgBitRate[i] = uiCode;
+    READ_CODE( 16, uiCode, "max_bit_rate[i]"                 ); sei.m_maxBitRate[i] = uiCode;
+  }
+  xParseByteAlign();
+}
+#endif
+#endif //SVC_EXTENSION
+
 //! \}
Index: trunk/source/Lib/TLibDecoder/SEIread.h
===================================================================
--- trunk/source/Lib/TLibDecoder/SEIread.h	(revision 588)
+++ trunk/source/Lib/TLibDecoder/SEIread.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibDecoder/SyntaxElementParser.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 588)
+++ trunk/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 595)
@@ -4,5 +4,5 @@
 * granted under this license.  
 *
-* Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
 * All rights reserved.
 *
Index: trunk/source/Lib/TLibDecoder/SyntaxElementParser.h
===================================================================
--- trunk/source/Lib/TLibDecoder/SyntaxElementParser.h	(revision 588)
+++ trunk/source/Lib/TLibDecoder/SyntaxElementParser.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibDecoder/TDecBinCoder.h
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.h
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibDecoder/TDecCAVLC.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 595)
@@ -4,5 +4,5 @@
 * granted under this license.
 *
-* Copyright (c) 2010-2013, ITU/ISO/IEC
+* Copyright (c) 2010-2014, ITU/ISO/IEC
 * All rights reserved.
 *
@@ -673,4 +673,10 @@
   READ_UVLC( uiCode, "log2_diff_max_min_coding_block_size" );
   pcSPS->setLog2DiffMaxMinCodingBlockSize(uiCode);
+  
+  if (pcSPS->getPTL()->getGeneralPTL()->getLevelIdc() >= Level::LEVEL5)
+  {
+    assert(log2MinCUSize + pcSPS->getLog2DiffMaxMinCodingBlockSize() >= 5);
+  }
+  
   Int maxCUDepthDelta = uiCode;
   pcSPS->setMaxCUWidth  ( 1<<(log2MinCUSize + maxCUDepthDelta) );
Index: trunk/source/Lib/TLibDecoder/TDecCAVLC.h
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibDecoder/TDecCu.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecCu.cpp	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecCu.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -532,4 +532,6 @@
   m_pcPrediction->predIntraLumaAng( pcCU->getPattern(), uiLumaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );
   
+  if ( pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiTrDepth ) )
+  {
   //===== inverse transform =====
 #if REPN_FORMAT_IN_VPS
@@ -540,5 +542,5 @@
 
   Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)TEXT_LUMA];
-  assert(scalingListType < 6);
+    assert(scalingListType < SCALING_LIST_NUM);
   m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA, pcCU->getLumaIntraDir( uiAbsPartIdx ), piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkip );
 
@@ -560,4 +562,23 @@
     pReco     += uiStride;
     pRecIPred += uiRecIPredStride;
+  }
+  }
+  else
+  {
+    //===== reconstruction =====
+    Pel* pPred      = piPred;
+    Pel* pReco      = piReco;
+    Pel* pRecIPred  = piRecIPred;
+    for ( Int y = 0; y < uiHeight; y++ )
+    {
+      for ( Int x = 0; x < uiWidth; x++ )
+      {
+        pReco    [ x ] = pPred[ x ];
+        pRecIPred[ x ] = pReco[ x ];
+      }
+      pPred     += uiStride;
+      pReco     += uiStride;
+      pRecIPred += uiRecIPredStride;
+    }
   }
 }
@@ -624,4 +645,6 @@
   m_pcPrediction->predIntraChromaAng( pPatChroma, uiChromaPredMode, piPred, uiStride, uiWidth, uiHeight, bAboveAvail, bLeftAvail );  
 
+  if ( pcCU->getCbf( uiAbsPartIdx, eText, uiTrDepth ) )
+  {
   //===== inverse transform =====
   Int curChromaQpOffset;
@@ -646,5 +669,5 @@
 
   Int scalingListType = (pcCU->isIntra(uiAbsPartIdx) ? 0 : 3) + g_eTTable[(Int)eText];
-  assert(scalingListType < 6);
+    assert(scalingListType < SCALING_LIST_NUM);
   m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), eText, REG_DCT, piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkipChroma );
 
@@ -665,4 +688,23 @@
     pReco     += uiStride;
     pRecIPred += uiRecIPredStride;
+  }
+  }
+  else
+  {
+    //===== reconstruction =====
+    Pel* pPred      = piPred;
+    Pel* pReco      = piReco;
+    Pel* pRecIPred  = piRecIPred;
+    for ( Int y = 0; y < uiHeight; y++ )
+    {
+      for ( Int x = 0; x < uiWidth; x++ )
+      {
+        pReco    [ x ] = pPred[ x ];
+        pRecIPred[ x ] = pReco[ x ];
+      }
+      pPred     += uiStride;
+      pReco     += uiStride;
+      pRecIPred += uiRecIPredStride;
+    }    
   }
 }
Index: trunk/source/Lib/TLibDecoder/TDecCu.h
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecCu.h	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecCu.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibDecoder/TDecEntropy.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -319,5 +319,5 @@
 }
 
-Void TDecEntropy::xDecodeTransform( TComDataCU* pcCU, UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, Bool& bCodeDQP)
+Void TDecEntropy::xDecodeTransform( TComDataCU* pcCU, UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, Bool& bCodeDQP, Int quadtreeTULog2MinSizeInCU)
 {
   UInt uiSubdiv;
@@ -343,5 +343,5 @@
   else if( (pcCU->getSlice()->getSPS()->getQuadtreeTUMaxDepthInter() == 1) && (pcCU->getPredictionMode(uiAbsPartIdx) == MODE_INTER) && ( pcCU->getPartitionSize(uiAbsPartIdx) != SIZE_2Nx2N ) && (uiDepth == pcCU->getDepth(uiAbsPartIdx)) )
   {
-    uiSubdiv = (uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx));
+    uiSubdiv = (uiLog2TrafoSize > quadtreeTULog2MinSizeInCU);
   }
   else if( uiLog2TrafoSize > pcCU->getSlice()->getSPS()->getQuadtreeTULog2MaxSize() )
@@ -353,5 +353,5 @@
     uiSubdiv = 0;
   }
-  else if( uiLog2TrafoSize == pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) )
+  else if( uiLog2TrafoSize == quadtreeTULog2MinSizeInCU )
   {
     uiSubdiv = 0;
@@ -359,5 +359,5 @@
   else
   {
-    assert( uiLog2TrafoSize > pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx) );
+    assert( uiLog2TrafoSize > quadtreeTULog2MinSizeInCU );
     m_pcEntropyDecoderIf->parseTransformSubdivFlag( uiSubdiv, 5 - uiLog2TrafoSize );
   }
@@ -405,5 +405,5 @@
     for( Int i = 0; i < 4; i++ )
     {
-      xDecodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, uiDepth, width, height, uiTrIdx, bCodeDQP );
+      xDecodeTransform( pcCU, offsetLuma, offsetChroma, uiAbsPartIdx, uiDepth, width, height, uiTrIdx, bCodeDQP, quadtreeTULog2MinSizeInCU );
       uiYCbf |= pcCU->getCbf( uiAbsPartIdx, TEXT_LUMA, uiTrDepth+1 );
       uiUCbf |= pcCU->getCbf( uiAbsPartIdx, TEXT_CHROMA_U, uiTrDepth+1 );
@@ -553,5 +553,8 @@
     
   }
-  xDecodeTransform( pcCU, uiLumaOffset, uiChromaOffset, uiAbsPartIdx, uiDepth, uiWidth, uiHeight, 0, bCodeDQP );
+  
+  Int getQuadtreeTULog2MinSizeInCU = pcCU->getQuadtreeTULog2MinSizeInCU(uiAbsPartIdx);
+  
+  xDecodeTransform( pcCU, uiLumaOffset, uiChromaOffset, uiAbsPartIdx, uiDepth, uiWidth, uiHeight, 0, bCodeDQP, getQuadtreeTULog2MinSizeInCU );
 }
 
Index: trunk/source/Lib/TLibDecoder/TDecEntropy.h
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecEntropy.h	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecEntropy.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -167,5 +167,5 @@
   
 private:
-  Void xDecodeTransform        ( TComDataCU* pcCU, UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, Bool& bCodeDQP );
+  Void xDecodeTransform        ( TComDataCU* pcCU, UInt offsetLuma, UInt offsetChroma, UInt uiAbsPartIdx, UInt uiDepth, UInt width, UInt height, UInt uiTrIdx, Bool& bCodeDQP, Int getQuadtreeTULog2MinSizeInCU );
 
 public:
Index: trunk/source/Lib/TLibDecoder/TDecGop.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecGop.cpp	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecGop.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -128,13 +128,4 @@
   //-- For time output for each slice
   long iBeforeTime = clock();
-#if !HM_CLEANUP_SAO
-  UInt uiStartCUAddr   = pcSlice->getSliceSegmentCurStartCUAddr();
-
-  UInt uiSliceStartCuAddr = pcSlice->getSliceCurStartCUAddr();
-  if(uiSliceStartCuAddr == uiStartCUAddr)
-  {
-    m_sliceStartCUAddress.push_back(uiSliceStartCuAddr);
-  }
-#endif
   m_pcSbacDecoder->init( (TDecBinIf*)m_pcBinCABAC );
   m_pcEntropyDecoder->setEntropyDecoder (m_pcSbacDecoder);
@@ -163,10 +154,4 @@
   m_pcEntropyDecoder->setBitstream      ( ppcSubstreams[0] );
   m_pcEntropyDecoder->resetEntropy      (pcSlice);
-#if !HM_CLEANUP_SAO
-  if(uiSliceStartCuAddr == uiStartCUAddr)
-  {
-    m_LFCrossSliceBoundaryFlag.push_back( pcSlice->getLFCrossSliceBoundaryFlag());
-  }
-#endif
   m_pcSbacDecoders[0].load(m_pcSbacDecoder);
   m_pcSliceDecoder->decompressSlice( ppcSubstreams, rpcPic, m_pcSbacDecoder, m_pcSbacDecoders);
@@ -196,36 +181,10 @@
   m_pcLoopFilter->setCfg(bLFCrossTileBoundary);
   m_pcLoopFilter->loopFilterPic( rpcPic );
-#if !HM_CLEANUP_SAO
-  if(pcSlice->getSPS()->getUseSAO())
-  {
-    m_sliceStartCUAddress.push_back(rpcPic->getNumCUsInFrame()* rpcPic->getNumPartInCU());
-    rpcPic->createNonDBFilterInfo(m_sliceStartCUAddress, 0, &m_LFCrossSliceBoundaryFlag, rpcPic->getPicSym()->getNumTiles(), bLFCrossTileBoundary);
-  }
-#endif
   if( pcSlice->getSPS()->getUseSAO() )
   {
-#if HM_CLEANUP_SAO
     m_pcSAO->reconstructBlkSAOParams(rpcPic, rpcPic->getPicSym()->getSAOBlkParam());
     m_pcSAO->SAOProcess(rpcPic);
     m_pcSAO->PCMLFDisableProcess(rpcPic);
-#else
-    {
-      SAOParam *saoParam = rpcPic->getPicSym()->getSaoParam();
-      saoParam->bSaoFlag[0] = pcSlice->getSaoEnabledFlag();
-      saoParam->bSaoFlag[1] = pcSlice->getSaoEnabledFlagChroma();
-      m_pcSAO->setSaoLcuBasedOptimization(1);
-      m_pcSAO->createPicSaoInfo(rpcPic);
-      m_pcSAO->SAOProcess(saoParam);
-      m_pcSAO->PCMLFDisableProcess(rpcPic);
-      m_pcSAO->destroyPicSaoInfo();
-    }
-#endif
-  }
-#if !HM_CLEANUP_SAO
-  if(pcSlice->getSPS()->getUseSAO())
-  {
-    rpcPic->destroyNonDBFilterInfo();
-  }
-#endif
+  }
   rpcPic->compressMotion(); 
   Char c = (pcSlice->isIntra() ? 'I' : pcSlice->isInterP() ? 'P' : 'B');
@@ -291,8 +250,4 @@
   rpcPic->setOutputMark(true);
   rpcPic->setReconMark(true);
-#if !HM_CLEANUP_SAO
-  m_sliceStartCUAddress.clear();
-  m_LFCrossSliceBoundaryFlag.clear();
-#endif
 }
 
Index: trunk/source/Lib/TLibDecoder/TDecGop.h
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecGop.h	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecGop.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -83,9 +83,4 @@
   Int                   m_decodedPictureHashSEIEnabled;  ///< Checksum(3)/CRC(2)/MD5(1)/disable(0) acting on decoded picture hash SEI message
 
-#if !HM_CLEANUP_SAO
-  //! list that contains the CU address of each slice plus the end address 
-  std::vector<Int> m_sliceStartCUAddress;
-  std::vector<Bool> m_LFCrossSliceBoundaryFlag;
-#endif
 #if SVC_EXTENSION
   UInt                  m_layerId;
Index: trunk/source/Lib/TLibDecoder/TDecSbac.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -72,5 +72,4 @@
 , m_cCUAbsSCModel             ( 1,             1,               NUM_ABS_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cMVPIdxSCModel            ( 1,             1,               NUM_MVP_IDX_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUAMPSCModel             ( 1,             1,               NUM_CU_AMP_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cSaoMergeSCModel      ( 1,             1,               NUM_SAO_MERGE_FLAG_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cSaoTypeIdxSCModel        ( 1,             1,               NUM_SAO_TYPE_IDX_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
@@ -114,5 +113,4 @@
   m_cCUMergeIdxExtSCModel.initBuffer     ( sliceType, qp, (UChar*)INIT_MERGE_IDX_EXT );
   m_cCUPartSizeSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_PART_SIZE );
-  m_cCUAMPSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_CU_AMP_POS );
   m_cCUPredModeSCModel.initBuffer        ( sliceType, qp, (UChar*)INIT_PRED_MODE );
   m_cCUIntraPredSCModel.initBuffer       ( sliceType, qp, (UChar*)INIT_INTRA_PRED_MODE );
@@ -160,5 +158,4 @@
   m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT );
   m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
-  m_cCUAMPSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CU_AMP_POS );
   m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
   m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
@@ -579,5 +576,5 @@
       if (eMode == SIZE_2NxN)
       {
-        m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUAMPSCModel.get( 0, 0, 0 ));
+        m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
         if (uiSymbol == 0)
         {
@@ -588,5 +585,5 @@
       else if (eMode == SIZE_Nx2N)
       {
-        m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUAMPSCModel.get( 0, 0, 0 ));
+        m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
         if (uiSymbol == 0)
         {
@@ -1382,22 +1379,12 @@
     if (uiCode == 0)
     {
-#if HM_CLEANUP_SAO
       ruiVal = 1;
-#else
-      ruiVal = 5;
-#endif
     }
     else
     {
-#if HM_CLEANUP_SAO
       ruiVal = 2;
-#else
-      ruiVal = 1;
-#endif
-    }
-  }
-}
-
-#if HM_CLEANUP_SAO
+    }
+  }
+}
 
 Void TDecSbac::parseSaoSign(UInt& val)
@@ -1531,180 +1518,4 @@
 }
 
-#else
-
-inline Void copySaoOneLcuParam(SaoLcuParam* psDst,  SaoLcuParam* psSrc)
-{
-  Int i;
-  psDst->partIdx = psSrc->partIdx;
-  psDst->typeIdx    = psSrc->typeIdx;
-  if (psDst->typeIdx != -1)
-  {
-    psDst->subTypeIdx = psSrc->subTypeIdx ;
-    psDst->length  = psSrc->length;
-    for (i=0;i<psDst->length;i++)
-    {
-      psDst->offset[i] = psSrc->offset[i];
-    }
-  }
-  else
-  {
-    psDst->length  = 0;
-    for (i=0;i<SAO_BO_LEN;i++)
-    {
-      psDst->offset[i] = 0;
-    }
-  }
-}
-
-Void TDecSbac::parseSaoOffset(SaoLcuParam* psSaoLcuParam, UInt compIdx)
-{
-  UInt uiSymbol;
-  static Int iTypeLength[MAX_NUM_SAO_TYPE] =
-  {
-    SAO_EO_LEN,
-    SAO_EO_LEN,
-    SAO_EO_LEN,
-    SAO_EO_LEN,
-    SAO_BO_LEN
-  }; 
-
-  if (compIdx==2)
-  {
-    uiSymbol = (UInt)( psSaoLcuParam->typeIdx + 1);
-  }
-  else
-  {
-    parseSaoTypeIdx(uiSymbol);
-  }
-  psSaoLcuParam->typeIdx = (Int)uiSymbol - 1;
-  if (uiSymbol)
-  {
-    psSaoLcuParam->length = iTypeLength[psSaoLcuParam->typeIdx];
-
-    Int bitDepth = compIdx ? g_bitDepthC : g_bitDepthY;
-    Int offsetTh = 1 << min(bitDepth - 5,5);
-
-    if( psSaoLcuParam->typeIdx == SAO_BO )
-    {
-      for(Int i=0; i< psSaoLcuParam->length; i++)
-      {
-        parseSaoMaxUvlc(uiSymbol, offsetTh -1 );
-        psSaoLcuParam->offset[i] = uiSymbol;
-      }   
-      for(Int i=0; i< psSaoLcuParam->length; i++)
-      {
-        if (psSaoLcuParam->offset[i] != 0) 
-        {
-          m_pcTDecBinIf->decodeBinEP ( uiSymbol);
-          if (uiSymbol)
-          {
-            psSaoLcuParam->offset[i] = -psSaoLcuParam->offset[i] ;
-          }
-        }
-      }
-      parseSaoUflc(5, uiSymbol );
-      psSaoLcuParam->subTypeIdx = uiSymbol;
-    }
-    else if( psSaoLcuParam->typeIdx < 4 )
-    {
-      parseSaoMaxUvlc(uiSymbol, offsetTh -1 ); psSaoLcuParam->offset[0] = uiSymbol;
-      parseSaoMaxUvlc(uiSymbol, offsetTh -1 ); psSaoLcuParam->offset[1] = uiSymbol;
-      parseSaoMaxUvlc(uiSymbol, offsetTh -1 ); psSaoLcuParam->offset[2] = -(Int)uiSymbol;
-      parseSaoMaxUvlc(uiSymbol, offsetTh -1 ); psSaoLcuParam->offset[3] = -(Int)uiSymbol;
-     if (compIdx != 2)
-     {
-       parseSaoUflc(2, uiSymbol );
-       psSaoLcuParam->subTypeIdx = uiSymbol;
-       psSaoLcuParam->typeIdx += psSaoLcuParam->subTypeIdx;
-     }
-   }
-  }
-  else
-  {
-    psSaoLcuParam->length = 0;
-  }
-}
-
-Void TDecSbac::parseSaoOneLcuInterleaving(Int rx, Int ry, SAOParam* pSaoParam, TComDataCU* pcCU, Int iCUAddrInSlice, Int iCUAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp)
-{
-  Int iAddr = pcCU->getAddr();
-  UInt uiSymbol;
-  for (Int iCompIdx=0; iCompIdx<3; iCompIdx++)
-  {
-    pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag    = 0;
-    pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag  = 0;
-    pSaoParam->saoLcuParam[iCompIdx][iAddr].subTypeIdx     = 0;
-    pSaoParam->saoLcuParam[iCompIdx][iAddr].typeIdx        = -1;
-    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[0]     = 0;
-    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[1]     = 0;
-    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[2]     = 0;
-    pSaoParam->saoLcuParam[iCompIdx][iAddr].offset[3]     = 0;
-
-  }
- if (pSaoParam->bSaoFlag[0] || pSaoParam->bSaoFlag[1] )
-  {
-    if (rx>0 && iCUAddrInSlice!=0 && allowMergeLeft)
-    {
-      parseSaoMerge(uiSymbol); 
-      pSaoParam->saoLcuParam[0][iAddr].mergeLeftFlag = (Bool)uiSymbol;  
-    }
-    if (pSaoParam->saoLcuParam[0][iAddr].mergeLeftFlag==0)
-    {
-      if ((ry > 0) && (iCUAddrUpInSlice>=0) && allowMergeUp)
-      {
-        parseSaoMerge(uiSymbol);
-        pSaoParam->saoLcuParam[0][iAddr].mergeUpFlag = (Bool)uiSymbol;
-      }
-    }
-  }
-
-  for (Int iCompIdx=0; iCompIdx<3; iCompIdx++)
-  {
-    if ((iCompIdx == 0  && pSaoParam->bSaoFlag[0]) || (iCompIdx > 0  && pSaoParam->bSaoFlag[1]) )
-    {
-      if (rx>0 && iCUAddrInSlice!=0 && allowMergeLeft)
-      {
-        pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag = pSaoParam->saoLcuParam[0][iAddr].mergeLeftFlag;
-      }
-      else
-      {
-        pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag = 0;
-      }
-
-      if (pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeLeftFlag==0)
-      {
-        if ((ry > 0) && (iCUAddrUpInSlice>=0) && allowMergeUp)
-        {
-          pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag = pSaoParam->saoLcuParam[0][iAddr].mergeUpFlag;
-        }
-        else
-        {
-          pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag = 0;
-        }
-        if (!pSaoParam->saoLcuParam[iCompIdx][iAddr].mergeUpFlag)
-        {
-          pSaoParam->saoLcuParam[2][iAddr].typeIdx = pSaoParam->saoLcuParam[1][iAddr].typeIdx;
-          parseSaoOffset(&(pSaoParam->saoLcuParam[iCompIdx][iAddr]), iCompIdx);
-        }
-        else
-        {
-          copySaoOneLcuParam(&pSaoParam->saoLcuParam[iCompIdx][iAddr], &pSaoParam->saoLcuParam[iCompIdx][iAddr-pSaoParam->numCuInWidth]);
-        }
-      }
-      else
-      {
-        copySaoOneLcuParam(&pSaoParam->saoLcuParam[iCompIdx][iAddr],  &pSaoParam->saoLcuParam[iCompIdx][iAddr-1]);
-      }
-    }
-    else
-    {
-      pSaoParam->saoLcuParam[iCompIdx][iAddr].typeIdx = -1;
-      pSaoParam->saoLcuParam[iCompIdx][iAddr].subTypeIdx = 0;
-    }
-  }
-}
-
-#endif
-
 /**
  - Initialize our contexts from the nominated source.
Index: trunk/source/Lib/TLibDecoder/TDecSbac.h
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecSbac.h	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecSbac.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -90,11 +90,6 @@
   Void  parseSaoTypeIdx           ( UInt&  ruiVal  );
   Void  parseSaoUflc              ( UInt uiLength, UInt& ruiVal     );
-#if HM_CLEANUP_SAO
   Void parseSAOBlkParam (SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail);
   Void parseSaoSign(UInt& val);
-#else
-  Void  parseSaoOneLcuInterleaving(Int rx, Int ry, SAOParam* pSaoParam, TComDataCU* pcCU, Int iCUAddrInSlice, Int iCUAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp);
-  Void  parseSaoOffset            (SaoLcuParam* psSaoLcuParam, UInt compIdx);
-#endif
 private:
   Void  xReadUnarySymbol    ( UInt& ruiSymbol, ContextModel* pcSCModel, Int iOffset );
@@ -171,5 +166,4 @@
   ContextModel3DBuffer m_cMVPIdxSCModel;
   
-  ContextModel3DBuffer m_cCUAMPSCModel;
   ContextModel3DBuffer m_cSaoMergeSCModel;
   ContextModel3DBuffer m_cSaoTypeIdxSCModel;
Index: trunk/source/Lib/TLibDecoder/TDecSlice.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -323,5 +323,4 @@
 #endif
 
-#if HM_CLEANUP_SAO
     if ( pcSlice->getSPS()->getUseSAO() )
     {
@@ -358,57 +357,4 @@
       }
     }
-#else
-    if ( pcSlice->getSPS()->getUseSAO() && (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma()) )
-    {
-      SAOParam *saoParam = rpcPic->getPicSym()->getSaoParam();
-      saoParam->bSaoFlag[0] = pcSlice->getSaoEnabledFlag();
-      if (iCUAddr == iStartCUAddr)
-      {
-        saoParam->bSaoFlag[1] = pcSlice->getSaoEnabledFlagChroma();
-      }
-      Int numCuInWidth     = saoParam->numCuInWidth;
-      Int cuAddrInSlice = iCUAddr - rpcPic->getPicSym()->getCUOrderMap(pcSlice->getSliceCurStartCUAddr()/rpcPic->getNumPartInCU());
-      Int cuAddrUpInSlice  = cuAddrInSlice - numCuInWidth;
-      Int rx = iCUAddr % numCuInWidth;
-      Int ry = iCUAddr / numCuInWidth;
-      Int allowMergeLeft = 1;
-      Int allowMergeUp   = 1;
-      if (rx!=0)
-      {
-        if (rpcPic->getPicSym()->getTileIdxMap(iCUAddr-1) != rpcPic->getPicSym()->getTileIdxMap(iCUAddr))
-        {
-          allowMergeLeft = 0;
-        }
-      }
-      if (ry!=0)
-      {
-        if (rpcPic->getPicSym()->getTileIdxMap(iCUAddr-numCuInWidth) != rpcPic->getPicSym()->getTileIdxMap(iCUAddr))
-        {
-          allowMergeUp = 0;
-        }
-      }
-      pcSbacDecoder->parseSaoOneLcuInterleaving(rx, ry, saoParam,pcCU, cuAddrInSlice, cuAddrUpInSlice, allowMergeLeft, allowMergeUp);
-    }
-    else if ( pcSlice->getSPS()->getUseSAO() )
-    {
-      Int addr = pcCU->getAddr();
-      SAOParam *saoParam = rpcPic->getPicSym()->getSaoParam();
-      for (Int cIdx=0; cIdx<3; cIdx++)
-      {
-        SaoLcuParam *saoLcuParam = &(saoParam->saoLcuParam[cIdx][addr]);
-        if ( ((cIdx == 0) && !pcSlice->getSaoEnabledFlag()) || ((cIdx == 1 || cIdx == 2) && !pcSlice->getSaoEnabledFlagChroma()))
-        {
-          saoLcuParam->mergeUpFlag   = 0;
-          saoLcuParam->mergeLeftFlag = 0;
-          saoLcuParam->subTypeIdx    = 0;
-          saoLcuParam->typeIdx       = -1;
-          saoLcuParam->offset[0]     = 0;
-          saoLcuParam->offset[1]     = 0;
-          saoLcuParam->offset[2]     = 0;
-          saoLcuParam->offset[3]     = 0;
-        }
-      }
-    }
-#endif
 
     m_pcCuDecoder->decodeCU     ( pcCU, uiIsLast );
Index: trunk/source/Lib/TLibDecoder/TDecSlice.h
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecSlice.h	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecSlice.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecTop.cpp	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecTop.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -404,7 +404,4 @@
 #endif
 #endif
-#if !HM_CLEANUP_SAO
-    rpcPic->getPicSym()->allocSaoParam(&m_cSAO);
-#endif
     m_cListPic.pushBack( rpcPic );
     
@@ -485,7 +482,4 @@
 #endif
 #endif
-#endif
-#if !HM_CLEANUP_SAO
-  rpcPic->getPicSym()->allocSaoParam(&m_cSAO);
 #endif
 }
@@ -784,22 +778,10 @@
 #if REPN_FORMAT_IN_VPS
 #if AUXILIARY_PICTURES
-#if HM_CLEANUP_SAO
   m_cSAO.create( m_apcSlicePilot->getPicWidthInLumaSamples(), m_apcSlicePilot->getPicHeightInLumaSamples(), sps->getChromaFormatIdc(), sps->getMaxCUWidth(), sps->getMaxCUHeight(), sps->getMaxCUDepth() );
 #else
-  m_cSAO.create( m_apcSlicePilot->getPicWidthInLumaSamples(), m_apcSlicePilot->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight() );
-#endif
-#else
-#if HM_CLEANUP_SAO
   m_cSAO.create( m_apcSlicePilot->getPicWidthInLumaSamples(), m_apcSlicePilot->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight(), sps->getMaxCUDepth() );
-#else
-  m_cSAO.create( m_apcSlicePilot->getPicWidthInLumaSamples(), m_apcSlicePilot->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight() );
-#endif
-#endif
-#else
-#if HM_CLEANUP_SAO
+#endif
+#else
   m_cSAO.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight(), sps->getMaxCUDepth() );
-#else
-  m_cSAO.create( sps->getPicWidthInLumaSamples(), sps->getPicHeightInLumaSamples(), sps->getMaxCUWidth(), sps->getMaxCUHeight() );
-#endif
 #endif
   m_cLoopFilter.create( sps->getMaxCUDepth() );
@@ -817,8 +799,8 @@
 {
   TComPic*&   pcPic         = m_pcPic;
+#if SVC_EXTENSION
 #if NO_CLRAS_OUTPUT_FLAG
   Bool bFirstSliceInSeq;
 #endif
-#if SVC_EXTENSION
   m_apcSlicePilot->setVPS( m_parameterSetManagerDecoder.getPrefetchedVPS(0) );
 #if OUTPUT_LAYER_SET_INDEX
@@ -831,5 +813,5 @@
 #endif
   m_apcSlicePilot->initSlice( nalu.m_layerId );
-#else
+#else //SVC_EXTENSION
   m_apcSlicePilot->initSlice();
 #endif
@@ -839,9 +821,9 @@
     m_uiSliceIdx     = 0;
   }
+  else
+  {
+    m_apcSlicePilot->copySliceInfo( pcPic->getPicSym()->getSlice(m_uiSliceIdx-1) );
+  }
   m_apcSlicePilot->setSliceIdx(m_uiSliceIdx);
-  if (!m_bFirstSliceInPicture)
-  {
-    m_apcSlicePilot->copySliceInfo( pcPic->getPicSym()->getSlice(m_uiSliceIdx-1) );
-  }
 
   m_apcSlicePilot->setNalUnitType(nalu.m_nalUnitType);
@@ -857,5 +839,4 @@
 
 #if SVC_EXTENSION
-  m_apcSlicePilot->setSliceIdx( m_uiSliceIdx ); // it should be removed if HM will reflect it in above
 #if VPS_EXTN_DIRECT_REF_LAYERS
   setRefLayerParams(m_apcSlicePilot->getVPS());
@@ -1875,4 +1856,49 @@
       return false;
       
+      
+    case NAL_UNIT_RESERVED_VCL_N10:
+    case NAL_UNIT_RESERVED_VCL_R11:
+    case NAL_UNIT_RESERVED_VCL_N12:
+    case NAL_UNIT_RESERVED_VCL_R13:
+    case NAL_UNIT_RESERVED_VCL_N14:
+    case NAL_UNIT_RESERVED_VCL_R15:
+      
+    case NAL_UNIT_RESERVED_IRAP_VCL22:
+    case NAL_UNIT_RESERVED_IRAP_VCL23:
+      
+    case NAL_UNIT_RESERVED_VCL24:
+    case NAL_UNIT_RESERVED_VCL25:
+    case NAL_UNIT_RESERVED_VCL26:
+    case NAL_UNIT_RESERVED_VCL27:
+    case NAL_UNIT_RESERVED_VCL28:
+    case NAL_UNIT_RESERVED_VCL29:
+    case NAL_UNIT_RESERVED_VCL30:
+    case NAL_UNIT_RESERVED_VCL31:
+      
+    case NAL_UNIT_FILLER_DATA:
+    case NAL_UNIT_RESERVED_NVCL41:
+    case NAL_UNIT_RESERVED_NVCL42:
+    case NAL_UNIT_RESERVED_NVCL43:
+    case NAL_UNIT_RESERVED_NVCL44:
+    case NAL_UNIT_RESERVED_NVCL45:
+    case NAL_UNIT_RESERVED_NVCL46:
+    case NAL_UNIT_RESERVED_NVCL47:
+    case NAL_UNIT_UNSPECIFIED_48:
+    case NAL_UNIT_UNSPECIFIED_49:
+    case NAL_UNIT_UNSPECIFIED_50:
+    case NAL_UNIT_UNSPECIFIED_51:
+    case NAL_UNIT_UNSPECIFIED_52:
+    case NAL_UNIT_UNSPECIFIED_53:
+    case NAL_UNIT_UNSPECIFIED_54:
+    case NAL_UNIT_UNSPECIFIED_55:
+    case NAL_UNIT_UNSPECIFIED_56:
+    case NAL_UNIT_UNSPECIFIED_57:
+    case NAL_UNIT_UNSPECIFIED_58:
+    case NAL_UNIT_UNSPECIFIED_59:
+    case NAL_UNIT_UNSPECIFIED_60:
+    case NAL_UNIT_UNSPECIFIED_61:
+    case NAL_UNIT_UNSPECIFIED_62:
+    case NAL_UNIT_UNSPECIFIED_63:
+
     default:
       assert (0);
@@ -1954,4 +1980,5 @@
 }
 
+#if SVC_EXTENSION
 #if VPS_EXTN_DIRECT_REF_LAYERS
 TDecTop* TDecTop::getRefLayerDec( UInt refLayerIdc )
@@ -1968,5 +1995,4 @@
 
 #if VPS_EXTN_DIRECT_REF_LAYERS
-
 Void TDecTop::setRefLayerParams( TComVPS* vps )
 {
@@ -2137,3 +2163,4 @@
 }
 #endif
+#endif //SVC_EXTENSION
 //! \}
Index: trunk/source/Lib/TLibDecoder/TDecTop.h
===================================================================
--- trunk/source/Lib/TLibDecoder/TDecTop.h	(revision 588)
+++ trunk/source/Lib/TLibDecoder/TDecTop.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -221,5 +221,18 @@
   Void      xInitILRP(TComSPS *pcSPS);
 #endif
-#endif
+#if OUTPUT_LAYER_SET_INDEX
+  CommonDecoderParams*    getCommonDecoderParams() { return m_commonDecoderParams; }
+  Void                    setCommonDecoderParams(CommonDecoderParams* x) { m_commonDecoderParams = x; }
+  Void      checkValueOfTargetOutputLayerSetIdx(TComVPS *vps);
+#endif
+#if SCALINGLIST_INFERRING
+  ParameterSetManagerDecoder* getParameterSetManager() { return &m_parameterSetManagerDecoder; }
+#endif
+#if RESOLUTION_BASED_DPB
+  Void setSubDpbIdx(Int idx)    { m_subDpbIdx = idx; }
+  Int  getSubDpbIdx()           { return m_subDpbIdx; }
+  Void assignSubDpbs(TComVPS *vps);
+#endif
+#endif //SVC_EXTENSION
 #if AVC_SYNTAX || SYNTAX_OUTPUT
   Void      setBLSyntaxFile( fstream* pFile ) { m_pBLSyntaxFile = pFile; }
@@ -256,18 +269,4 @@
   Void setNoOutputOfPriorPicsFlags(Bool x)   { m_noOutputOfPriorPicsFlags = x;   }
 #endif
-public:
-#if OUTPUT_LAYER_SET_INDEX
-  CommonDecoderParams*    getCommonDecoderParams() { return m_commonDecoderParams; }
-  Void                    setCommonDecoderParams(CommonDecoderParams* x) { m_commonDecoderParams = x; }
-  Void      checkValueOfTargetOutputLayerSetIdx(TComVPS *vps);
-#endif
-#if SCALINGLIST_INFERRING
-  ParameterSetManagerDecoder* getParameterSetManager() { return &m_parameterSetManagerDecoder; }
-#endif
-#if RESOLUTION_BASED_DPB
-  Void setSubDpbIdx(Int idx)    { m_subDpbIdx = idx; }
-  Int  getSubDpbIdx()           { return m_subDpbIdx; }
-  Void assignSubDpbs(TComVPS *vps);
-#endif
 };// END CLASS DEFINITION TDecTop
 
Index: trunk/source/Lib/TLibEncoder/AnnexBwrite.h
===================================================================
--- trunk/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/NALwrite.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/NALwrite.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/NALwrite.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/NALwrite.h
===================================================================
--- trunk/source/Lib/TLibEncoder/NALwrite.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/NALwrite.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/SEIwrite.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -87,4 +87,11 @@
     fprintf( g_hTrace, "=========== Tone Mapping Info SEI message ===========\n");
     break;
+  case SEI::SOP_DESCRIPTION:
+    fprintf( g_hTrace, "=========== SOP Description SEI message ===========\n");
+    break;
+  case SEI::SCALABLE_NESTING:
+    fprintf( g_hTrace, "=========== Scalable Nesting SEI message ===========\n");
+    break;
+#if SVC_EXTENSION
 #if LAYERS_NOT_PRESENT_SEI
   case SEI::LAYERS_NOT_PRESENT:
@@ -92,7 +99,4 @@
     break;
 #endif
-  case SEI::SOP_DESCRIPTION:
-    fprintf( g_hTrace, "=========== SOP Description SEI message ===========\n");
-    break;
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
   case SEI::INTER_LAYER_CONSTRAINED_TILE_SETS:
@@ -105,7 +109,5 @@
       break;
 #endif
-  case SEI::SCALABLE_NESTING:
-    fprintf( g_hTrace, "=========== Scalable Nesting SEI message ===========\n");
-    break;
+#endif //SVC_EXTENSION
   default:
     fprintf( g_hTrace, "=========== Unknown SEI message ===========\n");
@@ -155,4 +157,11 @@
     xWriteSEIToneMappingInfo(*static_cast<const SEIToneMappingInfo*>(&sei));
     break;
+  case SEI::SOP_DESCRIPTION:
+    xWriteSEISOPDescription(*static_cast<const SEISOPDescription*>(&sei));
+    break;
+  case SEI::SCALABLE_NESTING:
+    xWriteSEIScalableNesting(bs, *static_cast<const SEIScalableNesting*>(&sei), sps);
+    break;
+#if SVC_EXTENSION
 #if LAYERS_NOT_PRESENT_SEI
   case SEI::LAYERS_NOT_PRESENT:
@@ -160,7 +169,4 @@
     break;
 #endif
-  case SEI::SOP_DESCRIPTION:
-    xWriteSEISOPDescription(*static_cast<const SEISOPDescription*>(&sei));
-    break;
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
   case SEI::INTER_LAYER_CONSTRAINED_TILE_SETS:
@@ -173,7 +179,5 @@
      break;
 #endif
-  case SEI::SCALABLE_NESTING:
-    xWriteSEIScalableNesting(bs, *static_cast<const SEIScalableNesting*>(&sei), sps);
-    break;
+#endif //SVC_EXTENSION
   default:
     assert(!"Unhandled SEI message");
@@ -337,13 +341,13 @@
   if( !hrd->getSubPicCpbParamsPresentFlag() )
   {
-    WRITE_FLAG( sei.m_rapCpbParamsPresentFlag, "rap_cpb_params_present_flag" );
+    WRITE_FLAG( sei.m_rapCpbParamsPresentFlag, "irap_cpb_params_present_flag" );
+  }
+  if( sei.m_rapCpbParamsPresentFlag )
+  {
+    WRITE_CODE( sei.m_cpbDelayOffset, hrd->getCpbRemovalDelayLengthMinus1() + 1, "cpb_delay_offset" );
+    WRITE_CODE( sei.m_dpbDelayOffset, hrd->getDpbOutputDelayLengthMinus1()  + 1, "dpb_delay_offset" );
   }
   WRITE_FLAG( sei.m_concatenationFlag, "concatenation_flag");
   WRITE_CODE( sei.m_auCpbRemovalDelayDelta - 1, ( hrd->getCpbRemovalDelayLengthMinus1() + 1 ), "au_cpb_removal_delay_delta_minus1" );
-  if( sei.m_rapCpbParamsPresentFlag )
-  {
-    WRITE_CODE( sei.m_cpbDelayOffset, hrd->getCpbRemovalDelayLengthMinus1() + 1, "cpb_delay_offset" );
-    WRITE_CODE( sei.m_dpbDelayOffset, hrd->getDpbOutputDelayLengthMinus1()  + 1, "dpb_delay_offset" );
-  }
   for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ )
   {
@@ -546,16 +550,4 @@
 }
 
-#if LAYERS_NOT_PRESENT_SEI
-Void SEIWriter::xWriteSEILayersNotPresent(const SEILayersNotPresent& sei)
-{
-  WRITE_UVLC( sei.m_activeVpsId,           "lp_sei_active_vps_id" );
-  for (UInt i = 0; i < sei.m_vpsMaxLayers; i++)
-  {
-    WRITE_FLAG( sei.m_layerNotPresentFlag[i], "layer_not_present_flag"   );
-  }
-  xWriteByteAlign();
-}
-#endif
-
 Void SEIWriter::xWriteSEISOPDescription(const SEISOPDescription& sei)
 {
@@ -578,4 +570,71 @@
   xWriteByteAlign();
 }
+
+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);
+  }
+}
+
+Void SEIWriter::xWriteByteAlign()
+{
+  if( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0)
+  {
+    WRITE_FLAG( 1, "bit_equal_to_one" );
+    while( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
+    {
+      WRITE_FLAG( 0, "bit_equal_to_zero" );
+    }
+  }
+};
+
+#if SVC_EXTENSION
+#if LAYERS_NOT_PRESENT_SEI
+Void SEIWriter::xWriteSEILayersNotPresent(const SEILayersNotPresent& sei)
+{
+  WRITE_UVLC( sei.m_activeVpsId,           "lp_sei_active_vps_id" );
+  for (UInt i = 0; i < sei.m_vpsMaxLayers; i++)
+  {
+    WRITE_FLAG( sei.m_layerNotPresentFlag[i], "layer_not_present_flag"   );
+  }
+  xWriteByteAlign();
+}
+#endif
 
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
@@ -634,57 +693,5 @@
 }
 #endif
-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);
-  }
-}
-
-Void SEIWriter::xWriteByteAlign()
-{
-  if( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0)
-  {
-    WRITE_FLAG( 1, "bit_equal_to_one" );
-    while( m_pcBitIf->getNumberOfWrittenBits() % 8 != 0 )
-    {
-      WRITE_FLAG( 0, "bit_equal_to_zero" );
-    }
-  }
-};
+#endif //SVC_EXTENSION
 
 //! \}
Index: trunk/source/Lib/TLibEncoder/SEIwrite.h
===================================================================
--- trunk/source/Lib/TLibEncoder/SEIwrite.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/SEIwrite.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -64,8 +64,11 @@
   Void xWriteSEIGradualDecodingRefreshInfo(const SEIGradualDecodingRefreshInfo &sei);
   Void xWriteSEIToneMappingInfo(const SEIToneMappingInfo& sei);
+  Void xWriteSEISOPDescription(const SEISOPDescription& sei);
+  Void xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, TComSPS *sps);
+  Void xWriteByteAlign();
+#if SVC_EXTENSION
 #if LAYERS_NOT_PRESENT_SEI
   Void xWriteSEILayersNotPresent(const SEILayersNotPresent& sei);
 #endif
-  Void xWriteSEISOPDescription(const SEISOPDescription& sei);
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
   Void xWriteSEIInterLayerConstrainedTileSets(const SEIInterLayerConstrainedTileSets& sei);
@@ -74,6 +77,5 @@
   Void xWriteSEISubBitstreamProperty(const SEISubBitstreamProperty &sei);
 #endif
-  Void xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, TComSPS *sps);
-  Void xWriteByteAlign();
+#endif //SVC_EXTENSION
 };
 
Index: trunk/source/Lib/TLibEncoder/SyntaxElementWriter.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/SyntaxElementWriter.h
===================================================================
--- trunk/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/TEncAnalyze.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncAnalyze.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/TEncBinCoder.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -579,4 +579,5 @@
   }
   WRITE_FLAG( pcSPS->getTMVPFlagsPresent()  ? 1 : 0,           "sps_temporal_mvp_enable_flag" );
+
   WRITE_FLAG( pcSPS->getUseStrongIntraSmoothing(),             "sps_strong_intra_smoothing_enable_flag" );
 
@@ -1733,18 +1734,7 @@
          WRITE_FLAG( pcSlice->getSaoEnabledFlag(), "slice_sao_luma_flag" );         
 #if AUXILIARY_PICTURES
-         if (pcSlice->getChromaFormatIdc() != CHROMA_400)
-         {
-#endif
-#if HM_CLEANUP_SAO
+         if (pcSlice->getChromaFormatIdc() != CHROMA_400)         
+#endif
          WRITE_FLAG( pcSlice->getSaoEnabledFlagChroma(), "slice_sao_chroma_flag" );
-#else
-         {
-           SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
-           WRITE_FLAG( saoParam->bSaoFlag[1], "slice_sao_chroma_flag" );
-         }
-#endif
-#if AUXILIARY_PICTURES
-         }
-#endif
       }
     }   
Index: trunk/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCavlc.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncCavlc.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -88,22 +88,6 @@
   UInt  getCoeffCost          ()                { return  m_uiCoeffCost;  }
   Void  codeVPS                 ( TComVPS* pcVPS );
-#if VPS_EXTNS
-  Void  codeVPSExtension        ( TComVPS* pcVPS );
-#endif
-
-#if VPS_VUI
-  Void codeVPSVUI               (TComVPS *vps);
-#endif
-#if REPN_FORMAT_IN_VPS
-  Void  codeRepFormat           ( RepFormat *repFormat );
-#endif
-#if VPS_DPB_SIZE_TABLE
-  Void  codeVpsDpbSizeTable      (TComVPS *vps);
-#endif
   Void  codeVUI                 ( TComVUI *pcVUI, TComSPS* pcSPS );
   Void  codeSPS                 ( TComSPS* pcSPS );
-#if SPS_EXTENSION
-  Void codeSPSExtension         ( TComSPS* pcSPS );
-#endif
   Void  codePPS                 ( TComPPS* pcPPS );
   Void  codeSliceHeader         ( TComSlice* pcSlice );
@@ -116,13 +100,5 @@
   
   Void codeMVPIdx ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefList );
-#if HM_CLEANUP_SAO
   Void codeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false){printf("only supported in CABAC"); assert(0); exit(-1);}
-#else
-  Void codeSAOSign       ( UInt code   ) { printf("Not supported\n"); assert (0); }
-  Void codeSaoMaxUvlc    ( UInt   code, UInt maxSymbol ){printf("Not supported\n"); assert (0);}
-  Void codeSaoMerge  ( UInt uiCode ){printf("Not supported\n"); assert (0);}
-  Void codeSaoTypeIdx    ( UInt uiCode ){printf("Not supported\n"); assert (0);}
-  Void codeSaoUflc       ( UInt uiLength, UInt   uiCode ){ assert(uiCode < 32); printf("Not supported\n"); assert (0);}
-#endif
   Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
@@ -165,4 +141,20 @@
   Void codeDFSvlc       ( Int   iCode, const Char *pSymbolName );
 
+#if SPS_EXTENSION
+  Void codeSPSExtension         ( TComSPS* pcSPS );
+#if VPS_EXTNS
+  Void  codeVPSExtension        ( TComVPS* pcVPS );
+#endif
+#if VPS_VUI
+  Void codeVPSVUI               (TComVPS *vps);
+#endif
+#if REPN_FORMAT_IN_VPS
+  Void  codeRepFormat           ( RepFormat *repFormat );
+#endif
+#if VPS_DPB_SIZE_TABLE
+  Void  codeVpsDpbSizeTable      (TComVPS *vps);
+#endif
+#endif //SVC_EXTENSION
+
 };
 
Index: trunk/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCfg.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncCfg.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -91,26 +91,4 @@
 
 std::istringstream &operator>>(std::istringstream &in, GOPEntry &entry);     //input
-
-#if REPN_FORMAT_IN_VPS
-struct RepFormatCfg
-{
-  Int   m_chromaFormatIdc;
-  Bool  m_separateColourPlaneFlag;
-  Int   m_picWidthInLumaSamples;
-  Int   m_picHeightInLumaSamples;
-  Int   m_bitDepthLuma;
-  Int   m_bitDepthChroma;
-  RepFormatCfg()
-    : m_chromaFormatIdc         (CHROMA_420)
-    , m_separateColourPlaneFlag (0)
-    , m_picWidthInLumaSamples   (352)
-    , m_picHeightInLumaSamples  (288)
-    , m_bitDepthLuma            (8)
-    , m_bitDepthChroma          (8)
-  {}
-};
-std::istringstream &operator>>(std::istringstream &in, RepFormatCfg &repFormatCfg);
-#endif
-
 //! \ingroup TLibEncoder
 //! \{
@@ -162,20 +140,4 @@
   Int       m_maxTempLayer;                      ///< Max temporal layer
   Bool m_useAMP;
-#if VPS_EXTN_DIRECT_REF_LAYERS
-  Int       m_numDirectRefLayers;
-  Int       m_refLayerId[MAX_VPS_LAYER_ID_PLUS1];
-
-  Int       m_numActiveRefLayers;
-  Int       m_predLayerId[MAX_VPS_LAYER_ID_PLUS1];
-  Int       m_numSamplePredRefLayers;
-  Int       m_samplePredRefLayerId[MAX_VPS_LAYER_ID_PLUS1];
-  Int       m_numMotionPredRefLayers;
-  Int       m_motionPredRefLayerId[MAX_VPS_LAYER_ID_PLUS1];
-  Bool      m_samplePredEnabledFlag[MAX_VPS_LAYER_ID_PLUS1];
-  Bool      m_motionPredEnabledFlag[MAX_VPS_LAYER_ID_PLUS1];
-#endif
-#if N0120_MAX_TID_REF_CFG
-  Int       m_maxTidIlRefPicsPlus1;
-#endif 
   //======= Transform =============
   UInt      m_uiQuadtreeTULog2MaxSize;
@@ -194,9 +156,4 @@
   Int       m_maxNumOffsetsPerPic;
   Bool      m_saoLcuBoundary;
-#if !HM_CLEANUP_SAO
-  Bool      m_saoLcuBasedOptimization;
-#endif
-  //====== Lossless ========
-  Bool      m_useLossless;
   //====== Motion search ========
   Int       m_iFastSearch;                      //  0:Full search  1:Diamond  2:PMVFAST
@@ -210,7 +167,4 @@
   Int       m_chromaCbQpOffset;                 //  Chroma Cb QP Offset (0:default)
   Int       m_chromaCrQpOffset;                 //  Chroma Cr Qp Offset (0:default)
-#if AUXILIARY_PICTURES
-  ChromaFormat m_chromaFormatIDC;
-#endif
 
 #if ADAPTIVE_QP_SELECTION
@@ -222,5 +176,4 @@
   
   //====== Tool list ========
-  Bool      m_bUseSBACRD;
   Bool      m_bUseASR;
   Bool      m_bUseHADME;
@@ -233,7 +186,4 @@
   Bool      m_bUseCbfFastMode;
   Bool      m_useEarlySkipDetection;
-#if FAST_INTRA_SHVC
-  Bool      m_useFastIntraScalable;
-#endif
   Bool      m_useTransformSkip;
   Bool      m_useTransformSkipFast;
@@ -305,17 +255,6 @@
   Int       m_gradualDecodingRefreshInfoEnabled;
   Int       m_decodingUnitInfoSEIEnabled;
-#if LAYERS_NOT_PRESENT_SEI
-  Int       m_layersNotPresentSEIEnabled;
-#endif
   Int       m_SOPDescriptionSEIEnabled;
   Int       m_scalableNestingSEIEnabled;
-#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
-  Bool      m_interLayerConstrainedTileSetsSEIEnabled;
-  UInt      m_ilNumSetsInMessage;
-  Bool      m_skippedTileSetPresentFlag;
-  UInt      m_topLeftTileIndex[1024];
-  UInt      m_bottomRightTileIndex[1024];
-  UInt      m_ilcIdc[1024];
-#endif
   //====== Weighted Prediction ========
   Bool      m_useWeightedPred;       //< Use of Weighting Prediction (P_SLICE)
@@ -335,7 +274,7 @@
   Bool      m_RCForceIntraQP;
   Bool      m_TransquantBypassEnableFlag;                     ///< transquant_bypass_enable_flag setting in PPS.
-  Bool      m_CUTransquantBypassFlagValue;                    ///< if transquant_bypass_enable_flag, the fixed value to use for the per-CU cu_transquant_bypass_flag.
+  Bool      m_CUTransquantBypassFlagForce;                    ///< if transquant_bypass_enable_flag, then, if true, all CU transquant bypass flags will be set to true.
 #if SVC_EXTENSION
-  static TComVPS                    m_cVPS;
+  static TComVPS             m_cVPS;
 #else
   TComVPS                    m_cVPS;
@@ -391,5 +330,38 @@
   Bool      m_crossLayerBLAFlag;
 #endif
-#endif
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  Int       m_numDirectRefLayers;
+  Int       m_refLayerId[MAX_VPS_LAYER_ID_PLUS1];
+
+  Int       m_numActiveRefLayers;
+  Int       m_predLayerId[MAX_VPS_LAYER_ID_PLUS1];
+  Int       m_numSamplePredRefLayers;
+  Int       m_samplePredRefLayerId[MAX_VPS_LAYER_ID_PLUS1];
+  Int       m_numMotionPredRefLayers;
+  Int       m_motionPredRefLayerId[MAX_VPS_LAYER_ID_PLUS1];
+  Bool      m_samplePredEnabledFlag[MAX_VPS_LAYER_ID_PLUS1];
+  Bool      m_motionPredEnabledFlag[MAX_VPS_LAYER_ID_PLUS1];
+#endif
+#if N0120_MAX_TID_REF_CFG
+  Int       m_maxTidIlRefPicsPlus1;
+#endif 
+#if AUXILIARY_PICTURES
+  ChromaFormat m_chromaFormatIDC;
+#endif
+#if FAST_INTRA_SHVC
+  Bool      m_useFastIntraScalable;
+#endif
+#if LAYERS_NOT_PRESENT_SEI
+  Int       m_layersNotPresentSEIEnabled;
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Bool      m_interLayerConstrainedTileSetsSEIEnabled;
+  UInt      m_ilNumSetsInMessage;
+  Bool      m_skippedTileSetPresentFlag;
+  UInt      m_topLeftTileIndex[1024];
+  UInt      m_bottomRightTileIndex[1024];
+  UInt      m_ilcIdc[1024];
+#endif
+#endif //SVC_EXTENSION
 
 public:
@@ -437,39 +409,4 @@
   Bool      getMaxTempLayer                 ()                              { return m_maxTempLayer;              } 
   Void      setMaxTempLayer                 ( Int maxTempLayer )            { m_maxTempLayer = maxTempLayer;      }
-#if VPS_EXTN_DIRECT_REF_LAYERS
-  Int       getNumDirectRefLayers           ()                              { return m_numDirectRefLayers;      }
-  Void      setNumDirectRefLayers           (Int num)                       { m_numDirectRefLayers = num;       }
-
-  Int       getRefLayerId                   (Int i)                         { return m_refLayerId[i];           }
-  Void      setRefLayerId                   (Int i, Int refLayerId)         { m_refLayerId[i] = refLayerId;     }
-
-  Int       getNumActiveRefLayers           ()                              { return m_numActiveRefLayers;      }
-  Void      setNumActiveRefLayers           (Int num)                       { m_numActiveRefLayers = num;       }
-
-  Int       getPredLayerId                  (Int i)                         { return m_predLayerId[i];          }
-  Void      setPredLayerId                  (Int i, Int refLayerId)         { m_predLayerId[i] = refLayerId;    }
-
-  Int       getNumSamplePredRefLayers       ()                              { return m_numSamplePredRefLayers;  }
-  Void      setNumSamplePredRefLayers       (Int num)                       { m_numSamplePredRefLayers = num;   }
-
-  Int       getSamplePredRefLayerId         (Int i)                         { return m_samplePredRefLayerId[i];       }
-  Void      setSamplePredRefLayerId         (Int i, Int refLayerId)         { m_samplePredRefLayerId[i] = refLayerId; }
-
-  Int       getNumMotionPredRefLayers       ()                              { return m_numMotionPredRefLayers;  }
-  Void      setNumMotionPredRefLayers       (Int num)                       { m_numMotionPredRefLayers = num;   }
-
-  Int       getMotionPredRefLayerId         (Int i)                         { return m_motionPredRefLayerId[i];       }
-  Void      setMotionPredRefLayerId         (Int i, Int refLayerId)         { m_motionPredRefLayerId[i] = refLayerId; }
-
-  Bool      getSamplePredEnabledFlag        (Int i)                         { return m_samplePredEnabledFlag[i];  }
-  Void      setSamplePredEnabledFlag        (Int i,Bool flag)               { m_samplePredEnabledFlag[i] = flag;  }
-
-  Bool      getMotionPredEnabledFlag        (Int i)                         { return m_motionPredEnabledFlag[i];  }
-  Void      setMotionPredEnabledFlag        (Int i,Bool flag)               { m_motionPredEnabledFlag[i] = flag;  }
-#endif
-#if N0120_MAX_TID_REF_CFG
-  Int       getMaxTidIlRefPicsPlus1         ()                              { return m_maxTidIlRefPicsPlus1; }
-  Void      setMaxTidIlRefPicsPlus1         (Int num)                       { m_maxTidIlRefPicsPlus1 = num;  }
-#endif 
   //======== Transform =============
   Void      setQuadtreeTULog2MaxSize        ( UInt  u )      { m_uiQuadtreeTULog2MaxSize = u; }
@@ -508,6 +445,4 @@
   Void      setQPAdaptationRange            ( Int   i )      { m_iQPAdaptationRange = i; }
   
-  //====== Lossless ========
-  Void      setUseLossless                  (Bool    b  )        { m_useLossless = b;  }
   //====== Sequence ========
   Int       getFrameRate                    ()      { return  m_iFrameRate; }
@@ -552,9 +487,6 @@
   Bool      getUseAdaptiveQP                ()      { return  m_bUseAdaptiveQP; }
   Int       getQPAdaptationRange            ()      { return  m_iQPAdaptationRange; }
-  //====== Lossless ========
-  Bool      getUseLossless                  ()      { return  m_useLossless;  }
   
   //==== Tool list ========
-  Void      setUseSBACRD                    ( Bool  b )     { m_bUseSBACRD  = b; }
   Void      setUseASR                       ( Bool  b )     { m_bUseASR     = b; }
   Void      setUseHADME                     ( Bool  b )     { m_bUseHADME   = b; }
@@ -567,7 +499,4 @@
   Void      setUseCbfFastMode            ( Bool  b )     { m_bUseCbfFastMode = b; }
   Void      setUseEarlySkipDetection        ( Bool  b )     { m_useEarlySkipDetection = b; }
-#if FAST_INTRA_SHVC
-  Void      setUseFastIntraScalable         ( Bool  b )     { m_useFastIntraScalable = b; }
-#endif
   Void      setUseConstrainedIntraPred      ( Bool  b )     { m_bUseConstrainedIntraPred = b; }
   Void      setPCMInputBitDepthFlag         ( Bool  b )     { m_bPCMInputBitDepthFlag = b; }
@@ -578,5 +507,4 @@
   Void      setdQPs                         ( Int*  p )     { m_aidQP       = p; }
   Void      setDeltaQpRD                    ( UInt  u )     {m_uiDeltaQpRD  = u; }
-  Bool      getUseSBACRD                    ()      { return m_bUseSBACRD;  }
   Bool      getUseASR                       ()      { return m_bUseASR;     }
   Bool      getUseHADME                     ()      { return m_bUseHADME;   }
@@ -589,7 +517,4 @@
   Bool      getUseCbfFastMode           ()      { return m_bUseCbfFastMode; }
   Bool      getUseEarlySkipDetection        ()      { return m_useEarlySkipDetection; }
-#if FAST_INTRA_SHVC
-  Bool      getUseFastIntraScalable         ()      { return m_useFastIntraScalable; }
-#endif
   Bool      getUseConstrainedIntraPred      ()      { return m_bUseConstrainedIntraPred; }
   Bool      getPCMInputBitDepthFlag         ()      { return m_bPCMInputBitDepthFlag;   }
@@ -625,8 +550,4 @@
   Void  setSaoLcuBoundary              (Bool val)      { m_saoLcuBoundary = val; }
   Bool  getSaoLcuBoundary              ()              { return m_saoLcuBoundary; }
-#if !HM_CLEANUP_SAO
-  Void  setSaoLcuBasedOptimization               (Bool val)            { m_saoLcuBasedOptimization = val; }
-  Bool  getSaoLcuBasedOptimization               ()                    { return m_saoLcuBasedOptimization; }
-#endif
   Void  setLFCrossTileBoundaryFlag               ( Bool   val  )       { m_loopFilterAcrossTilesEnabledFlag = val; }
   Bool  getLFCrossTileBoundaryFlag               ()                    { return m_loopFilterAcrossTilesEnabledFlag;   }
@@ -748,44 +669,8 @@
   Void  setDecodingUnitInfoSEIEnabled(Int b)                { m_decodingUnitInfoSEIEnabled = b;    }
   Int   getDecodingUnitInfoSEIEnabled()                     { return m_decodingUnitInfoSEIEnabled; }
-#if LAYERS_NOT_PRESENT_SEI
-  Void  setLayersNotPresentSEIEnabled(Int b)             { m_layersNotPresentSEIEnabled = b; }
-  Int   getLayersNotPresentSEIEnabled()                  { return m_layersNotPresentSEIEnabled; }
-#endif
   Void  setSOPDescriptionSEIEnabled(Int b)                { m_SOPDescriptionSEIEnabled = b; }
   Int   getSOPDescriptionSEIEnabled()                     { return m_SOPDescriptionSEIEnabled; }
   Void  setScalableNestingSEIEnabled(Int b)                { m_scalableNestingSEIEnabled = b; }
   Int   getScalableNestingSEIEnabled()                     { return m_scalableNestingSEIEnabled; }
-#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
-  Void  setInterLayerConstrainedTileSetsSEIEnabled(Bool b) { m_interLayerConstrainedTileSetsSEIEnabled = b; }
-  Bool  getInterLayerConstrainedTileSetsSEIEnabled()       { return m_interLayerConstrainedTileSetsSEIEnabled; }
-  Void  setIlNumSetsInMessage(UInt b)                      { m_ilNumSetsInMessage = b; }
-  Int   getIlNumSetsInMessage()                            { return m_ilNumSetsInMessage; }
-  Void  setSkippedTileSetPresentFlag(Bool b)               { m_skippedTileSetPresentFlag = b; }
-  Bool  getSkippedTileSetPresentFlag()                     { return m_skippedTileSetPresentFlag; }
-  Void  setTopLeftTileIndex(UInt *b)
-  {
-    for (UInt i = 0; i < m_ilNumSetsInMessage; i++)
-    {
-      m_topLeftTileIndex[i] = b[i];
-    }
-  }
-  UInt  getTopLeftTileIndex(UInt b)                        { return m_topLeftTileIndex[b]; }
-  Void  setBottomRightTileIndex(UInt *b)
-  {
-    for (UInt i = 0; i < m_ilNumSetsInMessage; i++)
-    {
-      m_bottomRightTileIndex[i] = b[i];
-    }
-  }
-  UInt  getBottomRightTileIndex(UInt b)                    { return m_bottomRightTileIndex[b]; }
-  Void  setIlcIdc(UInt *b)
-  {
-    for (UInt i = 0; i < m_ilNumSetsInMessage; i++)
-    {
-      m_ilcIdc[i] = b[i];
-    }
-  }
-  UInt  getIlcIdc(UInt b)                                  { return m_ilcIdc[b]; }
-#endif
   Void      setUseWP               ( Bool b )    { m_useWeightedPred   = b;    }
   Void      setWPBiPred            ( Bool b )    { m_useWeightedBiPred = b;    }
@@ -820,6 +705,6 @@
   Bool      getTransquantBypassEnableFlag()           { return m_TransquantBypassEnableFlag; }
   Void      setTransquantBypassEnableFlag(Bool flag)  { m_TransquantBypassEnableFlag = flag; }
-  Bool      getCUTransquantBypassFlagValue()          { return m_CUTransquantBypassFlagValue; }
-  Void      setCUTransquantBypassFlagValue(Bool flag) { m_CUTransquantBypassFlagValue = flag; }
+  Bool      getCUTransquantBypassFlagForceValue()          { return m_CUTransquantBypassFlagForce; }
+  Void      setCUTransquantBypassFlagForceValue(Bool flag) { m_CUTransquantBypassFlagForce = flag; }
   Void setVPS(TComVPS *p) { m_cVPS = *p; }
   TComVPS *getVPS() { return &m_cVPS; }
@@ -934,7 +819,105 @@
   Void      setCrossLayerBLAFlag(Bool b) { m_crossLayerBLAFlag = b;    }
 #endif
+#if FAST_INTRA_SHVC
+  Bool      getUseFastIntraScalable         ()      { return m_useFastIntraScalable; }
+  Void      setUseFastIntraScalable         ( Bool  b )     { m_useFastIntraScalable = b; }
+#endif
+#if VPS_EXTN_DIRECT_REF_LAYERS
+  Int       getNumDirectRefLayers           ()                              { return m_numDirectRefLayers;      }
+  Void      setNumDirectRefLayers           (Int num)                       { m_numDirectRefLayers = num;       }
+
+  Int       getRefLayerId                   (Int i)                         { return m_refLayerId[i];           }
+  Void      setRefLayerId                   (Int i, Int refLayerId)         { m_refLayerId[i] = refLayerId;     }
+
+  Int       getNumActiveRefLayers           ()                              { return m_numActiveRefLayers;      }
+  Void      setNumActiveRefLayers           (Int num)                       { m_numActiveRefLayers = num;       }
+
+  Int       getPredLayerId                  (Int i)                         { return m_predLayerId[i];          }
+  Void      setPredLayerId                  (Int i, Int refLayerId)         { m_predLayerId[i] = refLayerId;    }
+
+  Int       getNumSamplePredRefLayers       ()                              { return m_numSamplePredRefLayers;  }
+  Void      setNumSamplePredRefLayers       (Int num)                       { m_numSamplePredRefLayers = num;   }
+
+  Int       getSamplePredRefLayerId         (Int i)                         { return m_samplePredRefLayerId[i];       }
+  Void      setSamplePredRefLayerId         (Int i, Int refLayerId)         { m_samplePredRefLayerId[i] = refLayerId; }
+
+  Int       getNumMotionPredRefLayers       ()                              { return m_numMotionPredRefLayers;  }
+  Void      setNumMotionPredRefLayers       (Int num)                       { m_numMotionPredRefLayers = num;   }
+
+  Int       getMotionPredRefLayerId         (Int i)                         { return m_motionPredRefLayerId[i];       }
+  Void      setMotionPredRefLayerId         (Int i, Int refLayerId)         { m_motionPredRefLayerId[i] = refLayerId; }
+
+  Bool      getSamplePredEnabledFlag        (Int i)                         { return m_samplePredEnabledFlag[i];  }
+  Void      setSamplePredEnabledFlag        (Int i,Bool flag)               { m_samplePredEnabledFlag[i] = flag;  }
+
+  Bool      getMotionPredEnabledFlag        (Int i)                         { return m_motionPredEnabledFlag[i];  }
+  Void      setMotionPredEnabledFlag        (Int i,Bool flag)               { m_motionPredEnabledFlag[i] = flag;  }
+#endif
+#if N0120_MAX_TID_REF_CFG
+  Int       getMaxTidIlRefPicsPlus1         ()                              { return m_maxTidIlRefPicsPlus1; }
+  Void      setMaxTidIlRefPicsPlus1         (Int num)                       { m_maxTidIlRefPicsPlus1 = num;  }
+#endif 
+#if LAYERS_NOT_PRESENT_SEI
+  Void  setLayersNotPresentSEIEnabled(Int b)             { m_layersNotPresentSEIEnabled = b; }
+  Int   getLayersNotPresentSEIEnabled()                  { return m_layersNotPresentSEIEnabled; }
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Void  setInterLayerConstrainedTileSetsSEIEnabled(Bool b) { m_interLayerConstrainedTileSetsSEIEnabled = b; }
+  Bool  getInterLayerConstrainedTileSetsSEIEnabled()       { return m_interLayerConstrainedTileSetsSEIEnabled; }
+  Void  setIlNumSetsInMessage(UInt b)                      { m_ilNumSetsInMessage = b; }
+  Int   getIlNumSetsInMessage()                            { return m_ilNumSetsInMessage; }
+  Void  setSkippedTileSetPresentFlag(Bool b)               { m_skippedTileSetPresentFlag = b; }
+  Bool  getSkippedTileSetPresentFlag()                     { return m_skippedTileSetPresentFlag; }
+  Void  setTopLeftTileIndex(UInt *b)
+  {
+    for (UInt i = 0; i < m_ilNumSetsInMessage; i++)
+    {
+      m_topLeftTileIndex[i] = b[i];
+    }
+  }
+  UInt  getTopLeftTileIndex(UInt b)                        { return m_topLeftTileIndex[b]; }
+  Void  setBottomRightTileIndex(UInt *b)
+  {
+    for (UInt i = 0; i < m_ilNumSetsInMessage; i++)
+    {
+      m_bottomRightTileIndex[i] = b[i];
+    }
+  }
+  UInt  getBottomRightTileIndex(UInt b)                    { return m_bottomRightTileIndex[b]; }
+  Void  setIlcIdc(UInt *b)
+  {
+    for (UInt i = 0; i < m_ilNumSetsInMessage; i++)
+    {
+      m_ilcIdc[i] = b[i];
+    }
+  }
+  UInt  getIlcIdc(UInt b)                                  { return m_ilcIdc[b]; }
+#endif
 #endif
 };
 
+#if SVC_EXTENSION
+#if REPN_FORMAT_IN_VPS
+struct RepFormatCfg
+{
+  Int   m_chromaFormatIdc;
+  Bool  m_separateColourPlaneFlag;
+  Int   m_picWidthInLumaSamples;
+  Int   m_picHeightInLumaSamples;
+  Int   m_bitDepthLuma;
+  Int   m_bitDepthChroma;
+  RepFormatCfg()
+    : m_chromaFormatIdc         (CHROMA_420)
+    , m_separateColourPlaneFlag (0)
+    , m_picWidthInLumaSamples   (352)
+    , m_picHeightInLumaSamples  (288)
+    , m_bitDepthLuma            (8)
+    , m_bitDepthChroma          (8)
+  {}
+};
+std::istringstream &operator>>(std::istringstream &in, RepFormatCfg &repFormatCfg);
+#endif
+#endif //SVC_EXTENSION
+
 //! \}
 
Index: trunk/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCu.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncCu.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -223,5 +223,4 @@
   m_pcRDGoOnSbacCoder = pcEncTop->getRDGoOnSbacCoder();
   
-  m_bUseSBACRD        = pcEncTop->getUseSBACRD();
   m_pcRateCtrl        = pcEncTop->getRateCtrl();
 }
@@ -394,9 +393,4 @@
   Int iMaxQP;
   Bool isAddLowestQP = false;
-#if REPN_FORMAT_IN_VPS
-  Int lowestQP = -rpcTempCU->getSlice()->getQpBDOffsetY();
-#else
-  Int lowestQP = -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY();
-#endif
 
   if( (g_uiMaxCUWidth>>uiDepth) >= rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
@@ -409,10 +403,5 @@
     iMinQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP-idQP );
     iMaxQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP+idQP );
-#endif
-    if ( (rpcTempCU->getSlice()->getSPS()->getUseLossless()) && (lowestQP < iMinQP) && rpcTempCU->getSlice()->getPPS()->getUseDQP() )
-    {
-      isAddLowestQP = true; 
-      iMinQP = iMinQP - 1;
-    }
+#endif    
   }
   else
@@ -426,4 +415,18 @@
     iMinQP = m_pcRateCtrl->getRCQP();
     iMaxQP = m_pcRateCtrl->getRCQP();
+  }
+
+  // transquant-bypass (TQB) processing loop variable initialisation ---
+
+  const Int lowestQP = iMinQP; // For TQB, use this QP which is the lowest non TQB QP tested (rather than QP'=0) - that way delta QPs are smaller, and TQB can be tested at all CU levels.
+
+  if ( (rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag()) )
+  {
+    isAddLowestQP = true; // mark that the first iteration is to cost TQB mode.
+    iMinQP = iMinQP - 1;  // increase loop variable range by 1, to allow testing of TQB mode along with other QPs
+    if ( m_pcEncCfg->getCUTransquantBypassFlagForceValue() )
+    {
+      iMaxQP = iMinQP;
+    }
   }
 
@@ -443,5 +446,13 @@
     if (m_pcEncCfg->getSkipPictureAtArcSwitch() && m_pcEncCfg->getAdaptiveResolutionChange() > 0 && pcSlice->getLayerId() == 1 && pcSlice->getPOC() == m_pcEncCfg->getAdaptiveResolutionChange())
     {
-      rpcTempCU->initEstData( uiDepth, iBaseQP );
+      Int iQP = iBaseQP;
+      const Bool bIsLosslessMode = isAddLowestQP && (iQP == iMinQP);
+
+      if( bIsLosslessMode )
+      {
+        iQP = lowestQP;
+      }
+
+      rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
       
       xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU, &earlyDetectionSkipMode, true );
@@ -466,10 +477,12 @@
     for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
     {
-      if (isAddLowestQP && (iQP == iMinQP))
+      const Bool bIsLosslessMode = isAddLowestQP && (iQP == iMinQP);
+
+      if (bIsLosslessMode)
       {
         iQP = lowestQP;
       }
 
-      rpcTempCU->initEstData( uiDepth, iQP );
+      rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 
       // do inter modes, SKIP and 2Nx2N
@@ -483,9 +496,10 @@
         if(m_pcEncCfg->getUseEarlySkipDetection())
         {
-          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );  rpcTempCU->initEstData( uiDepth, iQP );//by Competition for inter_2Nx2N
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );
+          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );//by Competition for inter_2Nx2N
         }
         // SKIP
         xCheckRDCostMerge2Nx2N( rpcBestCU, rpcTempCU, &earlyDetectionSkipMode );//by Merge for inter_2Nx2N
-        rpcTempCU->initEstData( uiDepth, iQP );
+        rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
         
 #if (ENCODER_FAST_MODE == 2)
@@ -496,5 +510,6 @@
         {
           // 2Nx2N, NxN
-          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );  rpcTempCU->initEstData( uiDepth, iQP );
+          xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2Nx2N );
+          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
           if(m_pcEncCfg->getUseCbfFastMode())
           {
@@ -507,5 +522,5 @@
       }
 
-      if (isAddLowestQP && (iQP == lowestQP))
+      if (bIsLosslessMode)
       {
         iQP = iMinQP;
@@ -517,9 +532,11 @@
       for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
       {
-        if (isAddLowestQP && (iQP == iMinQP))
+        const Bool bIsLosslessMode = isAddLowestQP && (iQP == iMinQP);
+
+        if (bIsLosslessMode)
         {
           iQP = lowestQP;
         }
-        rpcTempCU->initEstData( uiDepth, iQP );
+        rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 
         // do inter modes, NxN, 2NxN, and Nx2N
@@ -536,5 +553,5 @@
             {
               xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_NxN   );
-              rpcTempCU->initEstData( uiDepth, iQP );
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
             }
           }
@@ -544,5 +561,5 @@
           {
             xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_Nx2N  );
-            rpcTempCU->initEstData( uiDepth, iQP );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
             if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_Nx2N )
             {
@@ -553,5 +570,5 @@
           {
             xCheckRDCostInter      ( rpcBestCU, rpcTempCU, SIZE_2NxN  );
-            rpcTempCU->initEstData( uiDepth, iQP );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
             if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxN)
             {
@@ -581,5 +598,5 @@
               {
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
                 if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnU )
                 {
@@ -590,5 +607,5 @@
               {
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
                 if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnD )
                 {
@@ -603,5 +620,5 @@
               {
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU, true );
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
                 if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnU )
                 {
@@ -612,5 +629,5 @@
               {
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD, true );
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
                 if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_2NxnD )
                 {
@@ -627,5 +644,5 @@
               {
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
                 if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_nLx2N )
                 {
@@ -636,5 +653,5 @@
               {
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
               }
             }
@@ -645,5 +662,5 @@
               {
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N, true );
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
                 if(m_pcEncCfg->getUseCbfFastMode() && rpcBestCU->getPartitionSize(0) == SIZE_nLx2N )
                 {
@@ -654,5 +671,5 @@
               {
                 xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N, true );
-                rpcTempCU->initEstData( uiDepth, iQP );
+                rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
               }
             }
@@ -661,12 +678,12 @@
 #else
             xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
-            rpcTempCU->initEstData( uiDepth, iQP );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
             xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
-            rpcTempCU->initEstData( uiDepth, iQP );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
             xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
-            rpcTempCU->initEstData( uiDepth, iQP );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 
             xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
-            rpcTempCU->initEstData( uiDepth, iQP );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 
 #endif
@@ -691,5 +708,5 @@
           {
             xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_2Nx2N );
-            rpcTempCU->initEstData( uiDepth, iQP );
+          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
             if( uiDepth == g_uiMaxCUDepth - g_uiAddCUDepth )
             {
@@ -697,5 +714,5 @@
               {
                 xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_NxN   );
-                rpcTempCU->initEstData( uiDepth, iQP );
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
               }
             }
@@ -712,5 +729,5 @@
           {
             xCheckIntraPCM (rpcBestCU, rpcTempCU);
-            rpcTempCU->initEstData( uiDepth, iQP );
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
           }
         }
@@ -725,10 +742,10 @@
         {  
            xCheckRDCostILRUni( rpcBestCU, rpcTempCU, pcSlice->getInterLayerPredLayerIdc(refLayer));
-           rpcTempCU->initEstData( uiDepth, iQP );
+           rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
         }
       }
 #endif
 
-        if (isAddLowestQP && (iQP == lowestQP))
+        if (bIsLosslessMode)
         {
           iQP = iMinQP;
@@ -740,8 +757,5 @@
     m_pcEntropyCoder->encodeSplitFlag( rpcBestCU, 0, uiDepth, true );
     rpcBestCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
-    if(m_pcEncCfg->getUseSBACRD())
-    {
       rpcBestCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-    }
     rpcBestCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcBestCU->getTotalBits(), rpcBestCU->getTotalDistortion() );
 
@@ -778,10 +792,5 @@
     iMinQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP-idQP );
     iMaxQP = Clip3( -rpcTempCU->getSlice()->getSPS()->getQpBDOffsetY(), MAX_QP, iBaseQP+idQP );
-#endif
-    if ( (rpcTempCU->getSlice()->getSPS()->getUseLossless()) && (lowestQP < iMinQP) && rpcTempCU->getSlice()->getPPS()->getUseDQP() )
-    {
-      isAddLowestQP = true;
-      iMinQP = iMinQP - 1;      
-    }
+#endif    
   }
   else if( (g_uiMaxCUWidth>>uiDepth) > rpcTempCU->getSlice()->getPPS()->getMinCuDQPSize() )
@@ -810,11 +819,14 @@
     iMaxQP = m_pcRateCtrl->getRCQP();
   }
+
+  if ( m_pcEncCfg->getCUTransquantBypassFlagForceValue() )
+    {
+    iMaxQP = iMinQP; // If all blocks are forced into using transquant bypass, do not loop here.
+    }
+
   for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
   {
-    if (isAddLowestQP && (iQP == iMinQP))
-    {
-      iQP = lowestQP;
-    }
-    rpcTempCU->initEstData( uiDepth, iQP );
+    const Bool bIsLosslessMode = false; // False at this level. Next level down may set it to true.
+    rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 
     // further split
@@ -837,14 +849,11 @@
 #endif
         {
-          if( m_bUseSBACRD )
+          if ( 0 == uiPartUnitIdx) //initialize RD with previous depth buffer
           {
-            if ( 0 == uiPartUnitIdx) //initialize RD with previous depth buffer
-            {
-              m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
-            }
-            else
-            {
-              m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
-            }
+            m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+          }
+          else
+          {
+            m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
           }
 
@@ -878,8 +887,5 @@
 
         rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
-        if(m_pcEncCfg->getUseSBACRD())
-        {
-          rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-        }
+        rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
       }
       rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
@@ -913,8 +919,5 @@
           m_pcEntropyCoder->encodeQP( rpcTempCU, uiTargetPartIdx, false );
           rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
-          if(m_pcEncCfg->getUseSBACRD())
-          {
-            rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-          }
+          rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
           rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
 #endif
@@ -930,8 +933,6 @@
       }
 
-      if( m_bUseSBACRD )
-      {
-        m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
-      }
+      m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+
       Bool isEndOfSlice        = rpcBestCU->getSlice()->getSliceMode()==FIXED_NUMBER_OF_BYTES
                                  && (rpcBestCU->getTotalBits()>rpcBestCU->getSlice()->getSliceArgument()<<3);
@@ -944,8 +945,4 @@
       xCheckBestMode( rpcBestCU, rpcTempCU, uiDepth);                                  // RD compare current larger prediction
     }                                                                                  // with sub partitioned prediction.
-    if (isAddLowestQP && (iQP == lowestQP))
-    {
-      iQP = iMinQP;
-    }
   }
 
@@ -1334,4 +1331,5 @@
   UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
   Int numValidMergeCand = 0;
+  const Bool bTransquantBypassFlag = rpcTempCU->getCUTransquantBypass(0);
 
   for( UInt ui = 0; ui < rpcTempCU->getSlice()->getMaxNumMergeCand(); ++ui )
@@ -1341,5 +1339,4 @@
   UChar uhDepth = rpcTempCU->getDepth( 0 );
   rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to LCU level
-  rpcTempCU->setCUTransquantBypassSubParts( m_pcEncCfg->getCUTransquantBypassFlagValue(), 0, uhDepth );
   rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
 
@@ -1385,5 +1382,5 @@
           // set MC parameters
           rpcTempCU->setPredModeSubParts( MODE_INTER, 0, uhDepth ); // interprets depth relative to LCU level
-          rpcTempCU->setCUTransquantBypassSubParts( m_pcEncCfg->getCUTransquantBypassFlagValue(),     0, uhDepth );
+          rpcTempCU->setCUTransquantBypassSubParts( bTransquantBypassFlag,     0, uhDepth );
           rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to LCU level
           rpcTempCU->setMergeFlagSubParts( true, 0, 0, uhDepth ); // interprets depth relative to LCU level
@@ -1415,5 +1412,5 @@
           xCheckDQP( rpcTempCU );
           xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth);
-          rpcTempCU->initEstData( uhDepth, orgQP );
+          rpcTempCU->initEstData( uhDepth, orgQP, bTransquantBypassFlag );
           
           if( m_pcEncCfg->getUseFastDecisionForMerge() && !bestIsSkip )
@@ -1478,5 +1475,4 @@
   rpcTempCU->setPartSizeSubParts  ( ePartSize,  0, uhDepth );
   rpcTempCU->setPredModeSubParts  ( MODE_INTER, 0, uhDepth );
-  rpcTempCU->setCUTransquantBypassSubParts  ( m_pcEncCfg->getCUTransquantBypassFlagValue(),      0, uhDepth );
   
 #if AMP_MRG
@@ -1509,5 +1505,4 @@
   rpcTempCU->setPartSizeSubParts( eSize, 0, uiDepth );
   rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
-  rpcTempCU->setCUTransquantBypassSubParts( m_pcEncCfg->getCUTransquantBypassFlagValue(), 0, uiDepth );
   
   Bool bSeparateLumaChroma = true; // choose estimation mode
@@ -1539,11 +1534,8 @@
   setdQPFlag( bCodeDQP );
   
-  if( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+  m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
   
   rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
-  if(m_pcEncCfg->getUseSBACRD())
-  {
-    rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-  }
+  rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
   rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
   
@@ -1570,9 +1562,8 @@
   rpcTempCU->setPredModeSubParts( MODE_INTRA, 0, uiDepth );
   rpcTempCU->setTrIdxSubParts ( 0, 0, uiDepth );
-  rpcTempCU->setCUTransquantBypassSubParts( m_pcEncCfg->getCUTransquantBypassFlagValue(), 0, uiDepth );
 
   m_pcPredSearch->IPCMSearch( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth]);
 
-  if( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
 
   m_pcEntropyCoder->resetBits();
@@ -1586,11 +1577,8 @@
   m_pcEntropyCoder->encodeIPCMInfo ( rpcTempCU, 0, true );
 
-  if( m_bUseSBACRD ) m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
+  m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
 
   rpcTempCU->getTotalBits() = m_pcEntropyCoder->getNumberOfWrittenBits();
-  if(m_pcEncCfg->getUseSBACRD())
-  {
-    rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-  }
+  rpcTempCU->getTotalBins() = ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
   rpcTempCU->getTotalCost() = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
 
@@ -1627,6 +1615,6 @@
     pcCU  = NULL;
 
-    if( m_bUseSBACRD )  // store temp best CI for next CU coding
-      m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
+    // store temp best CI for next CU coding
+    m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]->store(m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]);
   }
 }
@@ -1644,8 +1632,5 @@
       m_pcEntropyCoder->encodeQP( pcCU, 0, false );
       pcCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // dQP bits
-      if(m_pcEncCfg->getUseSBACRD())
-      {
-        pcCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
-      }
+      pcCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
       pcCU->getTotalCost() = m_pcRdCost->calcRdCost( pcCU->getTotalBits(), pcCU->getTotalDistortion() );
 #endif
@@ -1795,4 +1780,47 @@
 }
 
+/** Collect ARL statistics from one LCU
+ * \param pcCU
+ */
+Void TEncCu::xLcuCollectARLStats(TComDataCU* rpcCU )
+{
+  Double cSum[ LEVEL_RANGE + 1 ];     //: the sum of DCT coefficients corresponding to datatype and quantization output
+  UInt numSamples[ LEVEL_RANGE + 1 ]; //: the number of coefficients corresponding to datatype and quantization output
+
+  TCoeff* pCoeffY = rpcCU->getCoeffY();
+  Int* pArlCoeffY = rpcCU->getArlCoeffY();
+
+  UInt uiMinCUWidth = g_uiMaxCUWidth >> g_uiMaxCUDepth;
+  UInt uiMinNumCoeffInCU = 1 << uiMinCUWidth;
+
+  memset( cSum, 0, sizeof( Double )*(LEVEL_RANGE+1) );
+  memset( numSamples, 0, sizeof( UInt )*(LEVEL_RANGE+1) );
+
+  // Collect stats to cSum[][] and numSamples[][]
+  for(Int i = 0; i < rpcCU->getTotalNumPart(); i ++ )
+  {
+    UInt uiTrIdx = rpcCU->getTransformIdx(i);
+
+    if(rpcCU->getPredictionMode(i) == MODE_INTER)
+    if( rpcCU->getCbf( i, TEXT_LUMA, uiTrIdx ) )
+    {
+      xTuCollectARLStats(pCoeffY, pArlCoeffY, uiMinNumCoeffInCU, cSum, numSamples);
+    }//Note that only InterY is processed. QP rounding is based on InterY data only.
+   
+    pCoeffY  += uiMinNumCoeffInCU;
+    pArlCoeffY  += uiMinNumCoeffInCU;
+  }
+
+  for(Int u=1; u<LEVEL_RANGE;u++)
+  {
+    m_pcTrQuant->getSliceSumC()[u] += cSum[ u ] ;
+    m_pcTrQuant->getSliceNSamples()[u] += numSamples[ u ] ;
+  }
+  m_pcTrQuant->getSliceSumC()[LEVEL_RANGE] += cSum[ LEVEL_RANGE ] ;
+  m_pcTrQuant->getSliceNSamples()[LEVEL_RANGE] += numSamples[ LEVEL_RANGE ] ;
+}
+#endif
+
+#if SVC_EXTENSION
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
 Bool TEncCu::xCheckTileSetConstraint( TComDataCU*& rpcCU )
@@ -1861,46 +1889,4 @@
 #endif
 
-/** Collect ARL statistics from one LCU
- * \param pcCU
- */
-Void TEncCu::xLcuCollectARLStats(TComDataCU* rpcCU )
-{
-  Double cSum[ LEVEL_RANGE + 1 ];     //: the sum of DCT coefficients corresponding to datatype and quantization output
-  UInt numSamples[ LEVEL_RANGE + 1 ]; //: the number of coefficients corresponding to datatype and quantization output
-
-  TCoeff* pCoeffY = rpcCU->getCoeffY();
-  Int* pArlCoeffY = rpcCU->getArlCoeffY();
-
-  UInt uiMinCUWidth = g_uiMaxCUWidth >> g_uiMaxCUDepth;
-  UInt uiMinNumCoeffInCU = 1 << uiMinCUWidth;
-
-  memset( cSum, 0, sizeof( Double )*(LEVEL_RANGE+1) );
-  memset( numSamples, 0, sizeof( UInt )*(LEVEL_RANGE+1) );
-
-  // Collect stats to cSum[][] and numSamples[][]
-  for(Int i = 0; i < rpcCU->getTotalNumPart(); i ++ )
-  {
-    UInt uiTrIdx = rpcCU->getTransformIdx(i);
-
-    if(rpcCU->getPredictionMode(i) == MODE_INTER)
-    if( rpcCU->getCbf( i, TEXT_LUMA, uiTrIdx ) )
-    {
-      xTuCollectARLStats(pCoeffY, pArlCoeffY, uiMinNumCoeffInCU, cSum, numSamples);
-    }//Note that only InterY is processed. QP rounding is based on InterY data only.
-   
-    pCoeffY  += uiMinNumCoeffInCU;
-    pArlCoeffY  += uiMinNumCoeffInCU;
-  }
-
-  for(Int u=1; u<LEVEL_RANGE;u++)
-  {
-    m_pcTrQuant->getSliceSumC()[u] += cSum[ u ] ;
-    m_pcTrQuant->getSliceNSamples()[u] += numSamples[ u ] ;
-  }
-  m_pcTrQuant->getSliceSumC()[LEVEL_RANGE] += cSum[ LEVEL_RANGE ] ;
-  m_pcTrQuant->getSliceNSamples()[LEVEL_RANGE] += numSamples[ LEVEL_RANGE ] ;
-}
-#endif
-
 #if (ENCODER_FAST_MODE)
 Void TEncCu::xCheckRDCostILRUni(TComDataCU *&rpcBestCU, TComDataCU *&rpcTempCU, UInt refLayerId)
@@ -1913,5 +1899,5 @@
   rpcTempCU->setPartSizeSubParts  ( SIZE_2Nx2N,  0, uhDepth );  //2Nx2N
   rpcTempCU->setPredModeSubParts  ( MODE_INTER, 0, uhDepth );
-  rpcTempCU->setCUTransquantBypassSubParts  ( m_pcEncCfg->getCUTransquantBypassFlagValue(), 0, uhDepth );
+  rpcTempCU->setCUTransquantBypassSubParts  ( m_pcEncCfg->getCUTransquantBypassFlagForceValue(), 0, uhDepth );
   Bool exitILR = m_pcPredSearch->predInterSearchILRUni( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth], refLayerId );
   if(!exitILR)
@@ -1926,3 +1912,4 @@
 }
 #endif
+#endif //SVC_EXTENSION
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncCu.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncCu.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncCu.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -89,8 +89,4 @@
   TComRdCost*             m_pcRdCost;
   
-#if SVC_EXTENSION
-  TEncTop**               m_ppcTEncTop;
-#endif
-  
   TEncEntropy*            m_pcEntropyCoder;
   TEncCavlc*              m_pcCavlcCoder;
@@ -101,10 +97,12 @@
   TEncSbac***             m_pppcRDSbacCoder;
   TEncSbac*               m_pcRDGoOnSbacCoder;
-  Bool                    m_bUseSBACRD;
   TEncRateCtrl*           m_pcRateCtrl;
 
+#if SVC_EXTENSION
+  TEncTop**               m_ppcTEncTop;
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
   Bool                    m_disableILP;
 #endif
+#endif //SVC_EXTENSION
 public:
   /// copy parameters from encoder class
@@ -148,7 +146,4 @@
 #endif
   Void  xCheckRDCostIntra   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize  );
-#if ENCODER_FAST_MODE
-  Void  xCheckRDCostILRUni  ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt refLayerId);
-#endif
   Void  xCheckDQP           ( TComDataCU*  pcCU );
   
@@ -167,9 +162,4 @@
 #endif
 
-#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
-  Bool xCheckTileSetConstraint( TComDataCU*& rpcCU );
-  Void xVerifyTileSetConstraint( TComDataCU*& rpcCU );
-#endif
-
 #if AMP_ENC_SPEEDUP 
 #if AMP_MRG
@@ -180,9 +170,16 @@
 #endif
 
+  Void  xFillPCMBuffer     ( TComDataCU*& pCU, TComYuv* pOrgYuv ); 
+
 #if SVC_EXTENSION
   TEncTop*   getLayerEnc(UInt LayerId)  {return m_ppcTEncTop[LayerId]; }
-#endif 
-
-  Void  xFillPCMBuffer     ( TComDataCU*& pCU, TComYuv* pOrgYuv ); 
+#if ENCODER_FAST_MODE
+  Void  xCheckRDCostILRUni  ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, UInt refLayerId);
+#endif
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+  Bool xCheckTileSetConstraint( TComDataCU*& rpcCU );
+  Void xVerifyTileSetConstraint( TComDataCU*& rpcCU );
+#endif
+#endif //SVC_EXTENSION
 };
 
Index: trunk/source/Lib/TLibEncoder/TEncEntropy.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -51,14 +51,4 @@
 Void TEncEntropy::encodeSliceHeader ( TComSlice* pcSlice )
 {
-#if !HM_CLEANUP_SAO
-  if (pcSlice->getSPS()->getUseSAO())
-  {
-    SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
-    pcSlice->setSaoEnabledFlag     (saoParam->bSaoFlag[0]);
-    {
-      pcSlice->setSaoEnabledFlagChroma   (saoParam->bSaoFlag[1]);
-    }
-  }
-#endif
   m_pcEntropyCoderIf->codeSliceHeader( pcSlice );
   return;
@@ -639,100 +629,4 @@
 }
 
-#if !HM_CLEANUP_SAO
-/** Encode SAO Offset
- * \param  saoLcuParam SAO LCU paramters
- */
-Void TEncEntropy::encodeSaoOffset(SaoLcuParam* saoLcuParam, UInt compIdx)
-{
-  UInt uiSymbol;
-  Int i;
-
-  uiSymbol = saoLcuParam->typeIdx + 1;
-  if (compIdx!=2)
-  {
-    m_pcEntropyCoderIf->codeSaoTypeIdx(uiSymbol);
-  }
-  if (uiSymbol)
-  {
-    if (saoLcuParam->typeIdx < 4 && compIdx != 2)
-    {
-      saoLcuParam->subTypeIdx = saoLcuParam->typeIdx;
-    }
-    Int bitDepth = compIdx ? g_bitDepthC : g_bitDepthY;
-    Int offsetTh = 1 << min(bitDepth - 5,5);
-    if( saoLcuParam->typeIdx == SAO_BO )
-    {
-      for( i=0; i< saoLcuParam->length; i++)
-      {
-        UInt absOffset = ( (saoLcuParam->offset[i] < 0) ? -saoLcuParam->offset[i] : saoLcuParam->offset[i]);
-        m_pcEntropyCoderIf->codeSaoMaxUvlc(absOffset, offsetTh-1);
-      }  
-      for( i=0; i< saoLcuParam->length; i++)
-      {
-        if (saoLcuParam->offset[i] != 0)
-        {
-          UInt sign = (saoLcuParam->offset[i] < 0) ? 1 : 0 ;
-          m_pcEntropyCoderIf->codeSAOSign(sign);
-        }
-      }
-      uiSymbol = (UInt) (saoLcuParam->subTypeIdx);
-      m_pcEntropyCoderIf->codeSaoUflc(5, uiSymbol);
-    }
-    else if( saoLcuParam->typeIdx < 4 )
-    {
-      m_pcEntropyCoderIf->codeSaoMaxUvlc( saoLcuParam->offset[0], offsetTh-1);
-      m_pcEntropyCoderIf->codeSaoMaxUvlc( saoLcuParam->offset[1], offsetTh-1);
-      m_pcEntropyCoderIf->codeSaoMaxUvlc(-saoLcuParam->offset[2], offsetTh-1);
-      m_pcEntropyCoderIf->codeSaoMaxUvlc(-saoLcuParam->offset[3], offsetTh-1);
-      if (compIdx!=2)
-      {
-        uiSymbol = (UInt) (saoLcuParam->subTypeIdx);
-        m_pcEntropyCoderIf->codeSaoUflc(2, uiSymbol);
-      }
-    }
-  }
-}
-
-/** Encode SAO unit interleaving
-* \param  rx
-* \param  ry
-* \param  pSaoParam
-* \param  pcCU
-* \param  iCUAddrInSlice
-* \param  iCUAddrUpInSlice
-* \param  bLFCrossSliceBoundaryFlag
- */
-Void TEncEntropy::encodeSaoUnitInterleaving(Int compIdx, Bool saoFlag, Int rx, Int ry, SaoLcuParam* saoLcuParam, Int cuAddrInSlice, Int cuAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp)
-{
-  if (saoFlag)
-  {
-    if (rx>0 && cuAddrInSlice!=0 && allowMergeLeft)
-    {
-      m_pcEntropyCoderIf->codeSaoMerge(saoLcuParam->mergeLeftFlag);
-    }
-    else
-    {
-      saoLcuParam->mergeLeftFlag = 0;
-    }
-    if (saoLcuParam->mergeLeftFlag == 0)
-    {
-      if ( (ry > 0) && (cuAddrUpInSlice>=0) && allowMergeUp )
-      {
-        m_pcEntropyCoderIf->codeSaoMerge(saoLcuParam->mergeUpFlag);
-      }
-      else
-      {
-        saoLcuParam->mergeUpFlag = 0;
-      }
-      if (!saoLcuParam->mergeUpFlag)
-      {
-        encodeSaoOffset(saoLcuParam, compIdx);
-      }
-    }
-  }
-}
-
-#endif
-
 Int TEncEntropy::countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize )
 {
Index: trunk/source/Lib/TLibEncoder/TEncEntropy.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncEntropy.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncEntropy.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -105,13 +105,5 @@
   virtual Void codeCoeffNxN      ( TComDataCU* pcCU, TCoeff* pcCoef, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt uiDepth, TextType eTType ) = 0;
   virtual Void codeTransformSkipFlags ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt width, UInt height, TextType eTType ) = 0;
-#if HM_CLEANUP_SAO
   virtual Void codeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false)    =0;
-#else
-  virtual Void codeSAOSign          ( UInt code   ) = 0;
-  virtual Void codeSaoMaxUvlc       ( UInt code, UInt maxSymbol ) = 0;
-  virtual Void codeSaoMerge    ( UInt   uiCode  ) = 0;
-  virtual Void codeSaoTypeIdx      ( UInt   uiCode) = 0;
-  virtual Void codeSaoUflc         ( UInt uiLength, UInt   uiCode ) = 0;
-#endif
   virtual Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType) = 0;
   
@@ -192,10 +184,5 @@
   
   Void estimateBit             ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, TextType eTType);
-#if HM_CLEANUP_SAO
   Void encodeSAOBlkParam(SAOBlkParam& saoBlkParam, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail){m_pcEntropyCoderIf->codeSAOBlkParam(saoBlkParam, sliceEnabled, leftMergeAvail, aboveMergeAvail, false);}
-#else
-  Void    encodeSaoOffset(SaoLcuParam* saoLcuParam, UInt compIdx);
-  Void    encodeSaoUnitInterleaving(Int compIdx, Bool saoFlag, Int rx, Int ry, SaoLcuParam* saoLcuParam, Int cuAddrInSlice, Int cuAddrUpInSlice, Int allowMergeLeft, Int allowMergeUp);
-#endif
   static Int countNonZeroCoeffs( TCoeff* pcCoef, UInt uiSize );
 
Index: trunk/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -96,4 +96,8 @@
   xResetNonNestedSEIPresentFlags();
   xResetNestedSEIPresentFlags();
+#if FIX1172
+  m_associatedIRAPType = NAL_UNIT_CODED_SLICE_IDR_N_LP;
+  m_associatedIRAPPOC  = 0;
+#endif
 #if SVC_UPSAMPLING
   m_pcPredSearch        = NULL;
@@ -167,22 +171,4 @@
 }
 
-#if LAYERS_NOT_PRESENT_SEI
-SEILayersNotPresent* TEncGOP::xCreateSEILayersNotPresent ()
-{
-  UInt i = 0;
-  SEILayersNotPresent *seiLayersNotPresent = new SEILayersNotPresent(); 
-  seiLayersNotPresent->m_activeVpsId = m_pcCfg->getVPS()->getVPSId(); 
-  seiLayersNotPresent->m_vpsMaxLayers = m_pcCfg->getVPS()->getMaxLayers();
-  for ( ; i < seiLayersNotPresent->m_vpsMaxLayers; i++)
-  {
-    seiLayersNotPresent->m_layerNotPresentFlag[i] = true; 
-  }
-  for ( ; i < MAX_LAYERS; i++)
-  {
-    seiLayersNotPresent->m_layerNotPresentFlag[i] = false; 
-  }
-  return seiLayersNotPresent;
-}
-#endif
 
 SEIFramePacking* TEncGOP::xCreateSEIFramePacking()
@@ -307,43 +293,4 @@
 }
 
-#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
-SEIInterLayerConstrainedTileSets* TEncGOP::xCreateSEIInterLayerConstrainedTileSets()
-{
-  SEIInterLayerConstrainedTileSets *seiInterLayerConstrainedTileSets = new SEIInterLayerConstrainedTileSets();
-  seiInterLayerConstrainedTileSets->m_ilAllTilesExactSampleValueMatchFlag = false;
-  seiInterLayerConstrainedTileSets->m_ilOneTilePerTileSetFlag = false;
-  if (!seiInterLayerConstrainedTileSets->m_ilOneTilePerTileSetFlag)
-  {
-    seiInterLayerConstrainedTileSets->m_ilNumSetsInMessageMinus1 = m_pcCfg->getIlNumSetsInMessage() - 1;
-    if (seiInterLayerConstrainedTileSets->m_ilNumSetsInMessageMinus1)
-    {
-      seiInterLayerConstrainedTileSets->m_skippedTileSetPresentFlag = m_pcCfg->getSkippedTileSetPresentFlag();
-    }
-    else
-    {
-      seiInterLayerConstrainedTileSets->m_skippedTileSetPresentFlag = false;
-    }
-    seiInterLayerConstrainedTileSets->m_ilNumSetsInMessageMinus1 += seiInterLayerConstrainedTileSets->m_skippedTileSetPresentFlag ? 1 : 0;
-    for (UInt i = 0; i < m_pcCfg->getIlNumSetsInMessage(); i++)
-    {
-      seiInterLayerConstrainedTileSets->m_ilctsId[i] = i;
-      seiInterLayerConstrainedTileSets->m_ilNumTileRectsInSetMinus1[i] = 0;
-      for( UInt j = 0; j <= seiInterLayerConstrainedTileSets->m_ilNumTileRectsInSetMinus1[i]; j++)
-      {
-        seiInterLayerConstrainedTileSets->m_ilTopLeftTileIndex[i][j]     = m_pcCfg->getTopLeftTileIndex(i);
-        seiInterLayerConstrainedTileSets->m_ilBottomRightTileIndex[i][j] = m_pcCfg->getBottomRightTileIndex(i);
-      }
-      seiInterLayerConstrainedTileSets->m_ilcIdc[i] = m_pcCfg->getIlcIdc(i);
-      if (seiInterLayerConstrainedTileSets->m_ilAllTilesExactSampleValueMatchFlag)
-      {
-        seiInterLayerConstrainedTileSets->m_ilExactSampleValueMatchFlag[i] = false;
-      }
-    }
-  }
-
-  return seiInterLayerConstrainedTileSets;
-}
-#endif
-
 Void TEncGOP::xCreateLeadingSEIMessages (/*SEIMessages seiMessages,*/ AccessUnit &accessUnit, TComSPS *sps)
 {
@@ -362,16 +309,4 @@
     m_activeParameterSetSEIPresentInAU = true;
   }
-
-#if LAYERS_NOT_PRESENT_SEI
-  if(m_pcCfg->getLayersNotPresentSEIEnabled())
-  {
-    SEILayersNotPresent *sei = xCreateSEILayersNotPresent ();
-    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
 
   if(m_pcCfg->getFramePackingArrangementSEIEnabled())
@@ -408,4 +343,18 @@
     delete sei;
   }
+
+#if SVC_EXTENSION
+#if LAYERS_NOT_PRESENT_SEI
+  if(m_pcCfg->getLayersNotPresentSEIEnabled())
+  {
+    SEILayersNotPresent *sei = xCreateSEILayersNotPresent ();
+    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
+
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
   if(m_pcCfg->getInterLayerConstrainedTileSetsSEIEnabled())
@@ -421,4 +370,5 @@
   }
 #endif
+#endif //SVC_EXTENSION
 }
 
@@ -547,5 +497,5 @@
 #endif
 
-    if( getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_N_LP )
+    if( getNalUnitType(pocCurr, m_iLastIDR, isField) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR, isField) == NAL_UNIT_CODED_SLICE_IDR_N_LP )
     {
       m_iLastIDR = pocCurr;
@@ -554,5 +504,5 @@
     accessUnitsInGOP.push_back(AccessUnit());
     AccessUnit& accessUnit = accessUnitsInGOP.back();
-    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr, isField );
+    xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr, isField);
 
     //  Slice data initialization
@@ -571,4 +521,5 @@
     pcSlice->getPic()->setField(isField);
 
+#if SVC_EXTENSION
 #if POC_RESET_FLAG
     if( !pcSlice->getPocResetFlag() ) // For picture that are not reset, we should adjust the value of POC calculated from the configuration files.
@@ -636,5 +587,5 @@
 #endif
 #if O0149_CROSS_LAYER_BLA_FLAG
-    if( m_layerId == 0 && (getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR) == NAL_UNIT_CODED_SLICE_IDR_N_LP) )
+    if( m_layerId == 0 && (getNalUnitType(pocCurr, m_iLastIDR, isField) == NAL_UNIT_CODED_SLICE_IDR_W_RADL || getNalUnitType(pocCurr, m_iLastIDR, isField) == NAL_UNIT_CODED_SLICE_IDR_N_LP) )
     {
       pcSlice->setCrossLayerBLAFlag(m_pcEncTop->getCrossLayerBLAFlag());
@@ -693,4 +644,5 @@
     }
 #endif
+#endif //SVC_EXTENSION
 
     pcSlice->setLastIDR(m_iLastIDR);
@@ -760,5 +712,4 @@
         pcSlice->setDefaultScalingList ();
       }
-
       pcSlice->getScalingList()->checkDcOfMatrix();
       m_pcEncTop->getSPS()->setScalingListPresentFlag(pcSlice->checkDefaultScalingList());
@@ -782,6 +733,11 @@
       pcSlice->setSliceType(P_SLICE);
     }
+    if(pcSlice->getSliceType()==B_SLICE&&m_pcCfg->getGOPEntry(iGOPid).m_sliceType=='I')
+    {
+      pcSlice->setSliceType(I_SLICE);
+    }
+
     // Set the nal unit type
-    pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR));
+    pcSlice->setNalUnitType(getNalUnitType(pocCurr, m_iLastIDR, isField));
 #if SVC_EXTENSION
     if (m_layerId > 0)
@@ -953,4 +909,18 @@
     m_pcEncTop->selectReferencePictureSet(pcSlice, pocCurr, iGOPid);
     pcSlice->getRPS()->setNumberOfLongtermPictures(0);
+#if FIX1172
+    if ( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_W_RADL
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_BLA_N_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP
+      || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA )  // IRAP picture
+    {
+      m_associatedIRAPType = pcSlice->getNalUnitType();
+      m_associatedIRAPPOC = pocCurr;
+    }
+    pcSlice->setAssociatedIRAPType(m_associatedIRAPType);
+    pcSlice->setAssociatedIRAPPOC(m_associatedIRAPPOC);
+#endif
 
     if ((pcSlice->checkThatAllRefPicsAreAvailable(rcListPic, pcSlice->getRPS(), false) != 0) || (pcSlice->isIRAP()))
@@ -960,5 +930,10 @@
     pcSlice->applyReferencePictureSet(rcListPic, pcSlice->getRPS());
 
-    if(pcSlice->getTLayer() > 0)
+    if(pcSlice->getTLayer() > 0 
+      &&  !( pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_N     // Check if not a leading picture
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RADL_R
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_N
+          || pcSlice->getNalUnitType() == NAL_UNIT_CODED_SLICE_RASL_R )
+        )
     {
       if(pcSlice->isTemporalLayerSwitchingPoint(rcListPic) || pcSlice->getSPS()->getTemporalIdNestingFlag())
@@ -1633,16 +1608,8 @@
 
     // SAO parameter estimation using non-deblocked pixels for LCU bottom and right boundary areas
-#if HM_CLEANUP_SAO
     if( pcSlice->getSPS()->getUseSAO() && m_pcCfg->getSaoLcuBoundary() )
     {
       m_pcSAO->getPreDBFStatistics(pcPic);
     }
-#else
-    if( m_pcCfg->getSaoLcuBasedOptimization() && m_pcCfg->getSaoLcuBoundary() )
-    {
-      m_pcSAO->resetStats();
-      m_pcSAO->calcSaoStatsCu_BeforeDblk( pcPic );
-    }
-#endif    
     //-- Loop filter
     Bool bLFCrossTileBoundary = pcSlice->getPPS()->getLoopFilterAcrossTilesEnabledFlag();
@@ -1654,25 +1621,4 @@
     m_pcLoopFilter->loopFilterPic( pcPic );
 
-#if !HM_CLEANUP_SAO    
-    pcSlice = pcPic->getSlice(0);
-    if(pcSlice->getSPS()->getUseSAO())
-    {
-      std::vector<Bool> LFCrossSliceBoundaryFlag;
-      for(Int s=0; s< uiNumSlices; s++)
-      {
-        LFCrossSliceBoundaryFlag.push_back(  ((uiNumSlices==1)?true:pcPic->getSlice(s)->getLFCrossSliceBoundaryFlag()) );
-      }
-      m_storedStartCUAddrForEncodingSlice.resize(uiNumSlices+1);
-      pcPic->createNonDBFilterInfo(m_storedStartCUAddrForEncodingSlice, 0, &LFCrossSliceBoundaryFlag ,pcPic->getPicSym()->getNumTiles() ,bLFCrossTileBoundary);
-    }
-
-
-    pcSlice = pcPic->getSlice(0);
-
-    if(pcSlice->getSPS()->getUseSAO())
-    {
-      m_pcSAO->createPicSaoInfo(pcPic);
-    }
-#endif
     /////////////////////////////////////////////////////////////////////////////////////////////////// File writing
     // Set entropy coder
@@ -1792,5 +1738,5 @@
         {
           SOPcurrPOC += deltaPOC;
-          SOPDescriptionSEI.m_sopDescVclNaluType[i] = getNalUnitType(SOPcurrPOC, m_iLastIDR);
+          SOPDescriptionSEI.m_sopDescVclNaluType[i] = getNalUnitType(SOPcurrPOC, m_iLastIDR, isField);
           SOPDescriptionSEI.m_sopDescTemporalId[i] = m_pcCfg->getGOPEntry(j).m_temporalId;
           SOPDescriptionSEI.m_sopDescStRpsIdx[i] = m_pcEncTop->getReferencePictureSetIdxForSOP(pcSlice, SOPcurrPOC, j);
@@ -2257,5 +2203,4 @@
               m_pcEntropyCoder->resetEntropy();
               m_pcEntropyCoder->setBitstream( m_pcBitCounter );
-#if HM_CLEANUP_SAO
               Bool sliceEnabled[NUM_SAO_COMPONENTS];
               m_pcSAO->initRDOCabacCoder(m_pcEncTop->getRDGoOnSbacCoder(), pcSlice);
@@ -2276,39 +2221,6 @@
                 pcPic->getSlice(s)->setSaoEnabledFlagChroma(sliceEnabled[SAO_Cb]);
               }
-#else
-              m_pcSAO->startSaoEnc(pcPic, m_pcEntropyCoder, m_pcEncTop->getRDSbacCoder(), m_pcEncTop->getRDGoOnSbacCoder());
-              SAOParam& cSaoParam = *pcSlice->getPic()->getPicSym()->getSaoParam();
-
-#if SAO_ENCODING_CHOICE
-              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdas()[TEXT_LUMA], pcPic->getSlice(0)->getLambdas()[TEXT_CHROMA], pcPic->getSlice(0)->getDepth());
-#else
-              m_pcSAO->SAOProcess(&cSaoParam, pcPic->getSlice(0)->getLambdaLuma(), pcPic->getSlice(0)->getLambdaChroma());
-#endif
-              m_pcSAO->endSaoEnc();
-              m_pcSAO->PCMLFDisableProcess(pcPic);
-#endif
             }
-#if !HM_CLEANUP_SAO          
-#if SAO_RDO
-            m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
-#endif
-#endif
             processingState = ENCODE_SLICE;
-#if !HM_CLEANUP_SAO
-#if HIGHER_LAYER_IRAP_SKIP_FLAG
-            if ( ( m_pcEncTop->getSkipPictureAtArcSwitch() && m_pcEncTop->getAdaptiveResolutionChange() > 0 && pcSlice->getLayerId() == 1 && pcSlice->getPOC() == m_pcEncTop->getAdaptiveResolutionChange()) )
-            {
-              pcSlice->getPic()->getPicSym()->getSaoParam()->bSaoFlag[0]=0;
-              pcSlice->getPic()->getPicSym()->getSaoParam()->bSaoFlag[1]=0;
-            }
-#endif
-            for(Int s=0; s< uiNumSlices; s++)
-            {
-              if (pcSlice->getSPS()->getUseSAO())
-              {
-                pcPic->getSlice(s)->setSaoEnabledFlag((pcSlice->getPic()->getPicSym()->getSaoParam()->bSaoFlag[0]==1)?true:false);
-              }
-            }
-#endif
           }
           break;
@@ -2321,14 +2233,4 @@
         }
       } // end iteration over slices
-#if !HM_CLEANUP_SAO    
-      if(pcSlice->getSPS()->getUseSAO())
-      {
-        if(pcSlice->getSPS()->getUseSAO())
-        {
-          m_pcSAO->destroyPicSaoInfo();
-        }
-        pcPic->destroyNonDBFilterInfo();
-      }
-#endif
       pcPic->compressMotion(); 
       
@@ -2402,5 +2304,5 @@
 
       //In case of field coding, compute the interlaced PSNR for both fields
-      if (isField && ((!pcPic->isTopField() && isTff) || (pcPic->isTopField() && !isTff)))
+    if (isField && ((!pcPic->isTopField() && isTff) || (pcPic->isTopField() && !isTff)) && (pcPic->getPOC()%m_iGopSize != 1))
       {
         //get complementary top field
@@ -2414,4 +2316,16 @@
         xCalculateInterlacedAddPSNR(pcPicTop, pcPic, pcPicTop->getPicYuvRec(), pcPic->getPicYuvRec(), accessUnit, dEncTime );
       }
+    else if (isField && pcPic->getPOC()!= 0 && (pcPic->getPOC()%m_iGopSize == 0))
+    {
+      //get complementary bottom field
+      TComPic* pcPicBottom;
+      TComList<TComPic*>::iterator   iterPic = rcListPic.begin();
+      while ((*iterPic)->getPOC() != pcPic->getPOC()+1)
+      {
+        iterPic ++;
+      }
+      pcPicBottom = *(iterPic);
+      xCalculateInterlacedAddPSNR(pcPic, pcPicBottom, pcPic->getPicYuvRec(), pcPicBottom->getPicYuvRec(), accessUnit, dEncTime );
+    }
 
       if (digestStr)
@@ -2717,20 +2631,4 @@
   m_pcEntropyCoder->resetEntropy    ();
   m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
-#if !HM_CLEANUP_SAO
-  pcSlice = pcPic->getSlice(0);
-  if(pcSlice->getSPS()->getUseSAO())
-  {
-    std::vector<Bool> LFCrossSliceBoundaryFlag(1, true);
-    std::vector<Int>  sliceStartAddress;
-    sliceStartAddress.push_back(0);
-    sliceStartAddress.push_back(pcPic->getNumCUsInFrame()* pcPic->getNumPartInCU());
-    pcPic->createNonDBFilterInfo(sliceStartAddress, 0, &LFCrossSliceBoundaryFlag);
-  }
-  
-  if( pcSlice->getSPS()->getUseSAO())
-  {
-    pcPic->destroyNonDBFilterInfo();
-  }
-#endif
   m_pcEntropyCoder->resetEntropy    ();
   ruiBits += m_pcEntropyCoder->getNumberOfWrittenBits();
@@ -3303,5 +3201,5 @@
  * This function checks the configuration and returns the appropriate nal_unit_type for the picture.
  */
-NalUnitType TEncGOP::getNalUnitType(Int pocCurr, Int lastIDR)
+NalUnitType TEncGOP::getNalUnitType(Int pocCurr, Int lastIDR, Bool isField)
 {
   if (pocCurr == 0)
@@ -3309,5 +3207,5 @@
     return NAL_UNIT_CODED_SLICE_IDR_W_RADL;
   }
-  if (pocCurr % m_pcCfg->getIntraPeriod() == 0)
+  if ((pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0)
   {
     if (m_pcCfg->getDecodingRefreshType() == 1)
@@ -3532,46 +3430,4 @@
   return seiStartPos;
 }
-
-#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
-Void TEncGOP::xBuildTileSetsMap(TComPicSym* picSym)
-{
-  Int numCUs = picSym->getFrameWidthInCU() * picSym->getFrameHeightInCU();
-
-  for (Int i = 0; i < numCUs; i++)
-  {
-    picSym->setTileSetIdxMap(i, -1, 0, false);
-  }
-
-  for (Int i = 0; i < m_pcCfg->getIlNumSetsInMessage(); i++)
-  {
-    TComTile* topLeftTile     = picSym->getTComTile(m_pcCfg->getTopLeftTileIndex(i));
-    TComTile* bottomRightTile = picSym->getTComTile(m_pcCfg->getBottomRightTileIndex(i));
-    Int tileSetLeftEdgePosInCU = topLeftTile->getRightEdgePosInCU() - topLeftTile->getTileWidth() + 1;
-    Int tileSetRightEdgePosInCU = bottomRightTile->getRightEdgePosInCU();
-    Int tileSetTopEdgePosInCU = topLeftTile->getBottomEdgePosInCU() - topLeftTile->getTileHeight() + 1;
-    Int tileSetBottomEdgePosInCU = bottomRightTile->getBottomEdgePosInCU();
-    assert(tileSetLeftEdgePosInCU < tileSetRightEdgePosInCU && tileSetTopEdgePosInCU < tileSetBottomEdgePosInCU);
-    for (Int j = tileSetTopEdgePosInCU; j <= tileSetBottomEdgePosInCU; j++)
-    {
-      for (Int k = tileSetLeftEdgePosInCU; k <= tileSetRightEdgePosInCU; k++)
-      {
-        picSym->setTileSetIdxMap(j * picSym->getFrameWidthInCU() + k, i, m_pcCfg->getIlcIdc(i), false);
-      }
-    }
-  }
-  
-  if (m_pcCfg->getSkippedTileSetPresentFlag())
-  {
-    Int skippedTileSetIdx = m_pcCfg->getIlNumSetsInMessage();
-    for (Int i = 0; i < numCUs; i++)
-    {
-      if (picSym->getTileSetIdxMap(i) < 0)
-      {
-        picSym->setTileSetIdxMap(i, skippedTileSetIdx, 0, true);
-      }
-    }
-  }
-}
-#endif
 
 Void TEncGOP::dblMetric( TComPic* pcPic, UInt uiNumSlices )
@@ -3698,3 +3554,103 @@
   free(rowSAD);
 }
+#if SVC_EXTENSION
+#if LAYERS_NOT_PRESENT_SEI
+SEILayersNotPresent* TEncGOP::xCreateSEILayersNotPresent ()
+{
+  UInt i = 0;
+  SEILayersNotPresent *seiLayersNotPresent = new SEILayersNotPresent(); 
+  seiLayersNotPresent->m_activeVpsId = m_pcCfg->getVPS()->getVPSId(); 
+  seiLayersNotPresent->m_vpsMaxLayers = m_pcCfg->getVPS()->getMaxLayers();
+  for ( ; i < seiLayersNotPresent->m_vpsMaxLayers; i++)
+  {
+    seiLayersNotPresent->m_layerNotPresentFlag[i] = true; 
+  }
+  for ( ; i < MAX_LAYERS; i++)
+  {
+    seiLayersNotPresent->m_layerNotPresentFlag[i] = false; 
+  }
+  return seiLayersNotPresent;
+}
+#endif
+
+#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
+SEIInterLayerConstrainedTileSets* TEncGOP::xCreateSEIInterLayerConstrainedTileSets()
+{
+  SEIInterLayerConstrainedTileSets *seiInterLayerConstrainedTileSets = new SEIInterLayerConstrainedTileSets();
+  seiInterLayerConstrainedTileSets->m_ilAllTilesExactSampleValueMatchFlag = false;
+  seiInterLayerConstrainedTileSets->m_ilOneTilePerTileSetFlag = false;
+  if (!seiInterLayerConstrainedTileSets->m_ilOneTilePerTileSetFlag)
+  {
+    seiInterLayerConstrainedTileSets->m_ilNumSetsInMessageMinus1 = m_pcCfg->getIlNumSetsInMessage() - 1;
+    if (seiInterLayerConstrainedTileSets->m_ilNumSetsInMessageMinus1)
+    {
+      seiInterLayerConstrainedTileSets->m_skippedTileSetPresentFlag = m_pcCfg->getSkippedTileSetPresentFlag();
+    }
+    else
+    {
+      seiInterLayerConstrainedTileSets->m_skippedTileSetPresentFlag = false;
+    }
+    seiInterLayerConstrainedTileSets->m_ilNumSetsInMessageMinus1 += seiInterLayerConstrainedTileSets->m_skippedTileSetPresentFlag ? 1 : 0;
+    for (UInt i = 0; i < m_pcCfg->getIlNumSetsInMessage(); i++)
+    {
+      seiInterLayerConstrainedTileSets->m_ilctsId[i] = i;
+      seiInterLayerConstrainedTileSets->m_ilNumTileRectsInSetMinus1[i] = 0;
+      for( UInt j = 0; j <= seiInterLayerConstrainedTileSets->m_ilNumTileRectsInSetMinus1[i]; j++)
+      {
+        seiInterLayerConstrainedTileSets->m_ilTopLeftTileIndex[i][j]     = m_pcCfg->getTopLeftTileIndex(i);
+        seiInterLayerConstrainedTileSets->m_ilBottomRightTileIndex[i][j] = m_pcCfg->getBottomRightTileIndex(i);
+      }
+      seiInterLayerConstrainedTileSets->m_ilcIdc[i] = m_pcCfg->getIlcIdc(i);
+      if (seiInterLayerConstrainedTileSets->m_ilAllTilesExactSampleValueMatchFlag)
+      {
+        seiInterLayerConstrainedTileSets->m_ilExactSampleValueMatchFlag[i] = false;
+      }
+    }
+  }
+
+  return seiInterLayerConstrainedTileSets;
+}
+
+Void TEncGOP::xBuildTileSetsMap(TComPicSym* picSym)
+{
+  Int numCUs = picSym->getFrameWidthInCU() * picSym->getFrameHeightInCU();
+
+  for (Int i = 0; i < numCUs; i++)
+  {
+    picSym->setTileSetIdxMap(i, -1, 0, false);
+  }
+
+  for (Int i = 0; i < m_pcCfg->getIlNumSetsInMessage(); i++)
+  {
+    TComTile* topLeftTile     = picSym->getTComTile(m_pcCfg->getTopLeftTileIndex(i));
+    TComTile* bottomRightTile = picSym->getTComTile(m_pcCfg->getBottomRightTileIndex(i));
+    Int tileSetLeftEdgePosInCU = topLeftTile->getRightEdgePosInCU() - topLeftTile->getTileWidth() + 1;
+    Int tileSetRightEdgePosInCU = bottomRightTile->getRightEdgePosInCU();
+    Int tileSetTopEdgePosInCU = topLeftTile->getBottomEdgePosInCU() - topLeftTile->getTileHeight() + 1;
+    Int tileSetBottomEdgePosInCU = bottomRightTile->getBottomEdgePosInCU();
+    assert(tileSetLeftEdgePosInCU < tileSetRightEdgePosInCU && tileSetTopEdgePosInCU < tileSetBottomEdgePosInCU);
+    for (Int j = tileSetTopEdgePosInCU; j <= tileSetBottomEdgePosInCU; j++)
+    {
+      for (Int k = tileSetLeftEdgePosInCU; k <= tileSetRightEdgePosInCU; k++)
+      {
+        picSym->setTileSetIdxMap(j * picSym->getFrameWidthInCU() + k, i, m_pcCfg->getIlcIdc(i), false);
+      }
+    }
+  }
+  
+  if (m_pcCfg->getSkippedTileSetPresentFlag())
+  {
+    Int skippedTileSetIdx = m_pcCfg->getIlNumSetsInMessage();
+    for (Int i = 0; i < numCUs; i++)
+    {
+      if (picSym->getTileSetIdxMap(i) < 0)
+      {
+        picSym->setTileSetIdxMap(i, skippedTileSetIdx, 0, true);
+      }
+    }
+  }
+}
+#endif
+#endif //SVC_EXTENSION
+
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncGOP.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncGOP.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -83,8 +83,4 @@
   Bool                    m_bFirst;
   
-#if SVC_EXTENSION
-  UInt                    m_layerId;      
-#endif
-
   //  Access channel
   TEncTop*                m_pcEncTop;
@@ -92,11 +88,4 @@
   TEncSlice*              m_pcSliceEncoder;
   TComList<TComPic*>*     m_pcListPic;
-  
-#if SVC_EXTENSION
-  TEncTop**               m_ppcTEncTop;
-#if SVC_UPSAMPLING
-  TEncSearch*             m_pcPredSearch;                       ///< encoder search class
-#endif  
-#endif
   
   TEncEntropy*            m_pcEntropyCoder;
@@ -120,4 +109,8 @@
   std::vector<Int>        m_storedStartCUAddrForEncodingSlice;
   std::vector<Int>        m_storedStartCUAddrForEncodingSliceSegment;
+#if FIX1172
+  NalUnitType             m_associatedIRAPType;
+  Int                     m_associatedIRAPPOC;
+#endif
 
   std::vector<Int> m_vRVM_RP;
@@ -132,4 +125,13 @@
   Bool                    m_nestedBufferingPeriodSEIPresentInAU;
   Bool                    m_nestedPictureTimingSEIPresentInAU;
+
+#if SVC_EXTENSION
+  UInt                    m_layerId;      
+  TEncTop**               m_ppcTEncTop;
+#if SVC_UPSAMPLING
+  TEncSearch*             m_pcPredSearch;                       ///< encoder search class
+#endif  
+#endif
+  
 public:
   TEncGOP();
@@ -162,5 +164,5 @@
   
   TEncSlice*  getSliceEncoder()   { return m_pcSliceEncoder; }
-  NalUnitType getNalUnitType( Int pocCurr, Int lastIdr );
+  NalUnitType getNalUnitType( Int pocCurr, Int lastIdr, Bool isField );
   Void arrangeLongtermPicturesInRPS(TComSlice *, TComList<TComPic*>& );
 protected:
@@ -181,15 +183,8 @@
 
   SEIActiveParameterSets* xCreateSEIActiveParameterSets (TComSPS *sps);
-#if LAYERS_NOT_PRESENT_SEI
-  SEILayersNotPresent*    xCreateSEILayersNotPresent ();
-#endif
   SEIFramePacking*        xCreateSEIFramePacking();
   SEIDisplayOrientation*  xCreateSEIDisplayOrientation();
 
   SEIToneMappingInfo*     xCreateSEIToneMappingInfo();
-
-#if N0383_IL_CONSTRAINED_TILE_SETS_SEI
-  SEIInterLayerConstrainedTileSets* xCreateSEIInterLayerConstrainedTileSets();
-#endif
 
   Void xCreateLeadingSEIMessages (/*SEIMessages seiMessages,*/ AccessUnit &accessUnit, TComSPS *sps);
@@ -206,8 +201,15 @@
     m_nestedPictureTimingSEIPresentInAU      = false;
   }
+  Void dblMetric( TComPic* pcPic, UInt uiNumSlices );
+
+#if SVC_EXTENSION
+#if LAYERS_NOT_PRESENT_SEI
+  SEILayersNotPresent*    xCreateSEILayersNotPresent ();
+#endif
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
   Void xBuildTileSetsMap(TComPicSym* picSym);
-#endif
-  Void dblMetric( TComPic* pcPic, UInt uiNumSlices );
+  SEIInterLayerConstrainedTileSets* xCreateSEIInterLayerConstrainedTileSets();
+#endif
+#endif //SVC_EXTENSION
 };// END CLASS DEFINITION TEncGOP
 
Index: trunk/source/Lib/TLibEncoder/TEncPic.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncPic.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncPic.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/TEncPic.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncPic.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncPic.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/TEncPreanalyzer.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/TEncPreanalyzer.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncPreanalyzer.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncPreanalyzer.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/TEncRateCtrl.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -46,6 +46,4 @@
 
 
-#if HM_CLEANUP_SAO
-
 /** rounding with IBDI
  * \param  x
@@ -259,5 +257,5 @@
   TComPicYuv* orgYuv= pPic->getPicYuvOrg();
   TComPicYuv* resYuv= pPic->getPicYuvRec();
-  m_labmda[SAO_Y]= lambdas[0]; m_labmda[SAO_Cb]= lambdas[1]; m_labmda[SAO_Cr]= lambdas[2];
+  m_lambda[SAO_Y]= lambdas[0]; m_lambda[SAO_Cb]= lambdas[1]; m_lambda[SAO_Cr]= lambdas[2];
   TComPicYuv* srcYuv = m_tempPicYuv;
   resYuv->copyToPic(srcYuv);
@@ -509,5 +507,5 @@
           if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
           {
-            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_labmda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], classDist , classCost , offsetTh );
+            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_lambda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], classDist , classCost , offsetTh );
           }
         }
@@ -523,8 +521,8 @@
         for(Int classIdx=0; classIdx< NUM_SAO_BO_CLASSES; classIdx++)
         {         
-          costBOClasses[classIdx]= m_labmda[compIdx];
+          costBOClasses[classIdx]= m_lambda[compIdx];
           if( quantOffsets[classIdx] != 0 ) //iterative adjustment only when derived offset is not zero
           {
-            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_labmda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], distBOClasses[classIdx], costBOClasses[classIdx], offsetTh );
+            quantOffsets[classIdx] = estIterOffset( typeIdc, classIdx, m_lambda[compIdx], quantOffsets[classIdx], statData.count[classIdx], statData.diff[classIdx], shift, m_offsetStepLog2[compIdx], distBOClasses[classIdx], costBOClasses[classIdx], offsetTh );
           }
         }
@@ -572,5 +570,6 @@
 {
   Double minCost, cost;
-  Int rate, minRate;
+  Int rate;
+  UInt previousWrittenBits;
   Int64 dist[NUM_SAO_COMPONENTS], modeDist[NUM_SAO_COMPONENTS];
   SAOOffset testOffset[NUM_SAO_COMPONENTS];
@@ -592,7 +591,6 @@
   m_pcRDGoOnSbacCoder->resetBits();
   m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, modeParam[compIdx], sliceEnabled[compIdx]);
-  minRate= m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
   modeDist[compIdx] = 0;
-  minCost= m_labmda[compIdx]*((Double)minRate);
+  minCost= m_lambda[compIdx]*((Double)m_pcRDGoOnSbacCoder->getNumberOfWrittenBits());
   m_pcRDGoOnSbacCoder->store(cabacCoderRDO[SAO_CABACSTATE_BLK_TEMP]);
   if(sliceEnabled[compIdx])
@@ -617,9 +615,8 @@
       m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, testOffset[compIdx], sliceEnabled[compIdx]);
       rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
-      cost = (Double)dist[compIdx] + m_labmda[compIdx]*((Double)rate);
+      cost = (Double)dist[compIdx] + m_lambda[compIdx]*((Double)rate);
       if(cost < minCost)
       {
         minCost = cost;
-        minRate = rate;
         modeDist[compIdx] = dist[compIdx];
         modeParam[compIdx]= testOffset[compIdx];
@@ -632,15 +629,21 @@
 
   //------ chroma --------//
-  assert(m_labmda[SAO_Cb] == m_labmda[SAO_Cr]);
-  Double chromaLambda = m_labmda[SAO_Cb];
   //"off" case as initial cost
+  cost = 0;
+  previousWrittenBits = 0;
   m_pcRDGoOnSbacCoder->resetBits();
-  modeParam[SAO_Cb].modeIdc = SAO_MODE_OFF; 
-  m_pcRDGoOnSbacCoder->codeSAOOffsetParam(SAO_Cb, modeParam[SAO_Cb], sliceEnabled[SAO_Cb]);
-  modeParam[SAO_Cr].modeIdc = SAO_MODE_OFF; 
-  m_pcRDGoOnSbacCoder->codeSAOOffsetParam(SAO_Cr, modeParam[SAO_Cr], sliceEnabled[SAO_Cr]);
-  minRate= m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
-  modeDist[SAO_Cb] = modeDist[SAO_Cr]= 0;
-  minCost= chromaLambda*((Double)minRate); 
+  for (Int component = SAO_Cb; component < NUM_SAO_COMPONENTS; component++)
+  {
+    modeParam[component].modeIdc = SAO_MODE_OFF; 
+    modeDist [component] = 0;
+
+    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(component, modeParam[component], sliceEnabled[component]);
+
+    const UInt currentWrittenBits = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+    cost += m_lambda[component] * (currentWrittenBits - previousWrittenBits);
+    previousWrittenBits = currentWrittenBits;
+  }
+
+  minCost = cost;
 
   //doesn't need to store cabac status here since the whole CTU parameters will be re-encoded at the end of this function
@@ -648,4 +651,9 @@
   for(Int typeIdc=0; typeIdc< NUM_SAO_NEW_TYPES; typeIdc++)
   {
+    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
+    m_pcRDGoOnSbacCoder->resetBits();
+    previousWrittenBits = 0;
+    cost = 0;
+
     for(compIdx= SAO_Cb; compIdx< NUM_SAO_COMPONENTS; compIdx++)
     {
@@ -663,22 +671,20 @@
       invertQuantOffsets(compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, testOffset[compIdx].offset);
       dist[compIdx]= getDistortion(ctu, compIdx, typeIdc, testOffset[compIdx].typeAuxInfo, invQuantOffset, blkStats[ctu][compIdx][typeIdc]);
-    }
-
-    //get rate
-    m_pcRDGoOnSbacCoder->load(cabacCoderRDO[SAO_CABACSTATE_BLK_MID]);
-    m_pcRDGoOnSbacCoder->resetBits();
-    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(SAO_Cb, testOffset[SAO_Cb], sliceEnabled[SAO_Cb]);
-    m_pcRDGoOnSbacCoder->codeSAOOffsetParam(SAO_Cr, testOffset[SAO_Cr], sliceEnabled[SAO_Cr]);
-    rate = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
-
-    cost = (Double)(dist[SAO_Cb]+ dist[SAO_Cr]) + chromaLambda*((Double)rate);
+
+      m_pcRDGoOnSbacCoder->codeSAOOffsetParam(compIdx, testOffset[compIdx], sliceEnabled[compIdx]);
+
+      const UInt currentWrittenBits = m_pcRDGoOnSbacCoder->getNumberOfWrittenBits();
+      cost += dist[compIdx] + (m_lambda[compIdx] * (currentWrittenBits - previousWrittenBits));
+      previousWrittenBits = currentWrittenBits;
+    }
+
     if(cost < minCost)
     {
       minCost = cost;
-      minRate = rate;
-      modeDist[SAO_Cb] = dist[SAO_Cb];
-      modeDist[SAO_Cr] = dist[SAO_Cr];
-      modeParam[SAO_Cb]= testOffset[SAO_Cb];
-      modeParam[SAO_Cr]= testOffset[SAO_Cr];
+      for(compIdx= SAO_Cb; compIdx< NUM_SAO_COMPONENTS; compIdx++)
+      {
+        modeDist [compIdx] = dist      [compIdx];
+        modeParam[compIdx] = testOffset[compIdx];
+      }
     }
   }
@@ -686,6 +692,9 @@
 
   //----- re-gen rate & normalized cost----//
-  modeNormCost  = (Double)modeDist[SAO_Y]/m_labmda[SAO_Y];
-  modeNormCost += (Double)(modeDist[SAO_Cb]+ modeDist[SAO_Cr])/chromaLambda; 
+  modeNormCost = 0;
+  for(UInt component = SAO_Y; component < NUM_SAO_COMPONENTS; component++)
+  {
+    modeNormCost += (Double)modeDist[component] / m_lambda[component];
+  }
   m_pcRDGoOnSbacCoder->load(cabacCoderRDO[inCabacLabel]);
   m_pcRDGoOnSbacCoder->resetBits();
@@ -724,5 +733,5 @@
         //offsets have been reconstructed. Don't call inversed quantization function.
         normDist += (((Double)getDistortion(ctu, compIdx, mergedOffsetParam.typeIdc, mergedOffsetParam.typeAuxInfo, mergedOffsetParam.offset, blkStats[ctu][compIdx][mergedOffsetParam.typeIdc]))
-                       /m_labmda[compIdx]
+                       /m_lambda[compIdx]
                     );
       }
@@ -1304,2458 +1313,3 @@
 }
 
-#else
-
-
-
-TEncSampleAdaptiveOffset::TEncSampleAdaptiveOffset()
-{
-  m_pcEntropyCoder = NULL;
-  m_pppcRDSbacCoder = NULL;
-  m_pcRDGoOnSbacCoder = NULL;
-  m_pppcBinCoderCABAC = NULL;            
-  m_iCount = NULL;     
-  m_iOffset = NULL;      
-  m_iOffsetOrg = NULL;  
-  m_iRate = NULL;       
-  m_iDist = NULL;        
-  m_dCost = NULL;        
-  m_dCostPartBest = NULL; 
-  m_iDistOrg = NULL;      
-  m_iTypePartBest = NULL; 
-#if SAO_ENCODING_CHOICE_CHROMA
-  m_depthSaoRate[0][0] = 0;
-  m_depthSaoRate[0][1] = 0;
-  m_depthSaoRate[0][2] = 0;
-  m_depthSaoRate[0][3] = 0;
-  m_depthSaoRate[1][0] = 0;
-  m_depthSaoRate[1][1] = 0;
-  m_depthSaoRate[1][2] = 0;
-  m_depthSaoRate[1][3] = 0;
-#endif
-}
-TEncSampleAdaptiveOffset::~TEncSampleAdaptiveOffset()
-{
-
-}
-// ====================================================================================================================
-// Constants
-// ====================================================================================================================
-
-
-// ====================================================================================================================
-// Tables
-// ====================================================================================================================
-
-inline Double xRoundIbdi2(Int bitDepth, Double x)
-{
-  return ((x)>0) ? (Int)(((Int)(x)+(1<<(bitDepth-8-1)))/(1<<(bitDepth-8))) : ((Int)(((Int)(x)-(1<<(bitDepth-8-1)))/(1<<(bitDepth-8))));
-}
-
-/** rounding with IBDI
- * \param  x
- */
-inline Double xRoundIbdi(Int bitDepth, Double x)
-{
-  return (bitDepth > 8 ? xRoundIbdi2(bitDepth, (x)) : ((x)>=0 ? ((Int)((x)+0.5)) : ((Int)((x)-0.5)))) ;
-}
-
-
-
-/** process SAO for one partition
- * \param  *psQTPart, iPartIdx, dLambda
- */
-Void TEncSampleAdaptiveOffset::rdoSaoOnePart(SAOQTPart *psQTPart, Int iPartIdx, Double dLambda, Int yCbCr)
-{
-  Int iTypeIdx;
-  Int iNumTotalType = MAX_NUM_SAO_TYPE;
-  SAOQTPart*  pOnePart = &(psQTPart[iPartIdx]);
-
-  Int64 iEstDist;
-  Int iClassIdx;
-  Int uiShift = 2 * DISTORTION_PRECISION_ADJUSTMENT((yCbCr == 0 ? g_bitDepthY : g_bitDepthC)-8);
-  UInt uiDepth = pOnePart->PartLevel;
-
-  m_iDistOrg [iPartIdx] =  0;
-
-  Double  bestRDCostTableBo = MAX_DOUBLE;
-  Int     bestClassTableBo    = 0;
-  Int     currentDistortionTableBo[MAX_NUM_SAO_CLASS];
-  Double  currentRdCostTableBo[MAX_NUM_SAO_CLASS];
-
-  Int addr;
-  Int allowMergeLeft;
-  Int allowMergeUp;
-  Int frameWidthInCU = m_pcPic->getFrameWidthInCU();
-  SaoLcuParam  saoLcuParamRdo;
-
-  for (iTypeIdx=-1; iTypeIdx<iNumTotalType; iTypeIdx++)
-  {
-    if( m_bUseSBACRD )
-    {
-      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
-      m_pcRDGoOnSbacCoder->resetBits();
-    }
-    else
-    {
-      m_pcEntropyCoder->resetEntropy();
-      m_pcEntropyCoder->resetBits();
-    }
-
-    iEstDist = 0;
-
-    if (iTypeIdx == -1)
-    {      
-      for (Int ry = pOnePart->StartCUY; ry<= pOnePart->EndCUY; ry++)
-      {
-        for (Int rx = pOnePart->StartCUX; rx <= pOnePart->EndCUX; rx++)
-        {
-          addr = ry * frameWidthInCU + rx;          
-
-          // get bits for iTypeIdx = -1
-          allowMergeLeft = 1;
-          allowMergeUp   = 1;
-          if (rx != 0)
-          { 
-            // check tile id and slice id 
-            if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-1) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-1)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
-            {
-              allowMergeLeft = 0;
-            }
-          }
-          if (ry!=0)
-          {
-            if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-m_iNumCuInWidth) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-m_iNumCuInWidth)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
-            {
-              allowMergeUp = 0;
-            }
-          }
-
-          // reset
-          resetSaoUnit(&saoLcuParamRdo);
-
-          // set merge flag
-          saoLcuParamRdo.mergeUpFlag   = 1;
-          saoLcuParamRdo.mergeLeftFlag = 1;
-
-          if (ry == pOnePart->StartCUY) 
-          {
-            saoLcuParamRdo.mergeUpFlag = 0;
-          } 
-          
-          if (rx == pOnePart->StartCUX) 
-          {
-            saoLcuParamRdo.mergeLeftFlag = 0;
-          }
-
-          m_pcEntropyCoder->encodeSaoUnitInterleaving(yCbCr, 1, rx, ry,  &saoLcuParamRdo, 1,  1,  allowMergeLeft, allowMergeUp);
-
-        }
-      }
-    }
-
-    if (iTypeIdx>=0)
-    {
-      iEstDist = estSaoTypeDist(iPartIdx, iTypeIdx, uiShift, dLambda, currentDistortionTableBo, currentRdCostTableBo);
-      if( iTypeIdx == SAO_BO )
-      {
-        // Estimate Best Position
-        Double currentRDCost = 0.0;
-
-        for(Int i=0; i< SAO_MAX_BO_CLASSES -SAO_BO_LEN +1; i++)
-        {
-          currentRDCost = 0.0;
-          for(UInt uj = i; uj < i+SAO_BO_LEN; uj++)
-          {
-            currentRDCost += currentRdCostTableBo[uj];
-          }
-
-          if( currentRDCost < bestRDCostTableBo)
-          {
-            bestRDCostTableBo = currentRDCost;
-            bestClassTableBo  = i;
-          }
-        }
-
-        // Re code all Offsets
-        // Code Center
-        for(iClassIdx = bestClassTableBo; iClassIdx < bestClassTableBo+SAO_BO_LEN; iClassIdx++)
-        {
-          iEstDist += currentDistortionTableBo[iClassIdx];
-        }
-      }
-
-      for (Int ry = pOnePart->StartCUY; ry<= pOnePart->EndCUY; ry++)
-      {
-        for (Int rx = pOnePart->StartCUX; rx <= pOnePart->EndCUX; rx++)
-        {
-          addr = ry * frameWidthInCU + rx;          
-
-          // get bits for iTypeIdx = -1
-          allowMergeLeft = 1;
-          allowMergeUp   = 1;
-          if (rx != 0)
-          { 
-            // check tile id and slice id 
-            if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-1) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-1)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
-            {
-              allowMergeLeft = 0;
-            }
-          }
-          if (ry!=0)
-          {
-            if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-m_iNumCuInWidth) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-m_iNumCuInWidth)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
-            {
-              allowMergeUp = 0;
-            }
-          }
-
-          // reset
-          resetSaoUnit(&saoLcuParamRdo);
-          
-          // set merge flag
-          saoLcuParamRdo.mergeUpFlag   = 1;
-          saoLcuParamRdo.mergeLeftFlag = 1;
-
-          if (ry == pOnePart->StartCUY) 
-          {
-            saoLcuParamRdo.mergeUpFlag = 0;
-          } 
-          
-          if (rx == pOnePart->StartCUX) 
-          {
-            saoLcuParamRdo.mergeLeftFlag = 0;
-          }
-
-          // set type and offsets
-          saoLcuParamRdo.typeIdx = iTypeIdx;
-          saoLcuParamRdo.subTypeIdx = (iTypeIdx==SAO_BO)?bestClassTableBo:0;
-          saoLcuParamRdo.length = m_iNumClass[iTypeIdx];
-          for (iClassIdx = 0; iClassIdx < saoLcuParamRdo.length; iClassIdx++)
-          {
-            saoLcuParamRdo.offset[iClassIdx] = (Int)m_iOffset[iPartIdx][iTypeIdx][iClassIdx+saoLcuParamRdo.subTypeIdx+1];
-          }
-
-          m_pcEntropyCoder->encodeSaoUnitInterleaving(yCbCr, 1, rx, ry,  &saoLcuParamRdo, 1,  1,  allowMergeLeft, allowMergeUp);
-
-        }
-      }
-
-      m_iDist[iPartIdx][iTypeIdx] = iEstDist;
-      m_iRate[iPartIdx][iTypeIdx] = m_pcEntropyCoder->getNumberOfWrittenBits();
-
-      m_dCost[iPartIdx][iTypeIdx] = (Double)((Double)m_iDist[iPartIdx][iTypeIdx] + dLambda * (Double) m_iRate[iPartIdx][iTypeIdx]);
-
-      if(m_dCost[iPartIdx][iTypeIdx] < m_dCostPartBest[iPartIdx])
-      {
-        m_iDistOrg [iPartIdx] = 0;
-        m_dCostPartBest[iPartIdx] = m_dCost[iPartIdx][iTypeIdx];
-        m_iTypePartBest[iPartIdx] = iTypeIdx;
-        if( m_bUseSBACRD )
-          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[pOnePart->PartLevel][CI_TEMP_BEST] );
-      }
-    }
-    else
-    {
-      if(m_iDistOrg[iPartIdx] < m_dCostPartBest[iPartIdx] )
-      {
-        m_dCostPartBest[iPartIdx] = (Double) m_iDistOrg[iPartIdx] + m_pcEntropyCoder->getNumberOfWrittenBits()*dLambda ; 
-        m_iTypePartBest[iPartIdx] = -1;
-        if( m_bUseSBACRD )
-        {
-          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[pOnePart->PartLevel][CI_TEMP_BEST] );
-        }
-      }
-    }
-  }
-
-  pOnePart->bProcessed = true;
-  pOnePart->bSplit     = false;
-  pOnePart->iMinDist   =        m_iTypePartBest[iPartIdx] >= 0 ? m_iDist[iPartIdx][m_iTypePartBest[iPartIdx]] : m_iDistOrg[iPartIdx];
-  pOnePart->iMinRate   = (Int) (m_iTypePartBest[iPartIdx] >= 0 ? m_iRate[iPartIdx][m_iTypePartBest[iPartIdx]] : 0);
-  pOnePart->dMinCost   = pOnePart->iMinDist + dLambda * pOnePart->iMinRate;
-  pOnePart->iBestType  = m_iTypePartBest[iPartIdx];
-  if (pOnePart->iBestType != -1)
-  {
-    //     pOnePart->bEnableFlag =  1;
-    pOnePart->iLength = m_iNumClass[pOnePart->iBestType];
-    Int minIndex = 0;
-    if( pOnePart->iBestType == SAO_BO )
-    {
-      pOnePart->subTypeIdx = bestClassTableBo;
-      minIndex = pOnePart->subTypeIdx;
-    }
-    for (Int i=0; i< pOnePart->iLength ; i++)
-    {
-      pOnePart->iOffset[i] = (Int) m_iOffset[iPartIdx][pOnePart->iBestType][minIndex+i+1];
-    }
-
-  }
-  else
-  {
-    //     pOnePart->bEnableFlag = 0;
-    pOnePart->iLength     = 0;
-  }
-}
-
-/** Run partition tree disable
- */
-Void TEncSampleAdaptiveOffset::disablePartTree(SAOQTPart *psQTPart, Int iPartIdx)
-{
-  SAOQTPart*  pOnePart= &(psQTPart[iPartIdx]);
-  pOnePart->bSplit      = false;
-  pOnePart->iLength     =  0;
-  pOnePart->iBestType   = -1;
-
-  if (pOnePart->PartLevel < m_uiMaxSplitLevel)
-  {
-    for (Int i=0; i<NUM_DOWN_PART; i++)
-    {
-      disablePartTree(psQTPart, pOnePart->DownPartsIdx[i]);
-    }
-  }
-}
-
-/** Run quadtree decision function
- * \param  iPartIdx, pcPicOrg, pcPicDec, pcPicRest, &dCostFinal
- */
-Void TEncSampleAdaptiveOffset::runQuadTreeDecision(SAOQTPart *psQTPart, Int iPartIdx, Double &dCostFinal, Int iMaxLevel, Double dLambda, Int yCbCr)
-{
-  SAOQTPart*  pOnePart = &(psQTPart[iPartIdx]);
-
-  UInt uiDepth = pOnePart->PartLevel;
-  UInt uhNextDepth = uiDepth+1;
-
-  if (iPartIdx == 0)
-  {
-    dCostFinal = 0;
-  }
-
-  //SAO for this part
-  if(!pOnePart->bProcessed)
-  {
-    rdoSaoOnePart (psQTPart, iPartIdx, dLambda, yCbCr);
-  }
-
-  //SAO for sub 4 parts
-  if (pOnePart->PartLevel < iMaxLevel)
-  {
-    Double      dCostNotSplit = dLambda + pOnePart->dMinCost;
-    Double      dCostSplit    = dLambda;
-
-    for (Int i=0; i< NUM_DOWN_PART ;i++)
-    {
-      if( m_bUseSBACRD )  
-      {
-        if ( 0 == i) //initialize RD with previous depth buffer
-        {
-          m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
-        }
-        else
-        {
-          m_pppcRDSbacCoder[uhNextDepth][CI_CURR_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
-        }
-      }  
-      runQuadTreeDecision(psQTPart, pOnePart->DownPartsIdx[i], dCostFinal, iMaxLevel, dLambda, yCbCr);
-      dCostSplit += dCostFinal;
-      if( m_bUseSBACRD )
-      {
-        m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_TEMP_BEST]);
-      }
-    }
-
-    if(dCostSplit < dCostNotSplit)
-    {
-      dCostFinal = dCostSplit;
-      pOnePart->bSplit      = true;
-      pOnePart->iLength     =  0;
-      pOnePart->iBestType   = -1;
-      if( m_bUseSBACRD )
-      {
-        m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]->load(m_pppcRDSbacCoder[uhNextDepth][CI_NEXT_BEST]);
-      }
-    }
-    else
-    {
-      dCostFinal = dCostNotSplit;
-      pOnePart->bSplit = false;
-      for (Int i=0; i<NUM_DOWN_PART; i++)
-      {
-        disablePartTree(psQTPart, pOnePart->DownPartsIdx[i]);
-      }
-      if( m_bUseSBACRD )
-      {
-        m_pppcRDSbacCoder[uiDepth][CI_NEXT_BEST]->load(m_pppcRDSbacCoder[uiDepth][CI_TEMP_BEST]);
-      }
-    }
-  }
-  else
-  {
-    dCostFinal = pOnePart->dMinCost;
-  }
-}
-
-/** delete allocated memory of TEncSampleAdaptiveOffset class.
- */
-Void TEncSampleAdaptiveOffset::destroyEncBuffer()
-{
-  for (Int i=0;i<m_iNumTotalParts;i++)
-  {
-    for (Int j=0;j<MAX_NUM_SAO_TYPE;j++)
-    {
-      if (m_iCount [i][j])
-      {
-        delete [] m_iCount [i][j]; 
-      }
-      if (m_iOffset[i][j])
-      {
-        delete [] m_iOffset[i][j]; 
-      }
-      if (m_iOffsetOrg[i][j])
-      {
-        delete [] m_iOffsetOrg[i][j]; 
-      }
-    }
-    if (m_iRate[i])
-    {
-      delete [] m_iRate[i];
-    }
-    if (m_iDist[i])
-    {
-      delete [] m_iDist[i]; 
-    }
-    if (m_dCost[i])
-    {
-      delete [] m_dCost[i]; 
-    }
-    if (m_iCount [i])
-    {
-      delete [] m_iCount [i]; 
-    }
-    if (m_iOffset[i])
-    {
-      delete [] m_iOffset[i]; 
-    }
-    if (m_iOffsetOrg[i])
-    {
-      delete [] m_iOffsetOrg[i]; 
-    }
-
-  }
-  if (m_iDistOrg)
-  {
-    delete [] m_iDistOrg ; m_iDistOrg = NULL;
-  }
-  if (m_dCostPartBest)
-  {
-    delete [] m_dCostPartBest ; m_dCostPartBest = NULL;
-  }
-  if (m_iTypePartBest)
-  {
-    delete [] m_iTypePartBest ; m_iTypePartBest = NULL;
-  }
-  if (m_iRate)
-  {
-    delete [] m_iRate ; m_iRate = NULL;
-  }
-  if (m_iDist)
-  {
-    delete [] m_iDist ; m_iDist = NULL;
-  }
-  if (m_dCost)
-  {
-    delete [] m_dCost ; m_dCost = NULL;
-  }
-  if (m_iCount)
-  {
-    delete [] m_iCount  ; m_iCount = NULL;
-  }
-  if (m_iOffset)
-  {
-    delete [] m_iOffset ; m_iOffset = NULL;
-  }
-  if (m_iOffsetOrg)
-  {
-    delete [] m_iOffsetOrg ; m_iOffsetOrg = NULL;
-  }
-  Int numLcu = m_iNumCuInWidth * m_iNumCuInHeight;
-
-  for (Int i=0;i<numLcu;i++)
-  {
-    for (Int j=0;j<3;j++)
-    {
-      for (Int k=0;k<MAX_NUM_SAO_TYPE;k++)
-      {
-        if (m_count_PreDblk [i][j][k])
-        {
-          delete [] m_count_PreDblk [i][j][k]; 
-        }
-        if (m_offsetOrg_PreDblk[i][j][k])
-        {
-          delete [] m_offsetOrg_PreDblk[i][j][k];
-        }
-      }
-      if (m_count_PreDblk [i][j])
-      {
-        delete [] m_count_PreDblk [i][j]; 
-      }
-      if (m_offsetOrg_PreDblk[i][j])
-      {
-        delete [] m_offsetOrg_PreDblk[i][j]; 
-      }
-    }
-    if (m_count_PreDblk [i])
-    {
-      delete [] m_count_PreDblk [i]; 
-    }
-    if (m_offsetOrg_PreDblk[i])
-    {
-      delete [] m_offsetOrg_PreDblk[i]; 
-    }
-  }
-  if (m_count_PreDblk)
-  {
-    delete [] m_count_PreDblk  ; m_count_PreDblk = NULL;
-  }
-  if (m_offsetOrg_PreDblk)
-  {
-    delete [] m_offsetOrg_PreDblk ; m_offsetOrg_PreDblk = NULL;
-  }
-
-  Int iMaxDepth = 4;
-  Int iDepth;
-  for ( iDepth = 0; iDepth < iMaxDepth+1; iDepth++ )
-  {
-    for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
-    {
-      delete m_pppcRDSbacCoder[iDepth][iCIIdx];
-      delete m_pppcBinCoderCABAC[iDepth][iCIIdx];
-    }
-  }
-
-  for ( iDepth = 0; iDepth < iMaxDepth+1; iDepth++ )
-  {
-    delete [] m_pppcRDSbacCoder[iDepth];
-    delete [] m_pppcBinCoderCABAC[iDepth];
-  }
-
-  delete [] m_pppcRDSbacCoder;
-  delete [] m_pppcBinCoderCABAC;
-}
-
-/** create Encoder Buffer for SAO
- * \param 
- */
-Void TEncSampleAdaptiveOffset::createEncBuffer()
-{
-  m_iDistOrg = new Int64 [m_iNumTotalParts]; 
-  m_dCostPartBest = new Double [m_iNumTotalParts]; 
-  m_iTypePartBest = new Int [m_iNumTotalParts]; 
-
-  m_iRate = new Int64* [m_iNumTotalParts];
-  m_iDist = new Int64* [m_iNumTotalParts];
-  m_dCost = new Double*[m_iNumTotalParts];
-
-  m_iCount  = new Int64 **[m_iNumTotalParts];
-  m_iOffset = new Int64 **[m_iNumTotalParts];
-  m_iOffsetOrg = new Int64 **[m_iNumTotalParts];
-
-  for (Int i=0;i<m_iNumTotalParts;i++)
-  {
-    m_iRate[i] = new Int64  [MAX_NUM_SAO_TYPE];
-    m_iDist[i] = new Int64  [MAX_NUM_SAO_TYPE]; 
-    m_dCost[i] = new Double [MAX_NUM_SAO_TYPE]; 
-
-    m_iCount [i] = new Int64 *[MAX_NUM_SAO_TYPE]; 
-    m_iOffset[i] = new Int64 *[MAX_NUM_SAO_TYPE]; 
-    m_iOffsetOrg[i] = new Int64 *[MAX_NUM_SAO_TYPE]; 
-
-    for (Int j=0;j<MAX_NUM_SAO_TYPE;j++)
-    {
-      m_iCount [i][j]   = new Int64 [MAX_NUM_SAO_CLASS]; 
-      m_iOffset[i][j]   = new Int64 [MAX_NUM_SAO_CLASS]; 
-      m_iOffsetOrg[i][j]= new Int64 [MAX_NUM_SAO_CLASS]; 
-    }
-  }
-  Int numLcu = m_iNumCuInWidth * m_iNumCuInHeight;
-  m_count_PreDblk  = new Int64 ***[numLcu];
-  m_offsetOrg_PreDblk = new Int64 ***[numLcu];
-  for (Int i=0; i<numLcu; i++)
-  {
-    m_count_PreDblk[i]  = new Int64 **[3];
-    m_offsetOrg_PreDblk[i] = new Int64 **[3];
-
-    for (Int j=0;j<3;j++)
-    {
-      m_count_PreDblk [i][j] = new Int64 *[MAX_NUM_SAO_TYPE]; 
-      m_offsetOrg_PreDblk[i][j] = new Int64 *[MAX_NUM_SAO_TYPE]; 
-
-      for (Int k=0;k<MAX_NUM_SAO_TYPE;k++)
-      {
-        m_count_PreDblk [i][j][k]   = new Int64 [MAX_NUM_SAO_CLASS]; 
-        m_offsetOrg_PreDblk[i][j][k]= new Int64 [MAX_NUM_SAO_CLASS]; 
-      }
-    }
-  }
-
-  Int iMaxDepth = 4;
-  m_pppcRDSbacCoder = new TEncSbac** [iMaxDepth+1];
-#if FAST_BIT_EST
-  m_pppcBinCoderCABAC = new TEncBinCABACCounter** [iMaxDepth+1];
-#else
-  m_pppcBinCoderCABAC = new TEncBinCABAC** [iMaxDepth+1];
-#endif
-
-  for ( Int iDepth = 0; iDepth < iMaxDepth+1; iDepth++ )
-  {
-    m_pppcRDSbacCoder[iDepth] = new TEncSbac* [CI_NUM];
-#if FAST_BIT_EST
-    m_pppcBinCoderCABAC[iDepth] = new TEncBinCABACCounter* [CI_NUM];
-#else
-    m_pppcBinCoderCABAC[iDepth] = new TEncBinCABAC* [CI_NUM];
-#endif
-    for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
-    {
-      m_pppcRDSbacCoder[iDepth][iCIIdx] = new TEncSbac;
-#if FAST_BIT_EST
-      m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABACCounter;
-#else
-      m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABAC;
-#endif
-      m_pppcRDSbacCoder   [iDepth][iCIIdx]->init( m_pppcBinCoderCABAC [iDepth][iCIIdx] );
-    }
-  }
-}
-
-/** Start SAO encoder
- * \param pcPic, pcEntropyCoder, pppcRDSbacCoder, pcRDGoOnSbacCoder 
- */
-Void TEncSampleAdaptiveOffset::startSaoEnc( TComPic* pcPic, TEncEntropy* pcEntropyCoder, TEncSbac*** pppcRDSbacCoder, TEncSbac* pcRDGoOnSbacCoder)
-{
-    m_bUseSBACRD = true;
-  m_pcPic = pcPic;
-  m_pcEntropyCoder = pcEntropyCoder;
-
-  m_pcRDGoOnSbacCoder = pcRDGoOnSbacCoder;
-  m_pcEntropyCoder->setEntropyCoder(m_pcRDGoOnSbacCoder, pcPic->getSlice(0));
-  m_pcEntropyCoder->resetEntropy();
-  m_pcEntropyCoder->resetBits();
-
-  if( m_bUseSBACRD )
-  {
-    m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_NEXT_BEST]);
-    m_pppcRDSbacCoder[0][CI_CURR_BEST]->load( m_pppcRDSbacCoder[0][CI_NEXT_BEST]);
-  }
-}
-
-/** End SAO encoder
- */
-Void TEncSampleAdaptiveOffset::endSaoEnc()
-{
-  m_pcPic = NULL;
-  m_pcEntropyCoder = NULL;
-}
-
-inline Int xSign(Int x)
-{
-  return ((x >> 31) | ((Int)( (((UInt) -x)) >> 31)));
-}
-
-/** Calculate SAO statistics for non-cross-slice or non-cross-tile processing
- * \param  pRecStart to-be-filtered block buffer pointer
- * \param  pOrgStart original block buffer pointer
- * \param  stride picture buffer stride
- * \param  ppStat statistics buffer
- * \param  ppCount counter buffer
- * \param  width block width
- * \param  height block height
- * \param  pbBorderAvail availabilities of block border pixels
- */
-Void TEncSampleAdaptiveOffset::calcSaoStatsBlock( Pel* pRecStart, Pel* pOrgStart, Int stride, Int64** ppStats, Int64** ppCount, UInt width, UInt height, Bool* pbBorderAvail, Int iYCbCr)
-{
-  Int64 *stats, *count;
-  Int classIdx, posShift, startX, endX, startY, endY, signLeft,signRight,signDown,signDown1;
-  Pel *pOrg, *pRec;
-  UInt edgeType;
-  Int x, y;
-  Pel *pTableBo = (iYCbCr==0)?m_lumaTableBo:m_chromaTableBo;
-
-  //--------- Band offset-----------//
-  stats = ppStats[SAO_BO];
-  count = ppCount[SAO_BO];
-  pOrg   = pOrgStart;
-  pRec   = pRecStart;
-  for (y=0; y< height; y++)
-  {
-    for (x=0; x< width; x++)
-    {
-      classIdx = pTableBo[pRec[x]];
-      if (classIdx)
-      {
-        stats[classIdx] += (pOrg[x] - pRec[x]); 
-        count[classIdx] ++;
-      }
-    }
-    pOrg += stride;
-    pRec += stride;
-  }
-  //---------- Edge offset 0--------------//
-  stats = ppStats[SAO_EO_0];
-  count = ppCount[SAO_EO_0];
-  pOrg   = pOrgStart;
-  pRec   = pRecStart;
-
-
-  startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
-  endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
-  for (y=0; y< height; y++)
-  {
-    signLeft = xSign(pRec[startX] - pRec[startX-1]);
-    for (x=startX; x< endX; x++)
-    {
-      signRight =  xSign(pRec[x] - pRec[x+1]); 
-      edgeType =  signRight + signLeft + 2;
-      signLeft  = -signRight;
-
-      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-      count[m_auiEoTable[edgeType]] ++;
-    }
-    pRec  += stride;
-    pOrg += stride;
-  }
-
-  //---------- Edge offset 1--------------//
-  stats = ppStats[SAO_EO_1];
-  count = ppCount[SAO_EO_1];
-  pOrg   = pOrgStart;
-  pRec   = pRecStart;
-
-  startY = (pbBorderAvail[SGU_T]) ? 0 : 1;
-  endY   = (pbBorderAvail[SGU_B]) ? height : height-1;
-  if (!pbBorderAvail[SGU_T])
-  {
-    pRec  += stride;
-    pOrg  += stride;
-  }
-
-  for (x=0; x< width; x++)
-  {
-    m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride]);
-  }
-  for (y=startY; y<endY; y++)
-  {
-    for (x=0; x< width; x++)
-    {
-      signDown     =  xSign(pRec[x] - pRec[x+stride]); 
-      edgeType    =  signDown + m_iUpBuff1[x] + 2;
-      m_iUpBuff1[x] = -signDown;
-
-      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-      count[m_auiEoTable[edgeType]] ++;
-    }
-    pOrg += stride;
-    pRec += stride;
-  }
-  //---------- Edge offset 2--------------//
-  stats = ppStats[SAO_EO_2];
-  count = ppCount[SAO_EO_2];
-  pOrg   = pOrgStart;
-  pRec   = pRecStart;
-
-  posShift= stride + 1;
-
-  startX = (pbBorderAvail[SGU_L]) ? 0 : 1 ;
-  endX   = (pbBorderAvail[SGU_R]) ? width : (width-1);
-
-  //prepare 2nd line upper sign
-  pRec += stride;
-  for (x=startX; x< endX+1; x++)
-  {
-    m_iUpBuff1[x] = xSign(pRec[x] - pRec[x- posShift]);
-  }
-
-  //1st line
-  pRec -= stride;
-  if(pbBorderAvail[SGU_TL])
-  {
-    x= 0;
-    edgeType      =  xSign(pRec[x] - pRec[x- posShift]) - m_iUpBuff1[x+1] + 2;
-    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-    count[m_auiEoTable[edgeType]] ++;
-  }
-  if(pbBorderAvail[SGU_T])
-  {
-    for(x= 1; x< endX; x++)
-    {
-      edgeType      =  xSign(pRec[x] - pRec[x- posShift]) - m_iUpBuff1[x+1] + 2;
-      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-      count[m_auiEoTable[edgeType]] ++;
-    }
-  }
-  pRec   += stride;
-  pOrg   += stride;
-
-  //middle lines
-  for (y= 1; y< height-1; y++)
-  {
-    for (x=startX; x<endX; x++)
-    {
-      signDown1      =  xSign(pRec[x] - pRec[x+ posShift]) ;
-      edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
-      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-      count[m_auiEoTable[edgeType]] ++;
-
-      m_iUpBufft[x+1] = -signDown1; 
-    }
-    m_iUpBufft[startX] = xSign(pRec[stride+startX] - pRec[startX-1]);
-
-    ipSwap     = m_iUpBuff1;
-    m_iUpBuff1 = m_iUpBufft;
-    m_iUpBufft = ipSwap;
-
-    pRec  += stride;
-    pOrg  += stride;
-  }
-
-  //last line
-  if(pbBorderAvail[SGU_B])
-  {
-    for(x= startX; x< width-1; x++)
-    {
-      edgeType =  xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
-      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-      count[m_auiEoTable[edgeType]] ++;
-    }
-  }
-  if(pbBorderAvail[SGU_BR])
-  {
-    x= width -1;
-    edgeType =  xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
-    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-    count[m_auiEoTable[edgeType]] ++;
-  }
-
-  //---------- Edge offset 3--------------//
-
-  stats = ppStats[SAO_EO_3];
-  count = ppCount[SAO_EO_3];
-  pOrg   = pOrgStart;
-  pRec   = pRecStart;
-
-  posShift     = stride - 1;
-  startX = (pbBorderAvail[SGU_L]) ? 0 : 1;
-  endX   = (pbBorderAvail[SGU_R]) ? width : (width -1);
-
-  //prepare 2nd line upper sign
-  pRec += stride;
-  for (x=startX-1; x< endX; x++)
-  {
-    m_iUpBuff1[x] = xSign(pRec[x] - pRec[x- posShift]);
-  }
-
-
-  //first line
-  pRec -= stride;
-  if(pbBorderAvail[SGU_T])
-  {
-    for(x= startX; x< width -1; x++)
-    {
-      edgeType = xSign(pRec[x] - pRec[x- posShift]) -m_iUpBuff1[x-1] + 2;
-      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-      count[m_auiEoTable[edgeType]] ++;
-    }
-  }
-  if(pbBorderAvail[SGU_TR])
-  {
-    x= width-1;
-    edgeType = xSign(pRec[x] - pRec[x- posShift]) -m_iUpBuff1[x-1] + 2;
-    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-    count[m_auiEoTable[edgeType]] ++;
-  }
-  pRec  += stride;
-  pOrg  += stride;
-
-  //middle lines
-  for (y= 1; y< height-1; y++)
-  {
-    for(x= startX; x< endX; x++)
-    {
-      signDown1      =  xSign(pRec[x] - pRec[x+ posShift]) ;
-      edgeType      =  signDown1 + m_iUpBuff1[x] + 2;
-
-      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-      count[m_auiEoTable[edgeType]] ++;
-      m_iUpBuff1[x-1] = -signDown1; 
-
-    }
-    m_iUpBuff1[endX-1] = xSign(pRec[endX-1 + stride] - pRec[endX]);
-
-    pRec  += stride;
-    pOrg  += stride;
-  }
-
-  //last line
-  if(pbBorderAvail[SGU_BL])
-  {
-    x= 0;
-    edgeType = xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
-    stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-    count[m_auiEoTable[edgeType]] ++;
-
-  }
-  if(pbBorderAvail[SGU_B])
-  {
-    for(x= 1; x< endX; x++)
-    {
-      edgeType = xSign(pRec[x] - pRec[x+ posShift]) + m_iUpBuff1[x] + 2;
-      stats[m_auiEoTable[edgeType]] += (pOrg[x] - pRec[x]);
-      count[m_auiEoTable[edgeType]] ++;
-    }
-  }
-}
-
-/** Calculate SAO statistics for current LCU
- * \param  iAddr,  iPartIdx,  iYCbCr
- */
-Void TEncSampleAdaptiveOffset::calcSaoStatsCu(Int iAddr, Int iPartIdx, Int iYCbCr)
-{
-  if(!m_bUseNIF)
-  {
-    calcSaoStatsCuOrg( iAddr, iPartIdx, iYCbCr);
-  }
-  else
-  {
-    Int64** ppStats = m_iOffsetOrg[iPartIdx];
-    Int64** ppCount = m_iCount    [iPartIdx];
-
-    //parameters
-    Int  isChroma = (iYCbCr != 0)? 1:0;
-    Int  stride   = (iYCbCr != 0)?(m_pcPic->getCStride()):(m_pcPic->getStride());
-    Pel* pPicOrg = getPicYuvAddr (m_pcPic->getPicYuvOrg(), iYCbCr);
-    Pel* pPicRec  = getPicYuvAddr(m_pcYuvTmp, iYCbCr);
-
-    std::vector<NDBFBlockInfo>& vFilterBlocks = *(m_pcPic->getCU(iAddr)->getNDBFilterBlocks());
-
-    //variables
-    UInt  xPos, yPos, width, height;
-    Bool* pbBorderAvail;
-    UInt  posOffset;
-
-    for(Int i=0; i< vFilterBlocks.size(); i++)
-    {
-      xPos        = vFilterBlocks[i].posX   >> isChroma;
-      yPos        = vFilterBlocks[i].posY   >> isChroma;
-      width       = vFilterBlocks[i].width  >> isChroma;
-      height      = vFilterBlocks[i].height >> isChroma;
-      pbBorderAvail = vFilterBlocks[i].isBorderAvailable;
-
-      posOffset = (yPos* stride) + xPos;
-
-      calcSaoStatsBlock(pPicRec+ posOffset, pPicOrg+ posOffset, stride, ppStats, ppCount,width, height, pbBorderAvail, iYCbCr);
-    }
-  }
-
-}
-
-/** Calculate SAO statistics for current LCU without non-crossing slice
- * \param  iAddr,  iPartIdx,  iYCbCr
- */
-Void TEncSampleAdaptiveOffset::calcSaoStatsCuOrg(Int iAddr, Int iPartIdx, Int iYCbCr)
-{
-  Int x,y;
-  TComDataCU *pTmpCu = m_pcPic->getCU(iAddr);
-  TComSPS *pTmpSPS =  m_pcPic->getSlice(0)->getSPS();
-
-  Pel* pOrg;
-  Pel* pRec;
-  Int iStride;
-  Int iLcuHeight = pTmpSPS->getMaxCUHeight();
-  Int iLcuWidth  = pTmpSPS->getMaxCUWidth();
-  UInt uiLPelX   = pTmpCu->getCUPelX();
-  UInt uiTPelY   = pTmpCu->getCUPelY();
-  UInt uiRPelX;
-  UInt uiBPelY;
-  Int64* iStats;
-  Int64* iCount;
-  Int iClassIdx;
-  Int iPicWidthTmp;
-  Int iPicHeightTmp;
-  Int iStartX;
-  Int iStartY;
-  Int iEndX;
-  Int iEndY;
-  Pel* pTableBo = (iYCbCr==0)?m_lumaTableBo:m_chromaTableBo;
-
-  Int iIsChroma = (iYCbCr!=0)? 1:0;
-  Int numSkipLine = iIsChroma? 2:4;
-  if (m_saoLcuBasedOptimization == 0)
-  {
-    numSkipLine = 0;
-  }
-
-  Int numSkipLineRight = iIsChroma? 3:5;
-  if (m_saoLcuBasedOptimization == 0)
-  {
-    numSkipLineRight = 0;
-  }
-
-  iPicWidthTmp  = m_iPicWidth  >> iIsChroma;
-  iPicHeightTmp = m_iPicHeight >> iIsChroma;
-  iLcuWidth     = iLcuWidth    >> iIsChroma;
-  iLcuHeight    = iLcuHeight   >> iIsChroma;
-  uiLPelX       = uiLPelX      >> iIsChroma;
-  uiTPelY       = uiTPelY      >> iIsChroma;
-  uiRPelX       = uiLPelX + iLcuWidth  ;
-  uiBPelY       = uiTPelY + iLcuHeight ;
-  uiRPelX       = uiRPelX > iPicWidthTmp  ? iPicWidthTmp  : uiRPelX;
-  uiBPelY       = uiBPelY > iPicHeightTmp ? iPicHeightTmp : uiBPelY;
-  iLcuWidth     = uiRPelX - uiLPelX;
-  iLcuHeight    = uiBPelY - uiTPelY;
-
-  iStride    =  (iYCbCr == 0)? m_pcPic->getStride(): m_pcPic->getCStride();
-
-//if(iSaoType == BO_0 || iSaoType == BO_1)
-  {
-    if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
-    {
-      numSkipLine = iIsChroma? 1:3;
-      numSkipLineRight = iIsChroma? 2:4;
-    }
-    iStats = m_iOffsetOrg[iPartIdx][SAO_BO];
-    iCount = m_iCount    [iPartIdx][SAO_BO];
-
-    pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
-    pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
-
-    iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth : iLcuWidth-numSkipLineRight;
-    iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight : iLcuHeight-numSkipLine;
-    for (y=0; y<iEndY; y++)
-    {
-      for (x=0; x<iEndX; x++)
-      {
-        iClassIdx = pTableBo[pRec[x]];
-        if (iClassIdx)
-        {
-          iStats[iClassIdx] += (pOrg[x] - pRec[x]); 
-          iCount[iClassIdx] ++;
-        }
-      }
-      pOrg += iStride;
-      pRec += iStride;
-    }
-
-  }
-  Int iSignLeft;
-  Int iSignRight;
-  Int iSignDown;
-  Int iSignDown1;
-  Int iSignDown2;
-
-  UInt uiEdgeType;
-
-//if (iSaoType == EO_0  || iSaoType == EO_1 || iSaoType == EO_2 || iSaoType == EO_3)
-  {
-  //if (iSaoType == EO_0)
-    {
-      if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
-      {
-        numSkipLine = iIsChroma? 1:3;
-        numSkipLineRight = iIsChroma? 3:5;
-      }
-      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_0];
-      iCount = m_iCount    [iPartIdx][SAO_EO_0];
-
-      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
-      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
-
-      iStartX = (uiLPelX == 0) ? 1 : 0;
-      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth-numSkipLineRight;
-      for (y=0; y<iLcuHeight-numSkipLine; y++)
-      {
-        iSignLeft = xSign(pRec[iStartX] - pRec[iStartX-1]);
-        for (x=iStartX; x< iEndX; x++)
-        {
-          iSignRight =  xSign(pRec[x] - pRec[x+1]); 
-          uiEdgeType =  iSignRight + iSignLeft + 2;
-          iSignLeft  = -iSignRight;
-
-          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
-          iCount[m_auiEoTable[uiEdgeType]] ++;
-        }
-        pOrg += iStride;
-        pRec += iStride;
-      }
-    }
-
-  //if (iSaoType == EO_1)
-    {
-      if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
-      {
-        numSkipLine = iIsChroma? 2:4;
-        numSkipLineRight = iIsChroma? 2:4;
-      }
-      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_1];
-      iCount = m_iCount    [iPartIdx][SAO_EO_1];
-
-      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
-      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
-
-      iStartY = (uiTPelY == 0) ? 1 : 0;
-      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth : iLcuWidth-numSkipLineRight;
-      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight-numSkipLine;
-      if (uiTPelY == 0)
-      {
-        pOrg += iStride;
-        pRec += iStride;
-      }
-
-      for (x=0; x< iLcuWidth; x++)
-      {
-        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride]);
-      }
-      for (y=iStartY; y<iEndY; y++)
-      {
-        for (x=0; x<iEndX; x++)
-        {
-          iSignDown     =  xSign(pRec[x] - pRec[x+iStride]); 
-          uiEdgeType    =  iSignDown + m_iUpBuff1[x] + 2;
-          m_iUpBuff1[x] = -iSignDown;
-
-          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
-          iCount[m_auiEoTable[uiEdgeType]] ++;
-        }
-        pOrg += iStride;
-        pRec += iStride;
-      }
-    }
-  //if (iSaoType == EO_2)
-    {
-      if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
-      {
-        numSkipLine = iIsChroma? 2:4;
-        numSkipLineRight = iIsChroma? 3:5;
-      }
-      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_2];
-      iCount = m_iCount    [iPartIdx][SAO_EO_2];
-
-      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
-      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
-
-      iStartX = (uiLPelX == 0) ? 1 : 0;
-      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth-numSkipLineRight;
-
-      iStartY = (uiTPelY == 0) ? 1 : 0;
-      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight-numSkipLine;
-      if (uiTPelY == 0)
-      {
-        pOrg += iStride;
-        pRec += iStride;
-      }
-
-      for (x=iStartX; x<iEndX; x++)
-      {
-        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride-1]);
-      }
-      for (y=iStartY; y<iEndY; y++)
-      {
-        iSignDown2 = xSign(pRec[iStride+iStartX] - pRec[iStartX-1]);
-        for (x=iStartX; x<iEndX; x++)
-        {
-          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride+1]) ;
-          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
-          m_iUpBufft[x+1] = -iSignDown1; 
-          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
-          iCount[m_auiEoTable[uiEdgeType]] ++;
-        }
-        m_iUpBufft[iStartX] = iSignDown2;
-        ipSwap     = m_iUpBuff1;
-        m_iUpBuff1 = m_iUpBufft;
-        m_iUpBufft = ipSwap;
-
-        pRec += iStride;
-        pOrg += iStride;
-      }
-    } 
-  //if (iSaoType == EO_3  )
-    {
-      if( m_saoLcuBasedOptimization && m_saoLcuBoundary )
-      {
-        numSkipLine = iIsChroma? 2:4;
-        numSkipLineRight = iIsChroma? 3:5;
-      }
-      iStats = m_iOffsetOrg[iPartIdx][SAO_EO_3];
-      iCount = m_iCount    [iPartIdx][SAO_EO_3];
-
-      pOrg = getPicYuvAddr(m_pcPic->getPicYuvOrg(), iYCbCr, iAddr);
-      pRec = getPicYuvAddr(m_pcPic->getPicYuvRec(), iYCbCr, iAddr);
-
-      iStartX = (uiLPelX == 0) ? 1 : 0;
-      iEndX   = (uiRPelX == iPicWidthTmp) ? iLcuWidth-1 : iLcuWidth-numSkipLineRight;
-
-      iStartY = (uiTPelY == 0) ? 1 : 0;
-      iEndY   = (uiBPelY == iPicHeightTmp) ? iLcuHeight-1 : iLcuHeight-numSkipLine;
-      if (iStartY == 1)
-      {
-        pOrg += iStride;
-        pRec += iStride;
-      }
-
-      for (x=iStartX-1; x<iEndX; x++)
-      {
-        m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-iStride+1]);
-      }
-
-      for (y=iStartY; y<iEndY; y++)
-      {
-        for (x=iStartX; x<iEndX; x++)
-        {
-          iSignDown1      =  xSign(pRec[x] - pRec[x+iStride-1]) ;
-          uiEdgeType      =  iSignDown1 + m_iUpBuff1[x] + 2;
-          m_iUpBuff1[x-1] = -iSignDown1; 
-          iStats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
-          iCount[m_auiEoTable[uiEdgeType]] ++;
-        }
-        m_iUpBuff1[iEndX-1] = xSign(pRec[iEndX-1 + iStride] - pRec[iEndX]);
-
-        pRec += iStride;
-        pOrg += iStride;
-      } 
-    } 
-  }
-}
-
-
-Void TEncSampleAdaptiveOffset::calcSaoStatsCu_BeforeDblk( TComPic* pcPic )
-{
-  Int addr, yCbCr;
-  Int x,y;
-  TComSPS *pTmpSPS =  pcPic->getSlice(0)->getSPS();
-
-  Pel* pOrg;
-  Pel* pRec;
-  Int stride;
-  Int lcuHeight = pTmpSPS->getMaxCUHeight();
-  Int lcuWidth  = pTmpSPS->getMaxCUWidth();
-  UInt rPelX;
-  UInt bPelY;
-  Int64* stats;
-  Int64* count;
-  Int classIdx;
-  Int picWidthTmp = 0;
-  Int picHeightTmp = 0;
-  Int startX;
-  Int startY;
-  Int endX;
-  Int endY;
-  Int firstX, firstY;
-
-  Int idxY;
-  Int idxX;
-  Int frameHeightInCU = m_iNumCuInHeight;
-  Int frameWidthInCU  = m_iNumCuInWidth;
-  Int j, k;
-
-  Int isChroma;
-  Int numSkipLine, numSkipLineRight;
-
-  UInt lPelX, tPelY;
-  TComDataCU *pTmpCu;
-  Pel* pTableBo;
-
-  for (idxY = 0; idxY< frameHeightInCU; idxY++)
-  {
-    for (idxX = 0; idxX< frameWidthInCU; idxX++)
-    {
-      lcuHeight = pTmpSPS->getMaxCUHeight();
-      lcuWidth  = pTmpSPS->getMaxCUWidth();
-      addr     = idxX  + frameWidthInCU*idxY;
-      pTmpCu = pcPic->getCU(addr);
-      lPelX   = pTmpCu->getCUPelX();
-      tPelY   = pTmpCu->getCUPelY();
-      for( yCbCr = 0; yCbCr < 3; yCbCr++ )
-      {
-        isChroma = (yCbCr!=0)? 1:0;
-
-        for ( j=0;j<MAX_NUM_SAO_TYPE;j++)
-        {
-          for ( k=0;k< MAX_NUM_SAO_CLASS;k++)
-          {
-            m_count_PreDblk    [addr][yCbCr][j][k] = 0;
-            m_offsetOrg_PreDblk[addr][yCbCr][j][k] = 0;
-          }  
-        }
-        if( yCbCr == 0 )
-        {
-          picWidthTmp  = m_iPicWidth;
-          picHeightTmp = m_iPicHeight;
-        }
-        else if( yCbCr == 1 )
-        {
-          picWidthTmp  = m_iPicWidth  >> isChroma;
-          picHeightTmp = m_iPicHeight >> isChroma;
-          lcuWidth     = lcuWidth    >> isChroma;
-          lcuHeight    = lcuHeight   >> isChroma;
-          lPelX       = lPelX      >> isChroma;
-          tPelY       = tPelY      >> isChroma;
-        }
-        rPelX       = lPelX + lcuWidth  ;
-        bPelY       = tPelY + lcuHeight ;
-        rPelX       = rPelX > picWidthTmp  ? picWidthTmp  : rPelX;
-        bPelY       = bPelY > picHeightTmp ? picHeightTmp : bPelY;
-        lcuWidth     = rPelX - lPelX;
-        lcuHeight    = bPelY - tPelY;
-
-        stride    =  (yCbCr == 0)? pcPic->getStride(): pcPic->getCStride();
-        pTableBo = (yCbCr==0)?m_lumaTableBo:m_chromaTableBo;
-
-        //if(iSaoType == BO)
-
-        numSkipLine = isChroma? 1:3;
-        numSkipLineRight = isChroma? 2:4;
-
-        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_BO];
-        count = m_count_PreDblk[addr][yCbCr][SAO_BO];
-
-        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
-        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
-
-        startX   = (rPelX == picWidthTmp) ? lcuWidth : lcuWidth-numSkipLineRight;
-        startY   = (bPelY == picHeightTmp) ? lcuHeight : lcuHeight-numSkipLine;
-
-        for (y=0; y<lcuHeight; y++)
-        {
-          for (x=0; x<lcuWidth; x++)
-          {
-            if( x < startX && y < startY )
-              continue;
-
-            classIdx = pTableBo[pRec[x]];
-            if (classIdx)
-            {
-              stats[classIdx] += (pOrg[x] - pRec[x]); 
-              count[classIdx] ++;
-            }
-          }
-          pOrg += stride;
-          pRec += stride;
-        }
-
-        Int signLeft;
-        Int signRight;
-        Int signDown;
-        Int signDown1;
-        Int signDown2;
-
-        UInt uiEdgeType;
-
-        //if (iSaoType == EO_0)
-
-        numSkipLine = isChroma? 1:3;
-        numSkipLineRight = isChroma? 3:5;
-
-        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_EO_0];
-        count = m_count_PreDblk[addr][yCbCr][SAO_EO_0];
-
-        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
-        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
-
-        startX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth-numSkipLineRight;
-        startY   = (bPelY == picHeightTmp) ? lcuHeight : lcuHeight-numSkipLine;
-        firstX   = (lPelX == 0) ? 1 : 0;
-        endX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth;
-
-        for (y=0; y<lcuHeight; y++)
-        {
-          signLeft = xSign(pRec[firstX] - pRec[firstX-1]);
-          for (x=firstX; x< endX; x++)
-          {
-            signRight =  xSign(pRec[x] - pRec[x+1]); 
-            uiEdgeType =  signRight + signLeft + 2;
-            signLeft  = -signRight;
-
-            if( x < startX && y < startY )
-              continue;
-
-            stats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
-            count[m_auiEoTable[uiEdgeType]] ++;
-          }
-          pOrg += stride;
-          pRec += stride;
-        }
-
-        //if (iSaoType == EO_1)
-
-        numSkipLine = isChroma? 2:4;
-        numSkipLineRight = isChroma? 2:4;
-
-        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_EO_1];
-        count = m_count_PreDblk[addr][yCbCr][SAO_EO_1];
-
-        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
-        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
-
-        startX   = (rPelX == picWidthTmp) ? lcuWidth : lcuWidth-numSkipLineRight;
-        startY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight-numSkipLine;
-        firstY = (tPelY == 0) ? 1 : 0;
-        endY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight;
-        if (firstY == 1)
-        {
-          pOrg += stride;
-          pRec += stride;
-        }
-
-        for (x=0; x< lcuWidth; x++)
-        {
-          m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride]);
-        }
-        for (y=firstY; y<endY; y++)
-        {
-          for (x=0; x<lcuWidth; x++)
-          {
-            signDown     =  xSign(pRec[x] - pRec[x+stride]); 
-            uiEdgeType    =  signDown + m_iUpBuff1[x] + 2;
-            m_iUpBuff1[x] = -signDown;
-
-            if( x < startX && y < startY )
-              continue;
-
-            stats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
-            count[m_auiEoTable[uiEdgeType]] ++;
-          }
-          pOrg += stride;
-          pRec += stride;
-        }
-
-        //if (iSaoType == EO_2)
-
-        numSkipLine = isChroma? 2:4;
-        numSkipLineRight = isChroma? 3:5;
-
-        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_EO_2];
-        count = m_count_PreDblk[addr][yCbCr][SAO_EO_2];
-
-        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
-        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
-
-        startX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth-numSkipLineRight;
-        startY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight-numSkipLine;
-        firstX   = (lPelX == 0) ? 1 : 0;
-        firstY = (tPelY == 0) ? 1 : 0;
-        endX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth;
-        endY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight;
-        if (firstY == 1)
-        {
-          pOrg += stride;
-          pRec += stride;
-        }
-
-        for (x=firstX; x<endX; x++)
-        {
-          m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride-1]);
-        }
-        for (y=firstY; y<endY; y++)
-        {
-          signDown2 = xSign(pRec[stride+startX] - pRec[startX-1]);
-          for (x=firstX; x<endX; x++)
-          {
-            signDown1      =  xSign(pRec[x] - pRec[x+stride+1]) ;
-            uiEdgeType      =  signDown1 + m_iUpBuff1[x] + 2;
-            m_iUpBufft[x+1] = -signDown1; 
-
-            if( x < startX && y < startY )
-              continue;
-
-            stats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
-            count[m_auiEoTable[uiEdgeType]] ++;
-          }
-          m_iUpBufft[firstX] = signDown2;
-          ipSwap     = m_iUpBuff1;
-          m_iUpBuff1 = m_iUpBufft;
-          m_iUpBufft = ipSwap;
-
-          pRec += stride;
-          pOrg += stride;
-        }
-
-        //if (iSaoType == EO_3)
-
-        numSkipLine = isChroma? 2:4;
-        numSkipLineRight = isChroma? 3:5;
-
-        stats = m_offsetOrg_PreDblk[addr][yCbCr][SAO_EO_3];
-        count = m_count_PreDblk[addr][yCbCr][SAO_EO_3];
-
-        pOrg = getPicYuvAddr(pcPic->getPicYuvOrg(), yCbCr, addr);
-        pRec = getPicYuvAddr(pcPic->getPicYuvRec(), yCbCr, addr);
-
-        startX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth-numSkipLineRight;
-        startY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight-numSkipLine;
-        firstX   = (lPelX == 0) ? 1 : 0;
-        firstY = (tPelY == 0) ? 1 : 0;
-        endX   = (rPelX == picWidthTmp) ? lcuWidth-1 : lcuWidth;
-        endY   = (bPelY == picHeightTmp) ? lcuHeight-1 : lcuHeight;
-        if (firstY == 1)
-        {
-          pOrg += stride;
-          pRec += stride;
-        }
-
-        for (x=firstX-1; x<endX; x++)
-        {
-          m_iUpBuff1[x] = xSign(pRec[x] - pRec[x-stride+1]);
-        }
-
-        for (y=firstY; y<endY; y++)
-        {
-          for (x=firstX; x<endX; x++)
-          {
-            signDown1      =  xSign(pRec[x] - pRec[x+stride-1]) ;
-            uiEdgeType      =  signDown1 + m_iUpBuff1[x] + 2;
-            m_iUpBuff1[x-1] = -signDown1; 
-
-            if( x < startX && y < startY )
-              continue;
-
-            stats[m_auiEoTable[uiEdgeType]] += (pOrg[x] - pRec[x]);
-            count[m_auiEoTable[uiEdgeType]] ++;
-          }
-          m_iUpBuff1[endX-1] = xSign(pRec[endX-1 + stride] - pRec[endX]);
-
-          pRec += stride;
-          pOrg += stride;
-        }
-      }
-    }
-  }
-}
-
-
-/** get SAO statistics
- * \param  *psQTPart,  iYCbCr
- */
-Void TEncSampleAdaptiveOffset::getSaoStats(SAOQTPart *psQTPart, Int iYCbCr)
-{
-  Int iLevelIdx, iPartIdx, iTypeIdx, iClassIdx;
-  Int i;
-  Int iNumTotalType = MAX_NUM_SAO_TYPE;
-  Int LcuIdxX;
-  Int LcuIdxY;
-  Int iAddr;
-  Int iFrameWidthInCU = m_pcPic->getFrameWidthInCU();
-  Int iDownPartIdx;
-  Int iPartStart;
-  Int iPartEnd;
-  SAOQTPart*  pOnePart; 
-
-  if (m_uiMaxSplitLevel == 0)
-  {
-    iPartIdx = 0;
-    pOnePart = &(psQTPart[iPartIdx]);
-    for (LcuIdxY = pOnePart->StartCUY; LcuIdxY<= pOnePart->EndCUY; LcuIdxY++)
-    {
-      for (LcuIdxX = pOnePart->StartCUX; LcuIdxX<= pOnePart->EndCUX; LcuIdxX++)
-      {
-        iAddr = LcuIdxY*iFrameWidthInCU + LcuIdxX;
-        calcSaoStatsCu(iAddr, iPartIdx, iYCbCr);
-      }
-    }
-  }
-  else
-  {
-    for(iPartIdx=m_aiNumCulPartsLevel[m_uiMaxSplitLevel-1]; iPartIdx<m_aiNumCulPartsLevel[m_uiMaxSplitLevel]; iPartIdx++)
-    {
-      pOnePart = &(psQTPart[iPartIdx]);
-      for (LcuIdxY = pOnePart->StartCUY; LcuIdxY<= pOnePart->EndCUY; LcuIdxY++)
-      {
-        for (LcuIdxX = pOnePart->StartCUX; LcuIdxX<= pOnePart->EndCUX; LcuIdxX++)
-        {
-          iAddr = LcuIdxY*iFrameWidthInCU + LcuIdxX;
-          calcSaoStatsCu(iAddr, iPartIdx, iYCbCr);
-        }
-      }
-    }
-    for (iLevelIdx = m_uiMaxSplitLevel-1; iLevelIdx>=0; iLevelIdx-- )
-    {
-      iPartStart = (iLevelIdx > 0) ? m_aiNumCulPartsLevel[iLevelIdx-1] : 0;
-      iPartEnd   = m_aiNumCulPartsLevel[iLevelIdx];
-
-      for(iPartIdx = iPartStart; iPartIdx < iPartEnd; iPartIdx++)
-      {
-        pOnePart = &(psQTPart[iPartIdx]);
-        for (i=0; i< NUM_DOWN_PART; i++)
-        {
-          iDownPartIdx = pOnePart->DownPartsIdx[i];
-          for (iTypeIdx=0; iTypeIdx<iNumTotalType; iTypeIdx++)
-          {
-            for (iClassIdx=0; iClassIdx< (iTypeIdx < SAO_BO ? m_iNumClass[iTypeIdx] : SAO_MAX_BO_CLASSES) +1; iClassIdx++)
-            {
-              m_iOffsetOrg[iPartIdx][iTypeIdx][iClassIdx] += m_iOffsetOrg[iDownPartIdx][iTypeIdx][iClassIdx];
-              m_iCount [iPartIdx][iTypeIdx][iClassIdx]    += m_iCount [iDownPartIdx][iTypeIdx][iClassIdx];
-            }
-          }
-        }
-      }
-    }
-  }
-}
-
-/** reset offset statistics 
- * \param 
- */
-Void TEncSampleAdaptiveOffset::resetStats()
-{
-  for (Int i=0;i<m_iNumTotalParts;i++)
-  {
-    m_dCostPartBest[i] = MAX_DOUBLE;
-    m_iTypePartBest[i] = -1;
-    m_iDistOrg[i] = 0;
-    for (Int j=0;j<MAX_NUM_SAO_TYPE;j++)
-    {
-      m_iDist[i][j] = 0;
-      m_iRate[i][j] = 0;
-      m_dCost[i][j] = 0;
-      for (Int k=0;k<MAX_NUM_SAO_CLASS;k++)
-      {
-        m_iCount [i][j][k] = 0;
-        m_iOffset[i][j][k] = 0;
-        m_iOffsetOrg[i][j][k] = 0;
-      }  
-    }
-  }
-}
-
-/** Sample adaptive offset process
- * \param pcSaoParam
- * \param dLambdaLuma
- * \param dLambdaChroma
- */
-#if SAO_ENCODING_CHOICE
-Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambdaLuma, Double dLambdaChroma, Int depth)
-#else
-Void TEncSampleAdaptiveOffset::SAOProcess(SAOParam *pcSaoParam, Double dLambdaLuma, Double dLambdaChroma)
-#endif
-{
-  if(m_bUseNIF)
-  {
-    m_pcPic->getPicYuvRec()->copyToPic(m_pcYuvTmp);
-  }
-
-  m_uiSaoBitIncreaseY = max(g_bitDepthY - 10, 0);
-  m_uiSaoBitIncreaseC = max(g_bitDepthC - 10, 0);
-  m_iOffsetThY = 1 << min(g_bitDepthY - 5, 5);
-  m_iOffsetThC = 1 << min(g_bitDepthC - 5, 5);
-  resetSAOParam(pcSaoParam);
-  if( !m_saoLcuBasedOptimization || !m_saoLcuBoundary )
-  {
-    resetStats();
-  }
-  Double dCostFinal = 0;
-  if ( m_saoLcuBasedOptimization)
-  {
-#if SAO_ENCODING_CHOICE
-    rdoSaoUnitAll(pcSaoParam, dLambdaLuma, dLambdaChroma, depth);
-#else
-    rdoSaoUnitAll(pcSaoParam, dLambdaLuma, dLambdaChroma);
-#endif
-  }
-  else
-  {
-    pcSaoParam->bSaoFlag[0] = 1;
-    pcSaoParam->bSaoFlag[1] = 0;
-    dCostFinal = 0;
-    Double lambdaRdo =  dLambdaLuma;
-    resetStats();
-    getSaoStats(pcSaoParam->psSaoPart[0], 0);
-    runQuadTreeDecision(pcSaoParam->psSaoPart[0], 0, dCostFinal, m_uiMaxSplitLevel, lambdaRdo, 0);
-    pcSaoParam->bSaoFlag[0] = dCostFinal < 0 ? 1:0;
-    if(pcSaoParam->bSaoFlag[0])
-    {
-      convertQT2SaoUnit(pcSaoParam, 0, 0);
-      assignSaoUnitSyntax(pcSaoParam->saoLcuParam[0],  pcSaoParam->psSaoPart[0], pcSaoParam->oneUnitFlag[0], 0);
-    }
-  }
-  if (pcSaoParam->bSaoFlag[0])
-  {
-    processSaoUnitAll( pcSaoParam->saoLcuParam[0], pcSaoParam->oneUnitFlag[0], 0);
-  }
-  if (pcSaoParam->bSaoFlag[1])
-  {
-    processSaoUnitAll( pcSaoParam->saoLcuParam[1], pcSaoParam->oneUnitFlag[1], 1);
-    processSaoUnitAll( pcSaoParam->saoLcuParam[2], pcSaoParam->oneUnitFlag[2], 2);
-  }
-}
-/** Check merge SAO unit
- * \param saoUnitCurr current SAO unit 
- * \param saoUnitCheck SAO unit tobe check
- * \param dir direction
- */
-Void TEncSampleAdaptiveOffset::checkMerge(SaoLcuParam * saoUnitCurr, SaoLcuParam * saoUnitCheck, Int dir)
-{
-  Int i ;
-  Int countDiff = 0;
-  if (saoUnitCurr->partIdx != saoUnitCheck->partIdx)
-  {
-    if (saoUnitCurr->typeIdx !=-1)
-    {
-      if (saoUnitCurr->typeIdx == saoUnitCheck->typeIdx)
-      {
-        for (i=0;i<saoUnitCurr->length;i++)
-        {
-          countDiff += (saoUnitCurr->offset[i] != saoUnitCheck->offset[i]);
-        }
-        countDiff += (saoUnitCurr->subTypeIdx != saoUnitCheck->subTypeIdx);
-        if (countDiff ==0)
-        {
-          saoUnitCurr->partIdx = saoUnitCheck->partIdx;
-          if (dir == 1)
-          {
-            saoUnitCurr->mergeUpFlag = 1;
-            saoUnitCurr->mergeLeftFlag = 0;
-          }
-          else
-          {
-            saoUnitCurr->mergeUpFlag = 0;
-            saoUnitCurr->mergeLeftFlag = 1;
-          }
-        }
-      }
-    }
-    else
-    {
-      if (saoUnitCurr->typeIdx == saoUnitCheck->typeIdx)
-      {
-        saoUnitCurr->partIdx = saoUnitCheck->partIdx;
-        if (dir == 1)
-        {
-          saoUnitCurr->mergeUpFlag = 1;
-          saoUnitCurr->mergeLeftFlag = 0;
-        }
-        else
-        {
-          saoUnitCurr->mergeUpFlag = 0;
-          saoUnitCurr->mergeLeftFlag = 1;
-        }
-      }
-    }
-  }
-}
-/** Assign SAO unit syntax from picture-based algorithm
- * \param saoLcuParam SAO LCU parameters
- * \param saoPart SAO part
- * \param oneUnitFlag SAO one unit flag
- * \param iYCbCr color component Index
- */
-Void TEncSampleAdaptiveOffset::assignSaoUnitSyntax(SaoLcuParam* saoLcuParam,  SAOQTPart* saoPart, Bool &oneUnitFlag, Int yCbCr)
-{
-  if (saoPart->bSplit == 0)
-  {
-    oneUnitFlag = 1;
-  }
-  else
-  {
-    Int i,j, addr, addrUp, addrLeft,  idx, idxUp, idxLeft,  idxCount;
-
-    oneUnitFlag = 0;
-
-    idxCount = -1;
-    saoLcuParam[0].mergeUpFlag = 0;
-    saoLcuParam[0].mergeLeftFlag = 0;
-
-    for (j=0;j<m_iNumCuInHeight;j++)
-    {
-      for (i=0;i<m_iNumCuInWidth;i++)
-      {
-        addr     = i + j*m_iNumCuInWidth;
-        addrLeft = (addr%m_iNumCuInWidth == 0) ? -1 : addr - 1;
-        addrUp   = (addr<m_iNumCuInWidth)      ? -1 : addr - m_iNumCuInWidth;
-        idx      = saoLcuParam[addr].partIdxTmp;
-        idxLeft  = (addrLeft == -1) ? -1 : saoLcuParam[addrLeft].partIdxTmp;
-        idxUp    = (addrUp == -1)   ? -1 : saoLcuParam[addrUp].partIdxTmp;
-
-        if(idx!=idxLeft && idx!=idxUp)
-        {
-          saoLcuParam[addr].mergeUpFlag   = 0; idxCount++;
-          saoLcuParam[addr].mergeLeftFlag = 0;
-          saoLcuParam[addr].partIdx = idxCount;
-        }
-        else if (idx==idxLeft)
-        {
-          saoLcuParam[addr].mergeUpFlag   = 1;
-          saoLcuParam[addr].mergeLeftFlag = 1;
-          saoLcuParam[addr].partIdx = saoLcuParam[addrLeft].partIdx;
-        }
-        else if (idx==idxUp)
-        {
-          saoLcuParam[addr].mergeUpFlag   = 1;
-          saoLcuParam[addr].mergeLeftFlag = 0;
-          saoLcuParam[addr].partIdx = saoLcuParam[addrUp].partIdx;
-        }
-        if (addrUp != -1)
-        {
-          checkMerge(&saoLcuParam[addr], &saoLcuParam[addrUp], 1);
-        }
-        if (addrLeft != -1)
-        {
-          checkMerge(&saoLcuParam[addr], &saoLcuParam[addrLeft], 0);
-        }
-      }
-    }
-  }
-}
-/** rate distortion optimization of all SAO units
- * \param saoParam SAO parameters
- * \param lambda 
- * \param lambdaChroma
- */
-#if SAO_ENCODING_CHOICE
-Void TEncSampleAdaptiveOffset::rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma, Int depth)
-#else
-Void TEncSampleAdaptiveOffset::rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma)
-#endif
-{
-
-  Int idxY;
-  Int idxX;
-  Int frameHeightInCU = saoParam->numCuInHeight;
-  Int frameWidthInCU  = saoParam->numCuInWidth;
-  Int j, k;
-  Int addr = 0;
-  Int addrUp = -1;
-  Int addrLeft = -1;
-  Int compIdx = 0;
-  SaoLcuParam mergeSaoParam[3][2];
-  Double compDistortion[3];
-
-  saoParam->bSaoFlag[0] = true;
-#if AUXILIARY_PICTURES
-  saoParam->bSaoFlag[1] = m_pcPic->getChromaFormat() == CHROMA_400 ? false : true;
-#else
-  saoParam->bSaoFlag[1] = true;
-#endif
-  saoParam->oneUnitFlag[0] = false;
-  saoParam->oneUnitFlag[1] = false;
-  saoParam->oneUnitFlag[2] = false;
-
-#if SAO_ENCODING_CHOICE
-#if SAO_ENCODING_CHOICE_CHROMA
-  Int numNoSao[2];
-  numNoSao[0] = 0;// Luma 
-  numNoSao[1] = 0;// Chroma 
-  if( depth > 0 && m_depthSaoRate[0][depth-1] > SAO_ENCODING_RATE )
-  {
-    saoParam->bSaoFlag[0] = false;
-  }
-  if( depth > 0 && m_depthSaoRate[1][depth-1] > SAO_ENCODING_RATE_CHROMA )
-  {
-    saoParam->bSaoFlag[1] = false;
-  }
-#else
-  Int numNoSao = 0;
-
-  if( depth > 0 && m_depth0SaoRate > SAO_ENCODING_RATE )
-  {
-    saoParam->bSaoFlag[0] = false;
-    saoParam->bSaoFlag[1] = false;
-  }
-#endif
-#endif
-
-  for (idxY = 0; idxY< frameHeightInCU; idxY++)
-  {
-    for (idxX = 0; idxX< frameWidthInCU; idxX++)
-    {
-      addr     = idxX  + frameWidthInCU*idxY;
-      addrUp   = addr < frameWidthInCU ? -1:idxX   + frameWidthInCU*(idxY-1);
-      addrLeft = idxX == 0               ? -1:idxX-1 + frameWidthInCU*idxY;
-      Int allowMergeLeft = 1;
-      Int allowMergeUp   = 1;
-      UInt rate;
-      Double bestCost, mergeCost;
-      if (idxX!=0)
-      { 
-        // check tile id and slice id 
-        if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-1) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-1)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
-        {
-          allowMergeLeft = 0;
-        }
-      }
-      else
-      {
-        allowMergeLeft = 0;
-      }
-      if (idxY!=0)
-      {
-        if ( (m_pcPic->getPicSym()->getTileIdxMap(addr-m_iNumCuInWidth) != m_pcPic->getPicSym()->getTileIdxMap(addr)) || (m_pcPic->getCU(addr-m_iNumCuInWidth)->getSlice()->getSliceIdx() != m_pcPic->getCU(addr)->getSlice()->getSliceIdx()))
-        {
-          allowMergeUp = 0;
-        }
-      }
-      else
-      {
-        allowMergeUp = 0;
-      }
-
-      compDistortion[0] = 0; 
-      compDistortion[1] = 0; 
-      compDistortion[2] = 0;
-      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
-      if (allowMergeLeft)
-      {
-        m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(0); 
-      }
-      if (allowMergeUp)
-      {
-        m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(0);
-      }
-      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_TEMP_BEST] );
-      // reset stats Y, Cb, Cr
-      for ( compIdx=0;compIdx<3;compIdx++)
-      {
-        for ( j=0;j<MAX_NUM_SAO_TYPE;j++)
-        {
-          for ( k=0;k< MAX_NUM_SAO_CLASS;k++)
-          {
-            m_iOffset   [compIdx][j][k] = 0;
-            if( m_saoLcuBasedOptimization && m_saoLcuBoundary ){
-              m_iCount    [compIdx][j][k] = m_count_PreDblk    [addr][compIdx][j][k];
-              m_iOffsetOrg[compIdx][j][k] = m_offsetOrg_PreDblk[addr][compIdx][j][k];
-            }
-            else
-            {
-              m_iCount    [compIdx][j][k] = 0;
-              m_iOffsetOrg[compIdx][j][k] = 0;
-            }
-          }  
-        }
-        saoParam->saoLcuParam[compIdx][addr].typeIdx       =  -1;
-        saoParam->saoLcuParam[compIdx][addr].mergeUpFlag   = 0;
-        saoParam->saoLcuParam[compIdx][addr].mergeLeftFlag = 0;
-        saoParam->saoLcuParam[compIdx][addr].subTypeIdx    = 0;
-#if SAO_ENCODING_CHOICE
-  if( (compIdx ==0 && saoParam->bSaoFlag[0])|| (compIdx >0 && saoParam->bSaoFlag[1]) )
-#endif
-        {
-          calcSaoStatsCu(addr, compIdx,  compIdx);
-
-       }
-      }
-      saoComponentParamDist(allowMergeLeft, allowMergeUp, saoParam, addr, addrUp, addrLeft, 0,  lambda, &mergeSaoParam[0][0], &compDistortion[0]);
-      sao2ChromaParamDist(allowMergeLeft, allowMergeUp, saoParam, addr, addrUp, addrLeft, lambdaChroma, &mergeSaoParam[1][0], &mergeSaoParam[2][0], &compDistortion[0]);
-     if( saoParam->bSaoFlag[0] || saoParam->bSaoFlag[1] )
-      {
-        // Cost of new SAO_params
-        m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
-        m_pcRDGoOnSbacCoder->resetBits();
-        if (allowMergeLeft)
-        {
-          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(0); 
-        }
-        if (allowMergeUp)
-        {
-          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(0);
-        }
-        for ( compIdx=0;compIdx<3;compIdx++)
-        {
-        if( (compIdx ==0 && saoParam->bSaoFlag[0]) || (compIdx >0 && saoParam->bSaoFlag[1]))
-          {
-           m_pcEntropyCoder->encodeSaoOffset(&saoParam->saoLcuParam[compIdx][addr], compIdx);
-          }
-        }
-
-        rate = m_pcEntropyCoder->getNumberOfWrittenBits();
-        bestCost = compDistortion[0] + (Double)rate;
-        m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
-
-        // Cost of Merge
-        for(Int mergeUp=0; mergeUp<2; ++mergeUp)
-        {
-          if ( (allowMergeLeft && (mergeUp==0)) || (allowMergeUp && (mergeUp==1)) )
-          {
-            m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
-            m_pcRDGoOnSbacCoder->resetBits();
-            if (allowMergeLeft)
-            {
-              m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(1-mergeUp); 
-            }
-            if ( allowMergeUp && (mergeUp==1) )
-            {
-              m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(1); 
-            }
-
-            rate = m_pcEntropyCoder->getNumberOfWrittenBits();
-            mergeCost = compDistortion[mergeUp+1] + (Double)rate;
-            if (mergeCost < bestCost)
-            {
-              bestCost = mergeCost;
-              m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);              
-              for ( compIdx=0;compIdx<3;compIdx++)
-              {
-                mergeSaoParam[compIdx][mergeUp].mergeLeftFlag = 1-mergeUp;
-                mergeSaoParam[compIdx][mergeUp].mergeUpFlag = mergeUp;
-                if( (compIdx==0 && saoParam->bSaoFlag[0]) || (compIdx>0 && saoParam->bSaoFlag[1]))
-                {
-                  copySaoUnit(&saoParam->saoLcuParam[compIdx][addr], &mergeSaoParam[compIdx][mergeUp] );             
-                }
-              }
-            }
-          }
-        }
-#if SAO_ENCODING_CHOICE
-#if SAO_ENCODING_CHOICE_CHROMA
-if( saoParam->saoLcuParam[0][addr].typeIdx == -1)
-{
-  numNoSao[0]++;
-}
-if( saoParam->saoLcuParam[1][addr].typeIdx == -1)
-{
-  numNoSao[1]+=2;
-}
-#else
-        for ( compIdx=0;compIdx<3;compIdx++)
-        {
-          if( depth == 0 && saoParam->saoLcuParam[compIdx][addr].typeIdx == -1)
-          {
-            numNoSao++;
-          }
-        }
-#endif
-#endif
-        m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
-        m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
-      }
-    }
-  }
-#if SAO_ENCODING_CHOICE
-#if SAO_ENCODING_CHOICE_CHROMA
-  if( !saoParam->bSaoFlag[0])
-  {
-    m_depthSaoRate[0][depth] = 1.0;
-  }
-  else
-  {
-    m_depthSaoRate[0][depth] = numNoSao[0]/((Double) frameHeightInCU*frameWidthInCU);
-  }
-  if( !saoParam->bSaoFlag[1]) 
-  {
-    m_depthSaoRate[1][depth] = 1.0;
-  }
-  else 
-  {
-    m_depthSaoRate[1][depth] = numNoSao[1]/((Double) frameHeightInCU*frameWidthInCU*2);
-  }
-#else
-  if( depth == 0)
-  {
-    // update SAO Rate
-    m_depth0SaoRate = numNoSao/((Double) frameHeightInCU*frameWidthInCU*3);
-  }
-#endif
-#endif
-
-}
-/** rate distortion optimization of SAO unit 
- * \param saoParam SAO parameters
- * \param addr address 
- * \param addrUp above address
- * \param addrLeft left address 
- * \param yCbCr color component index
- * \param lambda 
- */
-inline Int64 TEncSampleAdaptiveOffset::estSaoTypeDist(Int compIdx, Int typeIdx, Int shift, Double lambda, Int *currentDistortionTableBo, Double *currentRdCostTableBo)
-{
-  Int64 estDist = 0;
-  Int classIdx;
-  Int bitDepth = (compIdx==0) ? g_bitDepthY : g_bitDepthC;
-  Int saoBitIncrease = (compIdx==0) ? m_uiSaoBitIncreaseY : m_uiSaoBitIncreaseC;
-  Int saoOffsetTh = (compIdx==0) ? m_iOffsetThY : m_iOffsetThC;
-
-  for(classIdx=1; classIdx < ( (typeIdx < SAO_BO) ?  m_iNumClass[typeIdx]+1 : SAO_MAX_BO_CLASSES+1); classIdx++)
-  {
-    if( typeIdx == SAO_BO)
-    {
-      currentDistortionTableBo[classIdx-1] = 0;
-      currentRdCostTableBo[classIdx-1] = lambda;
-    }
-    if(m_iCount [compIdx][typeIdx][classIdx])
-    {
-      m_iOffset[compIdx][typeIdx][classIdx] = (Int64) xRoundIbdi(bitDepth, (Double)(m_iOffsetOrg[compIdx][typeIdx][classIdx]<<(bitDepth-8)) / (Double)(m_iCount [compIdx][typeIdx][classIdx]<<saoBitIncrease));
-      m_iOffset[compIdx][typeIdx][classIdx] = Clip3(-saoOffsetTh+1, saoOffsetTh-1, (Int)m_iOffset[compIdx][typeIdx][classIdx]);
-      if (typeIdx < 4)
-      {
-        if ( m_iOffset[compIdx][typeIdx][classIdx]<0 && classIdx<3 )
-        {
-          m_iOffset[compIdx][typeIdx][classIdx] = 0;
-        }
-        if ( m_iOffset[compIdx][typeIdx][classIdx]>0 && classIdx>=3)
-        {
-          m_iOffset[compIdx][typeIdx][classIdx] = 0;
-        }
-      }
-      m_iOffset[compIdx][typeIdx][classIdx] = estIterOffset( typeIdx, classIdx, lambda, m_iOffset[compIdx][typeIdx][classIdx], m_iCount [compIdx][typeIdx][classIdx], m_iOffsetOrg[compIdx][typeIdx][classIdx], shift, saoBitIncrease, currentDistortionTableBo, currentRdCostTableBo, saoOffsetTh );
-    }
-    else
-    {
-      m_iOffsetOrg[compIdx][typeIdx][classIdx] = 0;
-      m_iOffset[compIdx][typeIdx][classIdx] = 0;
-    }
-    if( typeIdx != SAO_BO )
-    {
-      estDist   += estSaoDist( m_iCount [compIdx][typeIdx][classIdx], m_iOffset[compIdx][typeIdx][classIdx] << saoBitIncrease, m_iOffsetOrg[compIdx][typeIdx][classIdx], shift);
-    }
-
-  }
-  return estDist;
-}
-
-inline Int64 TEncSampleAdaptiveOffset::estSaoDist(Int64 count, Int64 offset, Int64 offsetOrg, Int shift)
-{
-  return (( count*offset*offset-offsetOrg*offset*2 ) >> shift);
-}
-inline Int64 TEncSampleAdaptiveOffset::estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int64 offsetInput, Int64 count, Int64 offsetOrg, Int shift, Int bitIncrease, Int *currentDistortionTableBo, Double *currentRdCostTableBo, Int offsetTh )
-{
-  //Clean up, best_q_offset.
-  Int64 iterOffset, tempOffset;
-  Int64 tempDist, tempRate;
-  Double tempCost, tempMinCost;
-  Int64 offsetOutput = 0;
-  iterOffset = offsetInput;
-  // Assuming sending quantized value 0 results in zero offset and sending the value zero needs 1 bit. entropy coder can be used to measure the exact rate here. 
-  tempMinCost = lambda; 
-  while (iterOffset != 0)
-  {
-    // Calculate the bits required for signalling the offset
-    tempRate = (typeIdx == SAO_BO) ? (abs((Int)iterOffset)+2) : (abs((Int)iterOffset)+1);
-    if (abs((Int)iterOffset)==offsetTh-1) 
-    {  
-      tempRate --;
-    }
-    // Do the dequntization before distorion calculation
-    tempOffset  = iterOffset << bitIncrease;
-    tempDist    = estSaoDist( count, tempOffset, offsetOrg, shift);
-    tempCost    = ((Double)tempDist + lambda * (Double) tempRate);
-    if(tempCost < tempMinCost)
-    {
-      tempMinCost = tempCost;
-      offsetOutput = iterOffset;
-      if(typeIdx == SAO_BO)
-      {
-        currentDistortionTableBo[classIdx-1] = (Int) tempDist;
-        currentRdCostTableBo[classIdx-1] = tempCost;
-      }
-    }
-    iterOffset = (iterOffset > 0) ? (iterOffset-1):(iterOffset+1);
-  }
-  return offsetOutput;
-}
-
-
-Void TEncSampleAdaptiveOffset::saoComponentParamDist(Int allowMergeLeft, Int allowMergeUp, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Int yCbCr, Double lambda, SaoLcuParam *compSaoParam, Double *compDistortion)
-{
-  Int typeIdx;
-
-  Int64 estDist;
-  Int classIdx;
-  Int shift = 2 * DISTORTION_PRECISION_ADJUSTMENT(((yCbCr==0)?g_bitDepthY:g_bitDepthC)-8);
-  Int64 bestDist;
-
-  SaoLcuParam*  saoLcuParam = &(saoParam->saoLcuParam[yCbCr][addr]);
-  SaoLcuParam*  saoLcuParamNeighbor = NULL; 
-
-  resetSaoUnit(saoLcuParam);
-  resetSaoUnit(&compSaoParam[0]);
-  resetSaoUnit(&compSaoParam[1]);
-
-
-  Double dCostPartBest = MAX_DOUBLE;
-
-  Double  bestRDCostTableBo = MAX_DOUBLE;
-  Int     bestClassTableBo    = 0;
-  Int     currentDistortionTableBo[MAX_NUM_SAO_CLASS];
-  Double  currentRdCostTableBo[MAX_NUM_SAO_CLASS];
-
-
-  SaoLcuParam   saoLcuParamRdo;   
-  Double   estRate = 0;
-
-  resetSaoUnit(&saoLcuParamRdo);
-
-  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
-  m_pcRDGoOnSbacCoder->resetBits();
- m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo, yCbCr);
-  
-  dCostPartBest = m_pcEntropyCoder->getNumberOfWrittenBits()*lambda ; 
-  copySaoUnit(saoLcuParam, &saoLcuParamRdo );
-  bestDist = 0;
-  
-
-
-  for (typeIdx=0; typeIdx<MAX_NUM_SAO_TYPE; typeIdx++)
-  {
-    estDist = estSaoTypeDist(yCbCr, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
-
-    if( typeIdx == SAO_BO )
-    {
-      // Estimate Best Position
-      Double currentRDCost = 0.0;
-
-      for(Int i=0; i< SAO_MAX_BO_CLASSES -SAO_BO_LEN +1; i++)
-      {
-        currentRDCost = 0.0;
-        for(UInt uj = i; uj < i+SAO_BO_LEN; uj++)
-        {
-          currentRDCost += currentRdCostTableBo[uj];
-        }
-
-        if( currentRDCost < bestRDCostTableBo)
-        {
-          bestRDCostTableBo = currentRDCost;
-          bestClassTableBo  = i;
-        }
-      }
-
-      // Re code all Offsets
-      // Code Center
-      estDist = 0;
-      for(classIdx = bestClassTableBo; classIdx < bestClassTableBo+SAO_BO_LEN; classIdx++)
-      {
-        estDist += currentDistortionTableBo[classIdx];
-      }
-    }
-    resetSaoUnit(&saoLcuParamRdo);
-    saoLcuParamRdo.length = m_iNumClass[typeIdx];
-    saoLcuParamRdo.typeIdx = typeIdx;
-    saoLcuParamRdo.mergeLeftFlag = 0;
-    saoLcuParamRdo.mergeUpFlag   = 0;
-    saoLcuParamRdo.subTypeIdx = (typeIdx == SAO_BO) ? bestClassTableBo : 0;
-    for (classIdx = 0; classIdx < saoLcuParamRdo.length; classIdx++)
-    {
-      saoLcuParamRdo.offset[classIdx] = (Int)m_iOffset[yCbCr][typeIdx][classIdx+saoLcuParamRdo.subTypeIdx+1];
-    }
-    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
-    m_pcRDGoOnSbacCoder->resetBits();
-    m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo, yCbCr);
-
-    estRate = m_pcEntropyCoder->getNumberOfWrittenBits();
-    m_dCost[yCbCr][typeIdx] = (Double)((Double)estDist + lambda * (Double) estRate);
-
-    if(m_dCost[yCbCr][typeIdx] < dCostPartBest)
-    {
-      dCostPartBest = m_dCost[yCbCr][typeIdx];
-      copySaoUnit(saoLcuParam, &saoLcuParamRdo );
-      bestDist = estDist;       
-    }
-  }
-  compDistortion[0] += ((Double)bestDist/lambda);
-  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
- m_pcEntropyCoder->encodeSaoOffset(saoLcuParam, yCbCr);
-  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_TEMP_BEST] );
-
-
-  // merge left or merge up
-
-  for (Int idxNeighbor=0;idxNeighbor<2;idxNeighbor++) 
-  {
-    saoLcuParamNeighbor = NULL;
-    if (allowMergeLeft && addrLeft>=0 && idxNeighbor ==0)
-    {
-      saoLcuParamNeighbor = &(saoParam->saoLcuParam[yCbCr][addrLeft]);
-    }
-    else if (allowMergeUp && addrUp>=0 && idxNeighbor ==1)
-    {
-      saoLcuParamNeighbor = &(saoParam->saoLcuParam[yCbCr][addrUp]);
-    }
-    if (saoLcuParamNeighbor!=NULL)
-    {
-      estDist = 0;
-      typeIdx = saoLcuParamNeighbor->typeIdx;
-      if (typeIdx>=0) 
-      {
-        Int mergeBandPosition = (typeIdx == SAO_BO)?saoLcuParamNeighbor->subTypeIdx:0;
-        Int   merge_iOffset;
-        for(classIdx = 0; classIdx < m_iNumClass[typeIdx]; classIdx++)
-        {
-          merge_iOffset = saoLcuParamNeighbor->offset[classIdx];
-          estDist   += estSaoDist(m_iCount [yCbCr][typeIdx][classIdx+mergeBandPosition+1], merge_iOffset, m_iOffsetOrg[yCbCr][typeIdx][classIdx+mergeBandPosition+1],  shift);
-        }
-      }
-      else
-      {
-        estDist = 0;
-      }
-
-      copySaoUnit(&compSaoParam[idxNeighbor], saoLcuParamNeighbor );
-      compSaoParam[idxNeighbor].mergeUpFlag   = idxNeighbor;
-      compSaoParam[idxNeighbor].mergeLeftFlag = !idxNeighbor;
-
-      compDistortion[idxNeighbor+1] += ((Double)estDist/lambda);
-    } 
-  } 
-}
-Void TEncSampleAdaptiveOffset::sao2ChromaParamDist(Int allowMergeLeft, Int allowMergeUp, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Double lambda, SaoLcuParam *crSaoParam, SaoLcuParam *cbSaoParam, Double *distortion)
-{
-  Int typeIdx;
-
-  Int64 estDist[2];
-  Int classIdx;
-  Int shift = 2 * DISTORTION_PRECISION_ADJUSTMENT(g_bitDepthC-8);
-  Int64 bestDist = 0;
-
-  SaoLcuParam*  saoLcuParam[2] = {&(saoParam->saoLcuParam[1][addr]), &(saoParam->saoLcuParam[2][addr])};
-  SaoLcuParam*  saoLcuParamNeighbor[2] = {NULL, NULL}; 
-  SaoLcuParam*  saoMergeParam[2][2];
-  saoMergeParam[0][0] = &crSaoParam[0];
-  saoMergeParam[0][1] = &crSaoParam[1]; 
-  saoMergeParam[1][0] = &cbSaoParam[0];
-  saoMergeParam[1][1] = &cbSaoParam[1];
-
-  resetSaoUnit(saoLcuParam[0]);
-  resetSaoUnit(saoLcuParam[1]);
-  resetSaoUnit(saoMergeParam[0][0]);
-  resetSaoUnit(saoMergeParam[0][1]);
-  resetSaoUnit(saoMergeParam[1][0]);
-  resetSaoUnit(saoMergeParam[1][1]);
-
-
-  Double costPartBest = MAX_DOUBLE;
-
-  Double  bestRDCostTableBo;
-  Int     bestClassTableBo[2]    = {0, 0};
-  Int     currentDistortionTableBo[MAX_NUM_SAO_CLASS];
-  Double  currentRdCostTableBo[MAX_NUM_SAO_CLASS];
-
-  SaoLcuParam   saoLcuParamRdo[2];   
-  Double   estRate = 0;
-
-  resetSaoUnit(&saoLcuParamRdo[0]);
-  resetSaoUnit(&saoLcuParamRdo[1]);
-
-  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
-  m_pcRDGoOnSbacCoder->resetBits();
-  m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo[0], 1);
-  m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo[1], 2);
-  
-  costPartBest = m_pcEntropyCoder->getNumberOfWrittenBits()*lambda ; 
-  copySaoUnit(saoLcuParam[0], &saoLcuParamRdo[0] );
-  copySaoUnit(saoLcuParam[1], &saoLcuParamRdo[1] );
-
-  for (typeIdx=0; typeIdx<MAX_NUM_SAO_TYPE; typeIdx++)
-  {
-    if( typeIdx == SAO_BO )
-    {
-      // Estimate Best Position
-      for(Int compIdx = 0; compIdx < 2; compIdx++)
-      {
-        Double currentRDCost = 0.0;
-        bestRDCostTableBo = MAX_DOUBLE;
-        estDist[compIdx] = estSaoTypeDist(compIdx+1, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
-        for(Int i=0; i< SAO_MAX_BO_CLASSES -SAO_BO_LEN +1; i++)
-        {
-          currentRDCost = 0.0;
-          for(UInt uj = i; uj < i+SAO_BO_LEN; uj++)
-          {
-            currentRDCost += currentRdCostTableBo[uj];
-          }
-
-          if( currentRDCost < bestRDCostTableBo)
-          {
-            bestRDCostTableBo = currentRDCost;
-            bestClassTableBo[compIdx]  = i;
-          }
-        }
-
-        // Re code all Offsets
-        // Code Center
-        estDist[compIdx] = 0;
-        for(classIdx = bestClassTableBo[compIdx]; classIdx < bestClassTableBo[compIdx]+SAO_BO_LEN; classIdx++)
-        {
-          estDist[compIdx] += currentDistortionTableBo[classIdx];
-        }
-      }
-    }
-    else
-    {
-      estDist[0] = estSaoTypeDist(1, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
-      estDist[1] = estSaoTypeDist(2, typeIdx, shift, lambda, currentDistortionTableBo, currentRdCostTableBo);
-    }
-
-    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
-    m_pcRDGoOnSbacCoder->resetBits();
-
-    for(Int compIdx = 0; compIdx < 2; compIdx++)
-    {
-      resetSaoUnit(&saoLcuParamRdo[compIdx]);
-      saoLcuParamRdo[compIdx].length = m_iNumClass[typeIdx];
-      saoLcuParamRdo[compIdx].typeIdx = typeIdx;
-      saoLcuParamRdo[compIdx].mergeLeftFlag = 0;
-      saoLcuParamRdo[compIdx].mergeUpFlag   = 0;
-      saoLcuParamRdo[compIdx].subTypeIdx = (typeIdx == SAO_BO) ? bestClassTableBo[compIdx] : 0;
-      for (classIdx = 0; classIdx < saoLcuParamRdo[compIdx].length; classIdx++)
-      {
-        saoLcuParamRdo[compIdx].offset[classIdx] = (Int)m_iOffset[compIdx+1][typeIdx][classIdx+saoLcuParamRdo[compIdx].subTypeIdx+1];
-      }
-
-      m_pcEntropyCoder->encodeSaoOffset(&saoLcuParamRdo[compIdx], compIdx+1);
-    }
-    estRate = m_pcEntropyCoder->getNumberOfWrittenBits();
-    m_dCost[1][typeIdx] = (Double)((Double)(estDist[0] + estDist[1])  + lambda * (Double) estRate);
-    
-    if(m_dCost[1][typeIdx] < costPartBest)
-    {
-      costPartBest = m_dCost[1][typeIdx];
-      copySaoUnit(saoLcuParam[0], &saoLcuParamRdo[0] );
-      copySaoUnit(saoLcuParam[1], &saoLcuParamRdo[1] );
-      bestDist = (estDist[0]+estDist[1]);       
-    }
-  }
-
-  distortion[0] += ((Double)bestDist/lambda);
-  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[0][CI_TEMP_BEST]);
-  m_pcEntropyCoder->encodeSaoOffset(saoLcuParam[0], 1);
-  m_pcEntropyCoder->encodeSaoOffset(saoLcuParam[1], 2);
-  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[0][CI_TEMP_BEST] );
-
-  // merge left or merge up
-
-  for (Int idxNeighbor=0;idxNeighbor<2;idxNeighbor++) 
-  {
-    for(Int compIdx = 0; compIdx < 2; compIdx++)
-    {
-      saoLcuParamNeighbor[compIdx] = NULL;
-      if (allowMergeLeft && addrLeft>=0 && idxNeighbor ==0)
-      {
-        saoLcuParamNeighbor[compIdx] = &(saoParam->saoLcuParam[compIdx+1][addrLeft]);
-      }
-      else if (allowMergeUp && addrUp>=0 && idxNeighbor ==1)
-      {
-        saoLcuParamNeighbor[compIdx] = &(saoParam->saoLcuParam[compIdx+1][addrUp]);
-      }
-      if (saoLcuParamNeighbor[compIdx]!=NULL)
-      {
-        estDist[compIdx] = 0;
-        typeIdx = saoLcuParamNeighbor[compIdx]->typeIdx;
-        if (typeIdx>=0) 
-        {
-          Int mergeBandPosition = (typeIdx == SAO_BO)?saoLcuParamNeighbor[compIdx]->subTypeIdx:0;
-          Int   merge_iOffset;
-          for(classIdx = 0; classIdx < m_iNumClass[typeIdx]; classIdx++)
-          {
-            merge_iOffset = saoLcuParamNeighbor[compIdx]->offset[classIdx];
-            estDist[compIdx]   += estSaoDist(m_iCount [compIdx+1][typeIdx][classIdx+mergeBandPosition+1], merge_iOffset, m_iOffsetOrg[compIdx+1][typeIdx][classIdx+mergeBandPosition+1],  shift);
-          }
-        }
-        else
-        {
-          estDist[compIdx] = 0;
-        }
-
-        copySaoUnit(saoMergeParam[compIdx][idxNeighbor], saoLcuParamNeighbor[compIdx] );
-        saoMergeParam[compIdx][idxNeighbor]->mergeUpFlag   = idxNeighbor;
-        saoMergeParam[compIdx][idxNeighbor]->mergeLeftFlag = !idxNeighbor;
-        distortion[idxNeighbor+1] += ((Double)estDist[compIdx]/lambda);
-      }
-    } 
-  } 
-}
-
-#endif
-
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -54,5 +54,4 @@
 // ====================================================================================================================
 
-#if HM_CLEANUP_SAO
 enum SAOCabacStateLablesRDO //CABAC state labels
 {
@@ -146,5 +145,5 @@
   TEncSbac*              m_pcRDGoOnSbacCoder;
   TEncBinCABACCounter**  m_pppcBinCoderCABAC;    
-  Double                 m_labmda[NUM_SAO_COMPONENTS];
+  Double                 m_lambda[NUM_SAO_COMPONENTS];
 
   //statistics
@@ -159,81 +158,4 @@
   Int                    m_skipLinesB[NUM_SAO_COMPONENTS][NUM_SAO_NEW_TYPES];
 };
-#else
-
-
-class TEncSampleAdaptiveOffset : public TComSampleAdaptiveOffset
-{
-private:
-  TEncEntropy*      m_pcEntropyCoder;
-  TEncSbac***       m_pppcRDSbacCoder;              ///< for CABAC
-  TEncSbac*         m_pcRDGoOnSbacCoder;
-#if FAST_BIT_EST
-  TEncBinCABACCounter*** m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
-#else
-  TEncBinCABAC***   m_pppcBinCoderCABAC;            ///< temporal CABAC state storage for RD computation
-#endif
-  
-  Int64  ***m_iCount;      //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
-  Int64  ***m_iOffset;     //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
-  Int64  ***m_iOffsetOrg;  //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
-  Int64  ****m_count_PreDblk;      //[LCU][YCbCr][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
-  Int64  ****m_offsetOrg_PreDblk;  //[LCU][YCbCr][MAX_NUM_SAO_TYPE][MAX_NUM_SAO_CLASS]; 
-  Int64  **m_iRate;        //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
-  Int64  **m_iDist;        //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
-  Double **m_dCost;        //[MAX_NUM_SAO_PART][MAX_NUM_SAO_TYPE]; 
-  Double *m_dCostPartBest; //[MAX_NUM_SAO_PART]; 
-  Int64  *m_iDistOrg;      //[MAX_NUM_SAO_PART]; 
-  Int    *m_iTypePartBest; //[MAX_NUM_SAO_PART]; 
-  Int     m_iOffsetThY;
-  Int     m_iOffsetThC;
-  Bool    m_bUseSBACRD;
-#if SAO_ENCODING_CHOICE
-#if SAO_ENCODING_CHOICE_CHROMA
-  Double  m_depthSaoRate[2][4];
-#else
-  Double  m_depth0SaoRate;
-#endif
-#endif
-
-public:
-  TEncSampleAdaptiveOffset         ();
-  virtual ~TEncSampleAdaptiveOffset();
-
-  Void startSaoEnc( TComPic* pcPic, TEncEntropy* pcEntropyCoder, TEncSbac*** pppcRDSbacCoder, TEncSbac* pcRDGoOnSbacCoder);
-  Void endSaoEnc();
-  Void resetStats();
-#if SAO_ENCODING_CHOICE
-  Void SAOProcess(SAOParam *pcSaoParam, Double dLambda, Double dLambdaChroma, Int depth);
-#else
-  Void SAOProcess(SAOParam *pcSaoParam, Double dLambda, Double dLambdaChroma);
-#endif
-
-  Void runQuadTreeDecision(SAOQTPart *psQTPart, Int iPartIdx, Double &dCostFinal, Int iMaxLevel, Double dLambda, Int yCbCr);
-  Void rdoSaoOnePart(SAOQTPart *psQTPart, Int iPartIdx, Double dLambda, Int yCbCr);
-  
-  Void disablePartTree(SAOQTPart *psQTPart, Int iPartIdx);
-  Void getSaoStats(SAOQTPart *psQTPart, Int iYCbCr);
-  Void calcSaoStatsCu(Int iAddr, Int iPartIdx, Int iYCbCr);
-  Void calcSaoStatsBlock( Pel* pRecStart, Pel* pOrgStart, Int stride, Int64** ppStats, Int64** ppCount, UInt width, UInt height, Bool* pbBorderAvail, Int iYCbCr);
-  Void calcSaoStatsCuOrg(Int iAddr, Int iPartIdx, Int iYCbCr);
-  Void calcSaoStatsCu_BeforeDblk( TComPic* pcPic );
-  Void destroyEncBuffer();
-  Void createEncBuffer();
-  Void assignSaoUnitSyntax(SaoLcuParam* saoLcuParam,  SAOQTPart* saoPart, Bool &oneUnitFlag, Int yCbCr);
-  Void checkMerge(SaoLcuParam * lcuParamCurr,SaoLcuParam * lcuParamCheck, Int dir);
-#if SAO_ENCODING_CHOICE
-  Void rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma, Int depth);
-#else
-  Void rdoSaoUnitAll(SAOParam *saoParam, Double lambda, Double lambdaChroma);
-#endif
-  Void saoComponentParamDist(Int allowMergeLeft, Int allowMergeUp, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Int yCbCr, Double lambda, SaoLcuParam *compSaoParam, Double *distortion);
-  Void sao2ChromaParamDist(Int allowMergeLeft, Int allowMergeUp, SAOParam *saoParam, Int addr, Int addrUp, Int addrLeft, Double lambda, SaoLcuParam *crSaoParam, SaoLcuParam *cbSaoParam, Double *distortion);
-  inline Int64 estSaoDist(Int64 count, Int64 offset, Int64 offsetOrg, Int shift);
-  inline Int64 estIterOffset(Int typeIdx, Int classIdx, Double lambda, Int64 offsetInput, Int64 count, Int64 offsetOrg, Int shift, Int bitIncrease, Int *currentDistortionTableBo, Double *currentRdCostTableBo, Int offsetTh );
-  inline Int64 estSaoTypeDist(Int compIdx, Int typeIdx, Int shift, Double lambda, Int *currentDistortionTableBo, Double *currentRdCostTableBo);
-  Void setMaxNumOffsetsPerPic(Int iVal) {m_maxNumOffsetsPerPic = iVal; }
-  Int  getMaxNumOffsetsPerPic() {return m_maxNumOffsetsPerPic; }
-};
-#endif
 //! \}
 
Index: trunk/source/Lib/TLibEncoder/TEncSbac.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -78,5 +78,4 @@
 , m_cCUAbsSCModel             ( 1,             1,               NUM_ABS_FLAG_CTX              , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cMVPIdxSCModel            ( 1,             1,               NUM_MVP_IDX_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
-, m_cCUAMPSCModel             ( 1,             1,               NUM_CU_AMP_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cSaoMergeSCModel          ( 1,             1,               NUM_SAO_MERGE_FLAG_CTX   , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cSaoTypeIdxSCModel        ( 1,             1,               NUM_SAO_TYPE_IDX_CTX          , m_contextModels + m_numContextModels, m_numContextModels)
@@ -112,5 +111,4 @@
   m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT);
   m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
-  m_cCUAMPSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CU_AMP_POS );
   m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
   m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
@@ -166,5 +164,4 @@
       curCost += m_cCUMergeIdxExtSCModel.calcCost     ( curSliceType, qp, (UChar*)INIT_MERGE_IDX_EXT);
       curCost += m_cCUPartSizeSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_PART_SIZE );
-      curCost += m_cCUAMPSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_CU_AMP_POS );
       curCost += m_cCUPredModeSCModel.calcCost        ( curSliceType, qp, (UChar*)INIT_PRED_MODE );
       curCost += m_cCUIntraPredSCModel.calcCost       ( curSliceType, qp, (UChar*)INIT_INTRA_PRED_MODE );
@@ -215,5 +212,4 @@
   m_cCUMergeIdxExtSCModel.initBuffer     ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT);
   m_cCUPartSizeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PART_SIZE );
-  m_cCUAMPSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_CU_AMP_POS );
   m_cCUPredModeSCModel.initBuffer        ( eSliceType, iQp, (UChar*)INIT_PRED_MODE );
   m_cCUIntraPredSCModel.initBuffer       ( eSliceType, iQp, (UChar*)INIT_INTRA_PRED_MODE );
@@ -442,9 +438,9 @@
         if (eSize == SIZE_2NxN)
         {
-          m_pcBinIf->encodeBin(1, m_cCUAMPSCModel.get( 0, 0, 0 ));
+          m_pcBinIf->encodeBin(1, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
         }
         else
         {
-          m_pcBinIf->encodeBin(0, m_cCUAMPSCModel.get( 0, 0, 0 ));          
+          m_pcBinIf->encodeBin(0, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
           m_pcBinIf->encodeBinEP((eSize == SIZE_2NxnU? 0: 1));
         }
@@ -466,9 +462,9 @@
         if (eSize == SIZE_Nx2N)
         {
-          m_pcBinIf->encodeBin(1, m_cCUAMPSCModel.get( 0, 0, 0 ));
+          m_pcBinIf->encodeBin(1, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
         }
         else
         {
-          m_pcBinIf->encodeBin(0, m_cCUAMPSCModel.get( 0, 0, 0 ));
+          m_pcBinIf->encodeBin(0, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
           m_pcBinIf->encodeBinEP((eSize == SIZE_nLx2N? 0: 1));
         }
@@ -1393,9 +1389,5 @@
   {
     m_pcBinIf->encodeBin( 1, m_cSaoTypeIdxSCModel.get( 0, 0, 0 ) );
-#if HM_CLEANUP_SAO
     m_pcBinIf->encodeBinEP( uiCode == 1 ? 0 : 1 );
-#else
-    m_pcBinIf->encodeBinEP( uiCode <= 4 ? 1 : 0 );
-#endif
   }
 }
@@ -1600,5 +1592,4 @@
 }
 
-#if HM_CLEANUP_SAO
 Void TEncSbac::codeSAOOffsetParam(Int compIdx, SAOOffset& ctbParam, Bool sliceEnabled)
 {
@@ -1713,5 +1704,4 @@
   }
 }
-#endif
 
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncSbac.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSbac.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncSbac.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -104,5 +104,4 @@
   Void  codeScalingList      ( TComScalingList* /*scalingList*/     ){ assert (0);  return;};
 
-#if HM_CLEANUP_SAO
   Void codeSAOOffsetParam(Int compIdx, SAOOffset& ctbParam, Bool sliceEnabled);
   Void codeSAOBlkParam(SAOBlkParam& saoBlkParam
@@ -112,5 +111,4 @@
                     , Bool onlyEstMergeInfo = false
                     );
-#endif
 
 private:
@@ -208,5 +206,4 @@
   ContextModel3DBuffer m_cMVPIdxSCModel;
   
-  ContextModel3DBuffer m_cCUAMPSCModel;
   ContextModel3DBuffer m_cSaoMergeSCModel;
   ContextModel3DBuffer m_cSaoTypeIdxSCModel;
Index: trunk/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -199,6 +199,4 @@
   m_pppcRDSbacCoder     = pppcRDSbacCoder;
   m_pcRDGoOnSbacCoder   = pcRDGoOnSbacCoder;
-  
-  m_bUseSBACRD          = pppcRDSbacCoder ? true : false;
   
   for (Int iDir = 0; iDir < 2; iDir++)
@@ -1125,5 +1123,5 @@
   {
     Int scalingListType = 0 + g_eTTable[(Int)TEXT_LUMA];
-    assert(scalingListType < 6);
+    assert(scalingListType < SCALING_LIST_NUM);
     m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,pcCU->getLumaIntraDir( uiAbsPartIdx ), piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkip );
   }
@@ -1318,5 +1316,5 @@
     {
       Int scalingListType = 0 + g_eTTable[(Int)eText];
-      assert(scalingListType < 6);
+      assert(scalingListType < SCALING_LIST_NUM);
       m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA, REG_DCT, piResi, uiStride, pcCoeff, uiWidth, uiHeight, scalingListType, useTransformSkipChroma );
     }
@@ -1424,5 +1422,4 @@
   checkTransformSkip         &= (widthTransformSkip == 4 && heightTransformSkip == 4);
   checkTransformSkip         &= (!pcCU->getCUTransquantBypass(0));
-  checkTransformSkip         &= (!((pcCU->getQP( 0 ) == 0) && (pcCU->getSlice()->getSPS()->getUseLossless())));
   if ( m_pcEncCfg->getUseTransformSkipFast() )
   {
@@ -1434,8 +1431,6 @@
     {
       //----- store original entropy coding status -----
-      if( m_bUseSBACRD)
-      {
-        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
-      }
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+
       UInt   singleDistYTmp     = 0;
       UInt   singleDistCTmp     = 0;
@@ -1503,8 +1498,5 @@
           {
             xStoreIntraResultQT(pcCU, uiTrDepth, uiAbsPartIdx,bLumaOnly );
-            if( m_bUseSBACRD) 
-            {
-              m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
-            }
+            m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
           }
         }
@@ -1529,9 +1521,6 @@
           }
         }
-        if(m_bUseSBACRD)
-        {
-          m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
-        } 
-      }
+        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+      } 
 
       if( !bLumaOnly )
@@ -1558,5 +1547,5 @@
       pcCU ->setTransformSkipSubParts ( 0, TEXT_LUMA, uiAbsPartIdx, uiFullDepth ); 
       //----- store original entropy coding status -----
-      if( m_bUseSBACRD && bCheckSplit )
+      if( bCheckSplit )
       {
         m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
@@ -1595,16 +1584,14 @@
   {
     //----- store full entropy coding status, load original entropy coding status -----
-    if( m_bUseSBACRD )
-    {
-      if( bCheckFull )
-      {
-        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_TEST ] );
-        m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
-      }
-      else
-      {
-        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
-      }
-    }
+    if( bCheckFull )
+    {
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_TEST ] );
+      m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+    }
+    else
+    {
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+    }
+
     //----- code splitted block -----
     Double  dSplitCost      = 0.0;
@@ -1647,8 +1634,6 @@
     }
     //----- restore context states -----
-    if( m_bUseSBACRD )
-    {
-      m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
-    }
+    m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+
     //----- determine rate and r-d cost -----
     UInt uiSplitBits = xGetIntraBitsQT( pcCU, uiTrDepth, uiAbsPartIdx, true, !bLumaOnly, false );
@@ -1665,9 +1650,6 @@
     }
     //----- set entropy coding status -----
-    if( m_bUseSBACRD )
-    {
-      m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_TEST ] );
-    }
-    
+    m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_TEST ] );
+
     //--- set transform index and Cbf values ---
     pcCU->setTrIdxSubParts( uiTrDepth, uiAbsPartIdx, uiFullDepth );
@@ -2194,8 +2176,5 @@
     {
         //use RDO to decide whether Cr/Cb takes TS
-        if( m_bUseSBACRD )
-        {
-          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[uiFullDepth][CI_QT_TRAFO_ROOT] );
-        }
+        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[uiFullDepth][CI_QT_TRAFO_ROOT] );
 
         for(Int chromaId = 0; chromaId < 2; chromaId ++)
@@ -2239,45 +2218,36 @@
 
             if(singleCostTmp < dSingleCost)
+          {
+            dSingleCost = singleCostTmp;
+            singleDistC = singleDistCTmp;
+            bestModeId  = chromaModeId;
+            singleCbfC  = singleCbfCTmp;
+            
+            if(bestModeId == firstCheckId)
             {
-              dSingleCost = singleCostTmp;
-              singleDistC = singleDistCTmp;
-              bestModeId  = chromaModeId;
-              singleCbfC  = singleCbfCTmp;
-
-              if(bestModeId == firstCheckId)
-              {
-                xStoreIntraResultChromaQT(pcCU, uiTrDepth, uiAbsPartIdx,chromaId);
-                if( m_bUseSBACRD) 
-                {
-                  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
-                }
-              }
-            }
-            if(chromaModeId == firstCheckId)
-            {
-              m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
+              xStoreIntraResultChromaQT(pcCU, uiTrDepth, uiAbsPartIdx,chromaId);
+              m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
             }
           }
-
-          if(bestModeId == firstCheckId)
+          if(chromaModeId == firstCheckId)
           {
-            xLoadIntraResultChromaQT(pcCU, uiTrDepth, uiAbsPartIdx,chromaId);
-            pcCU->setCbfSubParts ( singleCbfC << uiTrDepth, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth(0) + actualTrDepth );
-            if(m_bUseSBACRD)
-            {
-              m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
-            } 
+            m_pcRDGoOnSbacCoder->load ( m_pppcRDSbacCoder[ uiFullDepth ][ CI_QT_TRAFO_ROOT ] );
           }
-          pcCU ->setTransformSkipSubParts( bestModeId, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth ); 
-          ruiDist += singleDistC;
-
-          if(chromaId == 0)
-          {
-            if( m_bUseSBACRD )
-            {
-              m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[uiFullDepth][CI_QT_TRAFO_ROOT] );
-            }
-          }
-        }
+        }
+        
+        if(bestModeId == firstCheckId)
+        {
+          xLoadIntraResultChromaQT(pcCU, uiTrDepth, uiAbsPartIdx,chromaId);
+          pcCU->setCbfSubParts ( singleCbfC << uiTrDepth, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth(0) + actualTrDepth );
+          m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiFullDepth ][ CI_TEMP_BEST ] );
+        }
+        pcCU ->setTransformSkipSubParts( bestModeId, (TextType)(chromaId + 2), uiAbsPartIdx, pcCU->getDepth( 0 ) +  actualTrDepth );
+        ruiDist += singleDistC;
+        
+        if(chromaId == 0)
+        {
+          m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[uiFullDepth][CI_QT_TRAFO_ROOT] );
+        }
+      }
     }
     else
@@ -2575,8 +2545,5 @@
       
       // set context models
-      if( m_bUseSBACRD )
-      {
-        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
-      }
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
       
       // determine residual for partition
@@ -2640,8 +2607,5 @@
       
       // set context models
-      if( m_bUseSBACRD )
-      {
-        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
-      }
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
       
       // determine residual for partition
@@ -2770,8 +2734,5 @@
   
   //===== reset context models =====
-  if(m_bUseSBACRD)
-  {
-    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
-  }
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
   
   //===== set distortion (rate and r-d costs are determined later) =====
@@ -2805,8 +2766,5 @@
   {
     //----- restore context models -----
-    if( m_bUseSBACRD )
-    {
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
-    }
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
     
     //----- chroma coding -----
@@ -2814,5 +2772,5 @@
     pcCU->setChromIntraDirSubParts  ( uiModeList[uiMode], 0, uiDepth );
     xRecurIntraChromaCodingQT       ( pcCU,   0, 0, pcOrgYuv, pcPredYuv, pcResiYuv, uiDist );
-    if( m_bUseSBACRD && pcCU->getSlice()->getPPS()->getUseTransformSkip() )
+    if( pcCU->getSlice()->getPPS()->getUseTransformSkip() )
     {
       m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
@@ -2846,8 +2804,5 @@
   
   //----- restore context models -----
-  if( m_bUseSBACRD )
-  {
-    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
-  }
+  m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
 }
 
@@ -3005,8 +2960,5 @@
   dCost = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
 
-  if(m_bUseSBACRD)
-  {
-    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
-  }
+  m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST]);
 
   pcCU->getTotalBits()       = uiBits;
@@ -4574,8 +4526,5 @@
     + m_pcRdCost->getDistPart(g_bitDepthC, rpcYuvRec->getCrAddr(),   rpcYuvRec->getCStride(), pcYuvOrg->getCrAddr(),   pcYuvOrg->getCStride(), uiWidth >> 1, uiHeight >> 1, TEXT_CHROMA_V );
 
-    if( m_bUseSBACRD )
-    {
-      m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST]);
-    }
+    m_pcRDGoOnSbacCoder->load(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST]);
     
     m_pcEntropyCoder->resetBits();
@@ -4592,8 +4541,5 @@
     pcCU->getTotalCost()       = m_pcRdCost->calcRdCost( uiBits, uiDistortion );
     
-    if( m_bUseSBACRD )
-    {
-      m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_TEMP_BEST]);
-    }
+    m_pcRDGoOnSbacCoder->store(m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_TEMP_BEST]);
     
     pcCU->setCbfSubParts( 0, 0, 0, 0, pcCU->getDepth( 0 ) );
@@ -4631,8 +4577,5 @@
     uiBits = 0;
     uiDistortion = 0;
-    if( m_bUseSBACRD )
-    {
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_CURR_BEST ] );
-    }
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_CURR_BEST ] );
     
     UInt uiZeroDistortion = 0;
@@ -4668,8 +4611,5 @@
     }
     
-    if( m_bUseSBACRD )
-    {
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
-    }
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
 #if 0 // check
     {
@@ -4677,8 +4617,5 @@
       m_pcEntropyCoder->encodeCoeff( pcCU, 0, pcCU->getDepth(0), pcCU->getWidth(0), pcCU->getHeight(0) );
       const UInt uiBitsForCoeff = m_pcEntropyCoder->getNumberOfWrittenBits();
-      if( m_bUseSBACRD )
-      {
-        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
-      }
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[pcCU->getDepth(0)][CI_CURR_BEST] );
       if( uiBitsForCoeff != uiBits )
         assert( 0 );
@@ -4729,8 +4666,5 @@
       dCostBest        = dCost;
       qpBest           = qp;
-      if( m_bUseSBACRD )
-      {
-        m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
-      }
+      m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
     }
   }
@@ -4740,9 +4674,7 @@
   if( qpMin != qpMax && qpBest != qpMax )
   {
-    if( m_bUseSBACRD )
-    {
-      assert( 0 ); // check
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
-    }
+    assert( 0 ); // check
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ pcCU->getDepth( 0 ) ][ CI_TEMP_BEST ] );
+
     // copy best cbf and trIdx to pcCU
     const UInt uiQPartNum = pcCU->getPic()->getNumPartInCU() >> (pcCU->getDepth(0) << 1);
@@ -4824,8 +4756,5 @@
   UInt uiBestTransformMode[3] = {0};
 
-  if( m_bUseSBACRD )
-  {
-    m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-  }
+  m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
   
   if( bCheckFull )
@@ -4965,5 +4894,5 @@
 
       Int scalingListType = 3 + g_eTTable[(Int)TEXT_LUMA];
-      assert(scalingListType < 6);     
+      assert(scalingListType < SCALING_LIST_NUM);
       m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,REG_DCT, pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, trWidth, trHeight, scalingListType );//this is for inter mode only
       
@@ -5038,5 +4967,5 @@
 
         Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_U];
-        assert(scalingListType < 6);
+        assert(scalingListType < SCALING_LIST_NUM);
         m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrU, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrU, trWidthC, trHeightC, scalingListType  );
         
@@ -5108,5 +5037,5 @@
 
         Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_V];
-        assert(scalingListType < 6);
+        assert(scalingListType < SCALING_LIST_NUM);
         m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrV, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrV, trWidthC, trHeightC, scalingListType );
         
@@ -5192,8 +5121,5 @@
       }
 
-      if( m_bUseSBACRD )
-      {
-        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-      }
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
 
       pcCU->setTransformSkipSubParts ( 1, TEXT_LUMA, uiAbsPartIdx, uiDepth );
@@ -5234,5 +5160,5 @@
 
         Int scalingListType = 3 + g_eTTable[(Int)TEXT_LUMA];
-        assert(scalingListType < 6);     
+        assert(scalingListType < SCALING_LIST_NUM);
 
         m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_LUMA,REG_DCT, pcResiCurrY, m_pcQTTempTComYuv[uiQTTempAccessLayer].getStride(),  pcCoeffCurrY, trWidth, trHeight, scalingListType, true );
@@ -5292,8 +5218,5 @@
       }
 
-      if( m_bUseSBACRD )
-      {
-        m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-      }
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
 
       pcCU->setTransformSkipSubParts ( 1, TEXT_CHROMA_U, uiAbsPartIdx, pcCU->getDepth(0)+uiTrModeC ); 
@@ -5345,5 +5268,5 @@
 
         Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_U];
-        assert(scalingListType < 6);
+        assert(scalingListType < SCALING_LIST_NUM);
 
         m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrU, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrU, trWidthC, trHeightC, scalingListType, true  );
@@ -5387,5 +5310,5 @@
 
         Int scalingListType = 3 + g_eTTable[(Int)TEXT_CHROMA_V];
-        assert(scalingListType < 6);
+        assert(scalingListType < SCALING_LIST_NUM);
 
         m_pcTrQuant->invtransformNxN( pcCU->getCUTransquantBypass(uiAbsPartIdx), TEXT_CHROMA,REG_DCT, pcResiCurrV, m_pcQTTempTComYuv[uiQTTempAccessLayer].getCStride(), pcCoeffCurrV, trWidthC, trHeightC, scalingListType, true );
@@ -5423,9 +5346,5 @@
     }
 
-    if( m_bUseSBACRD )
-    {
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-    }
-
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
     m_pcEntropyCoder->resetBits();
 
@@ -5460,5 +5379,5 @@
   if( bCheckSplit )
   {
-    if( m_bUseSBACRD && bCheckFull )
+    if( bCheckFull )
     {
       m_pcRDGoOnSbacCoder->store( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_TEST ] );
@@ -5492,8 +5411,5 @@
     }
     
-    if( m_bUseSBACRD )
-    {
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
-    }
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_ROOT ] );
     m_pcEntropyCoder->resetBits();
     
@@ -5523,8 +5439,6 @@
     }
     assert( bCheckFull );
-    if( m_bUseSBACRD )
-    {
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_TEST ] );
-    }
+
+    m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[ uiDepth ][ CI_QT_TRAFO_TEST ] );
   }
   rdCost += dSingleCost;
@@ -5717,9 +5631,6 @@
 UInt TEncSearch::xModeBitsIntra( TComDataCU* pcCU, UInt uiMode, UInt uiPU, UInt uiPartOffset, UInt uiDepth, UInt uiInitTrDepth )
 {
-  if( m_bUseSBACRD )
-  {
-    // Reload only contexts required for coding intra mode information
-    m_pcRDGoOnSbacCoder->loadIntraDirModeLuma( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
-  }
+  // Reload only contexts required for coding intra mode information
+  m_pcRDGoOnSbacCoder->loadIntraDirModeLuma( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
   
   pcCU->setLumaIntraDirSubParts ( uiMode, uiPartOffset, uiDepth + uiInitTrDepth );
@@ -6037,4 +5948,5 @@
 }
 
+#if SVC_EXTENSION
 #if REF_IDX_ME_ZEROMV
 Void TEncSearch::xPatternSearchFracDIFMv0(TComDataCU* pcCU,
@@ -6205,4 +6117,5 @@
 }
 #endif
+#endif //SVC_EXTENSION
 
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncSearch.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSearch.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncSearch.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -97,8 +97,4 @@
   TEncCfg*        m_pcEncCfg;
   
-#if SVC_EXTENSION
-  TEncTop**       m_ppcTEncTop;
-#endif
-  
   // interface to classes
   TComTrQuant*    m_pcTrQuant;
@@ -118,5 +114,4 @@
   TEncSbac***     m_pppcRDSbacCoder;
   TEncSbac*       m_pcRDGoOnSbacCoder;
-  Bool            m_bUseSBACRD;
   DistParam       m_cDistParam;
   
@@ -130,7 +125,10 @@
   UInt            m_auiMVPIdxCost[AMVP_MAX_NUM_CANDS+1][AMVP_MAX_NUM_CANDS+1]; //th array bounds
 
+#if SVC_EXTENSION
+  TEncTop**       m_ppcTEncTop;
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
   Bool            m_disableILP;
 #endif
+#endif //SVC_EXTENAION
 
 public:
@@ -207,8 +205,4 @@
                                 );
   
-#if (ENCODER_FAST_MODE)
-  Bool predInterSearchILRUni    ( TComDataCU* pcCU, TComYuv*    pcOrgYuv, TComYuv*&   rpcPredYuv, TComYuv*&   rpcResiYuv, TComYuv*&   rpcRecoYuv, UInt        refLayerId );
-#endif
-  
   /// encode residual and compute rd-cost for inter mode
   Void encodeResAndCalcRdInterCU( TComDataCU* pcCU,
@@ -226,7 +220,12 @@
   Void IPCMSearch (TComDataCU* pcCU, TComYuv* pcOrgYuv, TComYuv*& rpcPredYuv, TComYuv*& rpcResiYuv, TComYuv*& rpcRecoYuv );
 
+#if SVC_EXTENSION
+#if (ENCODER_FAST_MODE)
+  Bool predInterSearchILRUni    ( TComDataCU* pcCU, TComYuv*    pcOrgYuv, TComYuv*&   rpcPredYuv, TComYuv*&   rpcResiYuv, TComYuv*&   rpcRecoYuv, UInt        refLayerId );
+#endif  
 #if N0383_IL_CONSTRAINED_TILE_SETS_SEI
   Void setDisableILP(Bool a) {m_disableILP = a;}
 #endif
+#endif //SVC_EXTENSION
 
 protected:
@@ -453,4 +452,35 @@
                                    ,Bool biPred
                                    );
+  
+  Void xExtDIFUpSamplingH( TComPattern* pcPattern, Bool biPred  );
+  Void xExtDIFUpSamplingQ( TComPattern* pcPatternKey, TComMv halfPelRef, Bool biPred );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // T & Q & Q-1 & T-1
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void xEncodeResidualQT( TComDataCU* pcCU, UInt uiAbsPartIdx, const UInt uiDepth, Bool bSubdivAndCbf, TextType eType );
+  Void xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx,TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, UInt &ruiDist, UInt *puiZeroDist );
+  Void xSetResidualQTData( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx,UInt absTUPartIdx, TComYuv* pcResi, UInt uiDepth, Bool bSpatial );
+  
+  UInt  xModeBitsIntra ( TComDataCU* pcCU, UInt uiMode, UInt uiPU, UInt uiPartOffset, UInt uiDepth, UInt uiInitTrDepth );
+  UInt  xUpdateCandList( UInt uiMode, Double uiCost, UInt uiFastCandNum, UInt * CandModeList, Double * CandCostList );
+  
+  // -------------------------------------------------------------------------------------------------------------------
+  // compute symbol bits
+  // -------------------------------------------------------------------------------------------------------------------
+  
+  Void xAddSymbolBitsInter        ( TComDataCU*   pcCU,
+                                   UInt          uiQp,
+                                   UInt          uiTrMode,
+                                   UInt&         ruiBits,
+                                   TComYuv*&     rpcYuvRec,
+                                   TComYuv*      pcYuvPred,
+                                   TComYuv*&     rpcYuvResi );
+  
+  Void  setWpScalingDistParam( TComDataCU* pcCU, Int iRefIdx, RefPicList eRefPicListCur );
+  inline  Void  setDistParamComp( UInt uiComp )  { m_cDistParam.uiComp = uiComp; }
+
+#if SVC_EXTENSION
 #if REF_IDX_ME_ZEROMV
   Void xPatternSearchFracDIFMv0  ( TComDataCU*   pcCU,
@@ -464,33 +494,6 @@
                                    Bool          biPred );
 #endif
-  Void xExtDIFUpSamplingH( TComPattern* pcPattern, Bool biPred  );
-  Void xExtDIFUpSamplingQ( TComPattern* pcPatternKey, TComMv halfPelRef, Bool biPred );
-  
-  // -------------------------------------------------------------------------------------------------------------------
-  // T & Q & Q-1 & T-1
-  // -------------------------------------------------------------------------------------------------------------------
-  
-  Void xEncodeResidualQT( TComDataCU* pcCU, UInt uiAbsPartIdx, const UInt uiDepth, Bool bSubdivAndCbf, TextType eType );
-  Void xEstimateResidualQT( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx, UInt absTUPartIdx,TComYuv* pcResi, const UInt uiDepth, Double &rdCost, UInt &ruiBits, UInt &ruiDist, UInt *puiZeroDist );
-  Void xSetResidualQTData( TComDataCU* pcCU, UInt uiQuadrant, UInt uiAbsPartIdx,UInt absTUPartIdx, TComYuv* pcResi, UInt uiDepth, Bool bSpatial );
-  
-  UInt  xModeBitsIntra ( TComDataCU* pcCU, UInt uiMode, UInt uiPU, UInt uiPartOffset, UInt uiDepth, UInt uiInitTrDepth );
-  UInt  xUpdateCandList( UInt uiMode, Double uiCost, UInt uiFastCandNum, UInt * CandModeList, Double * CandCostList );
-  
-  // -------------------------------------------------------------------------------------------------------------------
-  // compute symbol bits
-  // -------------------------------------------------------------------------------------------------------------------
-  
-  Void xAddSymbolBitsInter        ( TComDataCU*   pcCU,
-                                   UInt          uiQp,
-                                   UInt          uiTrMode,
-                                   UInt&         ruiBits,
-                                   TComYuv*&     rpcYuvRec,
-                                   TComYuv*      pcYuvPred,
-                                   TComYuv*&     rpcYuvResi );
-  
-  Void  setWpScalingDistParam( TComDataCU* pcCU, Int iRefIdx, RefPicList eRefPicListCur );
-  inline  Void  setDistParamComp( UInt uiComp )  { m_cDistParam.uiComp = uiComp; }
-  
+#endif //SVC_EXTENSION  
+
 };// END CLASS DEFINITION TEncSearch
 
Index: trunk/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -254,5 +254,5 @@
 
   eSliceType=B_SLICE;
-  eSliceType = (pocLast == 0 || pocCurr % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+  eSliceType = (pocLast == 0 || (pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
 
   rpcSlice->setSliceType    ( eSliceType );
@@ -280,7 +280,7 @@
   {
 #if REPN_FORMAT_IN_VPS
-    if (!(( m_pcCfg->getMaxDeltaQP() == 0 ) && (dQP == -rpcSlice->getQpBDOffsetY() ) && (rpcSlice->getSPS()->getUseLossless())))
+    if (!(( m_pcCfg->getMaxDeltaQP() == 0 ) && (dQP == -rpcSlice->getQpBDOffsetY() ) && (rpcSlice->getPPS()->getTransquantBypassEnableFlag())))
 #else
-    if (!(( m_pcCfg->getMaxDeltaQP() == 0 ) && (dQP == -rpcSlice->getSPS()->getQpBDOffsetY() ) && (rpcSlice->getSPS()->getUseLossless())))
+    if (!(( m_pcCfg->getMaxDeltaQP() == 0 ) && (dQP == -rpcSlice->getSPS()->getQpBDOffsetY() ) && (rpcSlice->getPPS()->getTransquantBypassEnableFlag())))
 #endif
     {
@@ -423,5 +423,5 @@
 #if HB_LAMBDA_FOR_LDC
   // restore original slice type
-  eSliceType = (pocLast == 0 || pocCurr % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
+  eSliceType = (pocLast == 0 || (pocCurr - isField) % m_pcCfg->getIntraPeriod() == 0 || m_pcGOPEncoder->getGOPSize() == 0) ? I_SLICE : eSliceType;
 
 #if SVC_EXTENSION
@@ -785,21 +785,12 @@
 
   // set entropy coder
-  if( m_pcCfg->getUseSBACRD() )
-  {
-    m_pcSbacCoder->init( m_pcBinCABAC );
-    m_pcEntropyCoder->setEntropyCoder   ( m_pcSbacCoder, pcSlice );
-    m_pcEntropyCoder->resetEntropy      ();
-    m_pppcRDSbacCoder[0][CI_CURR_BEST]->load(m_pcSbacCoder);
-    pppcRDSbacCoder = (TEncBinCABAC *) m_pppcRDSbacCoder[0][CI_CURR_BEST]->getEncBinIf();
-    pppcRDSbacCoder->setBinCountingEnableFlag( false );
-    pppcRDSbacCoder->setBinsCoded( 0 );
-  }
-  else
-  {
-    m_pcEntropyCoder->setEntropyCoder ( m_pcCavlcCoder, pcSlice );
-    m_pcEntropyCoder->resetEntropy      ();
-    m_pcEntropyCoder->setBitstream    ( m_pcBitCounter );
-  }
-
+  m_pcSbacCoder->init( m_pcBinCABAC );
+  m_pcEntropyCoder->setEntropyCoder   ( m_pcSbacCoder, pcSlice );
+  m_pcEntropyCoder->resetEntropy      ();
+  m_pppcRDSbacCoder[0][CI_CURR_BEST]->load(m_pcSbacCoder);
+  pppcRDSbacCoder = (TEncBinCABAC *) m_pppcRDSbacCoder[0][CI_CURR_BEST]->getEncBinIf();
+  pppcRDSbacCoder->setBinCountingEnableFlag( false );
+  pppcRDSbacCoder->setBinsCoded( 0 );
+  
   //------------------------------------------------------------------------------
   //  Weighted Prediction parameters estimation.
@@ -854,39 +845,35 @@
   UInt uiTilesAcross  = 0;
 
-  if( m_pcCfg->getUseSBACRD() )
-  {
-    iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
-    uiTilesAcross = rpcPic->getPicSym()->getNumColumnsMinus1()+1;
-    delete[] m_pcBufferSbacCoders;
-    delete[] m_pcBufferBinCoderCABACs;
-    m_pcBufferSbacCoders     = new TEncSbac    [uiTilesAcross];
-    m_pcBufferBinCoderCABACs = new TEncBinCABAC[uiTilesAcross];
-    for (Int ui = 0; ui < uiTilesAcross; ui++)
-    {
-      m_pcBufferSbacCoders[ui].init( &m_pcBufferBinCoderCABACs[ui] );
-    }
-    for (UInt ui = 0; ui < uiTilesAcross; ui++)
-    {
-      m_pcBufferSbacCoders[ui].load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);  //init. state
-    }
-
-    for ( UInt ui = 0 ; ui < iNumSubstreams ; ui++ ) //init all sbac coders for RD optimization
-    {
-      ppppcRDSbacCoders[ui][0][CI_CURR_BEST]->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
-    }
-  }
-  //if( m_pcCfg->getUseSBACRD() )
-  {
-    delete[] m_pcBufferLowLatSbacCoders;
-    delete[] m_pcBufferLowLatBinCoderCABACs;
-    m_pcBufferLowLatSbacCoders     = new TEncSbac    [uiTilesAcross];
-    m_pcBufferLowLatBinCoderCABACs = new TEncBinCABAC[uiTilesAcross];
-    for (Int ui = 0; ui < uiTilesAcross; ui++)
-    {
-      m_pcBufferLowLatSbacCoders[ui].init( &m_pcBufferLowLatBinCoderCABACs[ui] );
-    }
-    for (UInt ui = 0; ui < uiTilesAcross; ui++)
-      m_pcBufferLowLatSbacCoders[ui].load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);  //init. state
-  }
+  iNumSubstreams = pcSlice->getPPS()->getNumSubstreams();
+  uiTilesAcross = rpcPic->getPicSym()->getNumColumnsMinus1()+1;
+  delete[] m_pcBufferSbacCoders;
+  delete[] m_pcBufferBinCoderCABACs;
+  m_pcBufferSbacCoders     = new TEncSbac    [uiTilesAcross];
+  m_pcBufferBinCoderCABACs = new TEncBinCABAC[uiTilesAcross];
+  for (Int ui = 0; ui < uiTilesAcross; ui++)
+  {
+    m_pcBufferSbacCoders[ui].init( &m_pcBufferBinCoderCABACs[ui] );
+  }
+  for (UInt ui = 0; ui < uiTilesAcross; ui++)
+  {
+    m_pcBufferSbacCoders[ui].load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);  //init. state
+  }
+
+  for ( UInt ui = 0 ; ui < iNumSubstreams ; ui++ ) //init all sbac coders for RD optimization
+  {
+    ppppcRDSbacCoders[ui][0][CI_CURR_BEST]->load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);
+  }
+
+  delete[] m_pcBufferLowLatSbacCoders;
+  delete[] m_pcBufferLowLatBinCoderCABACs;
+  m_pcBufferLowLatSbacCoders     = new TEncSbac    [uiTilesAcross];
+  m_pcBufferLowLatBinCoderCABACs = new TEncBinCABAC[uiTilesAcross];
+  for (Int ui = 0; ui < uiTilesAcross; ui++)
+  {
+    m_pcBufferLowLatSbacCoders[ui].init( &m_pcBufferLowLatBinCoderCABACs[ui] );
+  }
+  for (UInt ui = 0; ui < uiTilesAcross; ui++)
+    m_pcBufferLowLatSbacCoders[ui].load(m_pppcRDSbacCoder[0][CI_CURR_BEST]);  //init. state
+
   UInt uiWidthInLCUs  = rpcPic->getPicSym()->getFrameWidthInCU();
   //UInt uiHeightInLCUs = rpcPic->getPicSym()->getFrameHeightInCU();
@@ -944,51 +931,48 @@
 
     // inherit from TR if necessary, select substream to use.
-    if( m_pcCfg->getUseSBACRD() )
-    {
-      uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
-      uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
-      uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
-      //UInt uiSliceStartLCU = pcSlice->getSliceCurStartCUAddr();
-      uiCol     = uiCUAddr % uiWidthInLCUs;
-      uiLin     = uiCUAddr / uiWidthInLCUs;
-      if (pcSlice->getPPS()->getNumSubstreams() > 1)
-      {
-        // independent tiles => substreams are "per tile".  iNumSubstreams has already been multiplied.
-        Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
-        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)*iNumSubstreamsPerTile
-                      + uiLin%iNumSubstreamsPerTile;
+    uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
+    uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
+    uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
+    //UInt uiSliceStartLCU = pcSlice->getSliceCurStartCUAddr();
+    uiCol     = uiCUAddr % uiWidthInLCUs;
+    uiLin     = uiCUAddr / uiWidthInLCUs;
+    if (pcSlice->getPPS()->getNumSubstreams() > 1)
+    {
+      // independent tiles => substreams are "per tile".  iNumSubstreams has already been multiplied.
+      Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
+      uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)*iNumSubstreamsPerTile
+          + uiLin%iNumSubstreamsPerTile;
+    }
+    else
+    {
+      // dependent tiles => substreams are "per frame".
+      uiSubStrm = uiLin % iNumSubstreams;
+    }
+    if ( ((pcSlice->getPPS()->getNumSubstreams() > 1) || depSliceSegmentsEnabled ) && (uiCol == uiTileLCUX) && m_pcCfg->getWaveFrontsynchro())
+    {
+      // We'll sync if the TR is available.
+      TComDataCU *pcCUUp = pcCU->getCUAbove();
+      UInt uiWidthInCU = rpcPic->getFrameWidthInCU();
+      UInt uiMaxParts = 1<<(pcSlice->getSPS()->getMaxCUDepth()<<1);
+      TComDataCU *pcCUTR = NULL;
+      if ( pcCUUp && ((uiCUAddr%uiWidthInCU+1) < uiWidthInCU)  )
+      {
+        pcCUTR = rpcPic->getCU( uiCUAddr - uiWidthInCU + 1 );
+      }
+      if ( ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) ||
+          (pcCUTR->getSCUAddr()+uiMaxParts-1 < pcSlice->getSliceCurStartCUAddr()) ||
+          ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)))
+      )
+      )
+      {
+        // TR not available.
       }
       else
       {
-        // dependent tiles => substreams are "per frame".
-        uiSubStrm = uiLin % iNumSubstreams;
-      }
-      if ( ((pcSlice->getPPS()->getNumSubstreams() > 1) || depSliceSegmentsEnabled ) && (uiCol == uiTileLCUX) && m_pcCfg->getWaveFrontsynchro())
-      {
-        // We'll sync if the TR is available.
-        TComDataCU *pcCUUp = pcCU->getCUAbove();
-        UInt uiWidthInCU = rpcPic->getFrameWidthInCU();
-        UInt uiMaxParts = 1<<(pcSlice->getSPS()->getMaxCUDepth()<<1);
-        TComDataCU *pcCUTR = NULL;
-        if ( pcCUUp && ((uiCUAddr%uiWidthInCU+1) < uiWidthInCU)  )
-        {
-          pcCUTR = rpcPic->getCU( uiCUAddr - uiWidthInCU + 1 );
-        }
-        if ( ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) ||
-             (pcCUTR->getSCUAddr()+uiMaxParts-1 < pcSlice->getSliceCurStartCUAddr()) ||
-             ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)))
-             )
-           )
-        {
-          // TR not available.
-        }
-        else
-        {
-          // TR is available, we use it.
-          ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->loadContexts( &m_pcBufferSbacCoders[uiTileCol] );
-        }
-      }
-      m_pppcRDSbacCoder[0][CI_CURR_BEST]->load( ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST] ); //this load is used to simplify the code
-    }
+        // TR is available, we use it.
+        ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->loadContexts( &m_pcBufferSbacCoders[uiTileCol] );
+      }
+    }
+    m_pppcRDSbacCoder[0][CI_CURR_BEST]->load( ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST] ); //this load is used to simplify the code
 
     // reset the entropy coder
@@ -1008,36 +992,34 @@
       m_pcEntropyCoder->setEntropyCoder     ( m_pcSbacCoder, pcSlice );
     }
-    // if RD based on SBAC is used
-    if( m_pcCfg->getUseSBACRD() )
-    {
-      // set go-on entropy coder
-      m_pcEntropyCoder->setEntropyCoder ( m_pcRDGoOnSbacCoder, pcSlice );
-      m_pcEntropyCoder->setBitstream( &pcBitCounters[uiSubStrm] );
-
-      ((TEncBinCABAC*)m_pcRDGoOnSbacCoder->getEncBinIf())->setBinCountingEnableFlag(true);
-
-      Double oldLambda = m_pcRdCost->getLambda();
-      if ( m_pcCfg->getUseRateCtrl() )
-      {
-        Int estQP        = pcSlice->getSliceQp();
-        Double estLambda = -1.0;
-        Double bpp       = -1.0;
-
-        if ( ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE && m_pcCfg->getForceIntraQP() ) || !m_pcCfg->getLCULevelRC() )
+
+    // set go-on entropy coder
+    m_pcEntropyCoder->setEntropyCoder ( m_pcRDGoOnSbacCoder, pcSlice );
+    m_pcEntropyCoder->setBitstream( &pcBitCounters[uiSubStrm] );
+
+    ((TEncBinCABAC*)m_pcRDGoOnSbacCoder->getEncBinIf())->setBinCountingEnableFlag(true);
+
+    Double oldLambda = m_pcRdCost->getLambda();
+    if ( m_pcCfg->getUseRateCtrl() )
+    {
+      Int estQP        = pcSlice->getSliceQp();
+      Double estLambda = -1.0;
+      Double bpp       = -1.0;
+
+      if ( ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE && m_pcCfg->getForceIntraQP() ) || !m_pcCfg->getLCULevelRC() )
+      {
+        estQP = pcSlice->getSliceQp();
+      }
+      else
+      {
+        bpp = m_pcRateCtrl->getRCPic()->getLCUTargetBpp(pcSlice->getSliceType());
+        if ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE)
         {
-          estQP = pcSlice->getSliceQp();
+          estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambdaAndQP(bpp, pcSlice->getSliceQp(), &estQP);
         }
         else
         {
-          bpp = m_pcRateCtrl->getRCPic()->getLCUTargetBpp(pcSlice->getSliceType());
-          if ( rpcPic->getSlice( 0 )->getSliceType() == I_SLICE)
-          {
-            estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambdaAndQP(bpp, pcSlice->getSliceQp(), &estQP);
-          }
-          else
-          {
-            estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambda( bpp );
-            estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
-          }
+          estLambda = m_pcRateCtrl->getRCPic()->getLCUEstLambda( bpp );
+          estQP     = m_pcRateCtrl->getRCPic()->getLCUEstQP    ( estLambda, pcSlice->getSliceQp() );
+        }
 
 #if REPN_FORMAT_IN_VPS
@@ -1056,90 +1038,70 @@
           m_pcTrQuant->setLambda( estLambda );
 #endif
+      }
+
+      m_pcRateCtrl->setRCQP( estQP );
+      pcCU->getSlice()->setSliceQpBase( estQP );
+    }
+
+    // run CU encoder
+    m_pcCuEncoder->compressCU( pcCU );
+
+    // restore entropy coder to an initial stage
+    m_pcEntropyCoder->setEntropyCoder ( m_pppcRDSbacCoder[0][CI_CURR_BEST], pcSlice );
+    m_pcEntropyCoder->setBitstream( &pcBitCounters[uiSubStrm] );
+    m_pcCuEncoder->setBitCounter( &pcBitCounters[uiSubStrm] );
+    m_pcBitCounter = &pcBitCounters[uiSubStrm];
+    pppcRDSbacCoder->setBinCountingEnableFlag( true );
+    m_pcBitCounter->resetBits();
+    pppcRDSbacCoder->setBinsCoded( 0 );
+    m_pcCuEncoder->encodeCU( pcCU );
+
+    pppcRDSbacCoder->setBinCountingEnableFlag( false );
+    if (m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_BYTES && ( ( pcSlice->getSliceBits() + m_pcEntropyCoder->getNumberOfWrittenBits() ) ) > m_pcCfg->getSliceArgument()<<3)
+    {
+      pcSlice->setNextSlice( true );
+      break;
+    }
+    if (m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES && pcSlice->getSliceSegmentBits()+m_pcEntropyCoder->getNumberOfWrittenBits() > (m_pcCfg->getSliceSegmentArgument() << 3) &&pcSlice->getSliceCurEndCUAddr()!=pcSlice->getSliceSegmentCurEndCUAddr())
+    {
+      pcSlice->setNextSliceSegment( true );
+      break;
+    }
+
+    ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->load( m_pppcRDSbacCoder[0][CI_CURR_BEST] );
+    //Store probabilties of second LCU in line into buffer
+    if ( ( uiCol == uiTileLCUX+1) && (depSliceSegmentsEnabled || (pcSlice->getPPS()->getNumSubstreams() > 1)) && m_pcCfg->getWaveFrontsynchro())
+    {
+      m_pcBufferSbacCoders[uiTileCol].loadContexts(ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]);
+    }
+
+    if ( m_pcCfg->getUseRateCtrl() )
+    {
+
+      Int actualQP        = g_RCInvalidQPValue;
+      Double actualLambda = m_pcRdCost->getLambda();
+      Int actualBits      = pcCU->getTotalBits();
+      Int numberOfEffectivePixels    = 0;
+      for ( Int idx = 0; idx < rpcPic->getNumPartInCU(); idx++ )
+      {
+        if ( pcCU->getPredictionMode( idx ) != MODE_NONE && ( !pcCU->isSkipped( idx ) ) )
+        {
+          numberOfEffectivePixels = numberOfEffectivePixels + 16;
+          break;
         }
-
-        m_pcRateCtrl->setRCQP( estQP );
-        pcCU->getSlice()->setSliceQpBase( estQP );
-      }
-
-      // run CU encoder
-      m_pcCuEncoder->compressCU( pcCU );
-
-      // restore entropy coder to an initial stage
-      m_pcEntropyCoder->setEntropyCoder ( m_pppcRDSbacCoder[0][CI_CURR_BEST], pcSlice );
-      m_pcEntropyCoder->setBitstream( &pcBitCounters[uiSubStrm] );
-      m_pcCuEncoder->setBitCounter( &pcBitCounters[uiSubStrm] );
-      m_pcBitCounter = &pcBitCounters[uiSubStrm];
-      pppcRDSbacCoder->setBinCountingEnableFlag( true );
-      m_pcBitCounter->resetBits();
-      pppcRDSbacCoder->setBinsCoded( 0 );
-      m_pcCuEncoder->encodeCU( pcCU );
-
-      pppcRDSbacCoder->setBinCountingEnableFlag( false );
-      if (m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_BYTES && ( ( pcSlice->getSliceBits() + m_pcEntropyCoder->getNumberOfWrittenBits() ) ) > m_pcCfg->getSliceArgument()<<3)
-      {
-        pcSlice->setNextSlice( true );
-        break;
-      }
-      if (m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES && pcSlice->getSliceSegmentBits()+m_pcEntropyCoder->getNumberOfWrittenBits() > (m_pcCfg->getSliceSegmentArgument() << 3) &&pcSlice->getSliceCurEndCUAddr()!=pcSlice->getSliceSegmentCurEndCUAddr())
-      {
-        pcSlice->setNextSliceSegment( true );
-        break;
-      }
-      if( m_pcCfg->getUseSBACRD() )
-      {
-         ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]->load( m_pppcRDSbacCoder[0][CI_CURR_BEST] );
-
-         //Store probabilties of second LCU in line into buffer
-         if ( ( uiCol == uiTileLCUX+1) && (depSliceSegmentsEnabled || (pcSlice->getPPS()->getNumSubstreams() > 1)) && m_pcCfg->getWaveFrontsynchro())
-        {
-          m_pcBufferSbacCoders[uiTileCol].loadContexts(ppppcRDSbacCoders[uiSubStrm][0][CI_CURR_BEST]);
-        }
-      }
-
-      if ( m_pcCfg->getUseRateCtrl() )
-      {
-
-        Int actualQP        = g_RCInvalidQPValue;
-        Double actualLambda = m_pcRdCost->getLambda();
-        Int actualBits      = pcCU->getTotalBits();
-        Int numberOfEffectivePixels    = 0;
-        for ( Int idx = 0; idx < rpcPic->getNumPartInCU(); idx++ )
-        {
-          if ( pcCU->getPredictionMode( idx ) != MODE_NONE && ( !pcCU->isSkipped( idx ) ) )
-          {
-            numberOfEffectivePixels = numberOfEffectivePixels + 16;
-            break;
-          }
-        }
-
-        if ( numberOfEffectivePixels == 0 )
-        {
-          actualQP = g_RCInvalidQPValue;
-        }
-        else
-        {
-          actualQP = pcCU->getQP( 0 );
-        }
-        m_pcRdCost->setLambda(oldLambda);
-
-        m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda,
-          pcCU->getSlice()->getSliceType() == I_SLICE ? 0 : m_pcCfg->getLCULevelRC() );
-      }
-    }
-    // other case: encodeCU is not called
-    else
-    {
-      m_pcCuEncoder->compressCU( pcCU );
-      m_pcCuEncoder->encodeCU( pcCU );
-      if (m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_BYTES && ( ( pcSlice->getSliceBits()+ m_pcEntropyCoder->getNumberOfWrittenBits() ) ) > m_pcCfg->getSliceArgument()<<3)
-      {
-        pcSlice->setNextSlice( true );
-        break;
-      }
-      if (m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES && pcSlice->getSliceSegmentBits()+ m_pcEntropyCoder->getNumberOfWrittenBits()> m_pcCfg->getSliceSegmentArgument()<<3 &&pcSlice->getSliceCurEndCUAddr()!=pcSlice->getSliceSegmentCurEndCUAddr())
-      {
-        pcSlice->setNextSliceSegment( true );
-        break;
-      }
+      }
+
+      if ( numberOfEffectivePixels == 0 )
+      {
+        actualQP = g_RCInvalidQPValue;
+      }
+      else
+      {
+        actualQP = pcCU->getQP( 0 );
+      }
+      m_pcRdCost->setLambda(oldLambda);
+
+      m_pcRateCtrl->getRCPic()->updateAfterLCU( m_pcRateCtrl->getRCPic()->getLCUCoded(), actualBits, actualQP, actualLambda,
+        pcCU->getSlice()->getSliceType() == I_SLICE ? 0 : m_pcCfg->getLCULevelRC() );
     }
 
@@ -1151,4 +1113,15 @@
   {
     pcSlice->setNextSlice( true );
+  }
+  if(m_pcCfg->getSliceMode()==FIXED_NUMBER_OF_BYTES || m_pcCfg->getSliceSegmentMode()==FIXED_NUMBER_OF_BYTES)
+  {
+    if(pcSlice->getSliceCurEndCUAddr()<=pcSlice->getSliceSegmentCurEndCUAddr())
+    {
+       pcSlice->setNextSlice( true );
+    }
+    else
+    {
+       pcSlice->setNextSliceSegment( true );
+    }
   }
   if( depSliceSegmentsEnabled )
@@ -1269,55 +1242,53 @@
        uiCUAddr = rpcPic->getPicSym()->getCUOrderMap(++uiEncCUOrder) )
   {
-    if( m_pcCfg->getUseSBACRD() )
-    {
-      uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
-      uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
-      uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
-      //UInt uiSliceStartLCU = pcSlice->getSliceCurStartCUAddr();
-      uiCol     = uiCUAddr % uiWidthInLCUs;
-      uiLin     = uiCUAddr / uiWidthInLCUs;
-      if (pcSlice->getPPS()->getNumSubstreams() > 1)
-      {
-        // independent tiles => substreams are "per tile".  iNumSubstreams has already been multiplied.
-        Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
-        uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)*iNumSubstreamsPerTile
-                      + uiLin%iNumSubstreamsPerTile;
+    uiTileCol = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr) % (rpcPic->getPicSym()->getNumColumnsMinus1()+1); // what column of tiles are we in?
+    uiTileStartLCU = rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr();
+    uiTileLCUX = uiTileStartLCU % uiWidthInLCUs;
+    //UInt uiSliceStartLCU = pcSlice->getSliceCurStartCUAddr();
+    uiCol     = uiCUAddr % uiWidthInLCUs;
+    uiLin     = uiCUAddr / uiWidthInLCUs;
+    if (pcSlice->getPPS()->getNumSubstreams() > 1)
+    {
+      // independent tiles => substreams are "per tile".  iNumSubstreams has already been multiplied.
+      Int iNumSubstreamsPerTile = iNumSubstreams/rpcPic->getPicSym()->getNumTiles();
+      uiSubStrm = rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)*iNumSubstreamsPerTile
+          + uiLin%iNumSubstreamsPerTile;
+    }
+    else
+    {
+      // dependent tiles => substreams are "per frame".
+      uiSubStrm = uiLin % iNumSubstreams;
+    }
+
+    m_pcEntropyCoder->setBitstream( &pcSubstreams[uiSubStrm] );
+    // Synchronize cabac probabilities with upper-right LCU if it's available and we're at the start of a line.
+    if (((pcSlice->getPPS()->getNumSubstreams() > 1) || depSliceSegmentsEnabled) && (uiCol == uiTileLCUX) && m_pcCfg->getWaveFrontsynchro())
+    {
+      // We'll sync if the TR is available.
+      TComDataCU *pcCUUp = rpcPic->getCU( uiCUAddr )->getCUAbove();
+      UInt uiWidthInCU = rpcPic->getFrameWidthInCU();
+      UInt uiMaxParts = 1<<(pcSlice->getSPS()->getMaxCUDepth()<<1);
+      TComDataCU *pcCUTR = NULL;
+      if ( pcCUUp && ((uiCUAddr%uiWidthInCU+1) < uiWidthInCU)  )
+      {
+        pcCUTR = rpcPic->getCU( uiCUAddr - uiWidthInCU + 1 );
+      }
+      if ( (true/*bEnforceSliceRestriction*/ &&
+          ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) ||
+              (pcCUTR->getSCUAddr()+uiMaxParts-1 < pcSlice->getSliceCurStartCUAddr()) ||
+              ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)))
+          ))
+      )
+      {
+        // TR not available.
       }
       else
       {
-        // dependent tiles => substreams are "per frame".
-        uiSubStrm = uiLin % iNumSubstreams;
-      }
-
-      m_pcEntropyCoder->setBitstream( &pcSubstreams[uiSubStrm] );
-      // Synchronize cabac probabilities with upper-right LCU if it's available and we're at the start of a line.
-      if (((pcSlice->getPPS()->getNumSubstreams() > 1) || depSliceSegmentsEnabled) && (uiCol == uiTileLCUX) && m_pcCfg->getWaveFrontsynchro())
-      {
-        // We'll sync if the TR is available.
-        TComDataCU *pcCUUp = rpcPic->getCU( uiCUAddr )->getCUAbove();
-        UInt uiWidthInCU = rpcPic->getFrameWidthInCU();
-        UInt uiMaxParts = 1<<(pcSlice->getSPS()->getMaxCUDepth()<<1);
-        TComDataCU *pcCUTR = NULL;
-        if ( pcCUUp && ((uiCUAddr%uiWidthInCU+1) < uiWidthInCU)  )
-        {
-          pcCUTR = rpcPic->getCU( uiCUAddr - uiWidthInCU + 1 );
-        }
-        if ( (true/*bEnforceSliceRestriction*/ &&
-             ((pcCUTR==NULL) || (pcCUTR->getSlice()==NULL) ||
-             (pcCUTR->getSCUAddr()+uiMaxParts-1 < pcSlice->getSliceCurStartCUAddr()) ||
-             ((rpcPic->getPicSym()->getTileIdxMap( pcCUTR->getAddr() ) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr)))
-             ))
-           )
-        {
-          // TR not available.
-        }
-        else
-        {
-          // TR is available, we use it.
-          pcSbacCoders[uiSubStrm].loadContexts( &m_pcBufferSbacCoders[uiTileCol] );
-        }
-      }
-      m_pcSbacCoder->load(&pcSbacCoders[uiSubStrm]);  //this load is used to simplify the code (avoid to change all the call to m_pcSbacCoder)
-    }
+        // TR is available, we use it.
+        pcSbacCoders[uiSubStrm].loadContexts( &m_pcBufferSbacCoders[uiTileCol] );
+      }
+    }
+    m_pcSbacCoder->load(&pcSbacCoders[uiSubStrm]);  //this load is used to simplify the code (avoid to change all the call to m_pcSbacCoder)
+
     // reset the entropy coder
     if( uiCUAddr == rpcPic->getPicSym()->getTComTile(rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))->getFirstCUAddr() &&                                   // must be first CU of tile
@@ -1360,5 +1331,4 @@
 
     TComDataCU*& pcCU = rpcPic->getCU( uiCUAddr );
-#if HM_CLEANUP_SAO
     if ( pcSlice->getSPS()->getUseSAO() )
     {
@@ -1389,88 +1359,4 @@
       }
     }
-#else
-    if ( pcSlice->getSPS()->getUseSAO() && (pcSlice->getSaoEnabledFlag()||pcSlice->getSaoEnabledFlagChroma()) )
-    {
-      SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
-      Int iNumCuInWidth     = saoParam->numCuInWidth;
-      Int iCUAddrInSlice    = uiCUAddr - rpcPic->getPicSym()->getCUOrderMap(pcSlice->getSliceCurStartCUAddr()/rpcPic->getNumPartInCU());
-      Int iCUAddrUpInSlice  = iCUAddrInSlice - iNumCuInWidth;
-      Int rx = uiCUAddr % iNumCuInWidth;
-      Int ry = uiCUAddr / iNumCuInWidth;
-      Int allowMergeLeft = 1;
-      Int allowMergeUp   = 1;
-      if (rx!=0)
-      {
-        if (rpcPic->getPicSym()->getTileIdxMap(uiCUAddr-1) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))
-        {
-          allowMergeLeft = 0;
-        }
-      }
-      if (ry!=0)
-      {
-        if (rpcPic->getPicSym()->getTileIdxMap(uiCUAddr-iNumCuInWidth) != rpcPic->getPicSym()->getTileIdxMap(uiCUAddr))
-        {
-          allowMergeUp = 0;
-        }
-      }
-      Int addr = pcCU->getAddr();
-      allowMergeLeft = allowMergeLeft && (rx>0) && (iCUAddrInSlice!=0);
-      allowMergeUp = allowMergeUp && (ry>0) && (iCUAddrUpInSlice>=0);
-      if( saoParam->bSaoFlag[0] || saoParam->bSaoFlag[1] )
-      {
-        Int mergeLeft = saoParam->saoLcuParam[0][addr].mergeLeftFlag;
-        Int mergeUp = saoParam->saoLcuParam[0][addr].mergeUpFlag;
-        if (allowMergeLeft)
-        {
-          m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(mergeLeft);
-        }
-        else
-        {
-          mergeLeft = 0;
-        }
-        if(mergeLeft == 0)
-        {
-          if (allowMergeUp)
-          {
-            m_pcEntropyCoder->m_pcEntropyCoderIf->codeSaoMerge(mergeUp);
-          }
-          else
-          {
-            mergeUp = 0;
-          }
-          if(mergeUp == 0)
-          {
-            for (Int compIdx=0;compIdx<3;compIdx++)
-            {
-            if( (compIdx == 0 && saoParam->bSaoFlag[0]) || (compIdx > 0 && saoParam->bSaoFlag[1]))
-              {
-                m_pcEntropyCoder->encodeSaoOffset(&saoParam->saoLcuParam[compIdx][addr], compIdx);
-              }
-            }
-          }
-        }
-      }
-    }
-    else if (pcSlice->getSPS()->getUseSAO())
-    {
-      Int addr = pcCU->getAddr();
-      SAOParam *saoParam = pcSlice->getPic()->getPicSym()->getSaoParam();
-      for (Int cIdx=0; cIdx<3; cIdx++)
-      {
-        SaoLcuParam *saoLcuParam = &(saoParam->saoLcuParam[cIdx][addr]);
-        if ( ((cIdx == 0) && !pcSlice->getSaoEnabledFlag()) || ((cIdx == 1 || cIdx == 2) && !pcSlice->getSaoEnabledFlagChroma()))
-        {
-          saoLcuParam->mergeUpFlag   = 0;
-          saoLcuParam->mergeLeftFlag = 0;
-          saoLcuParam->subTypeIdx    = 0;
-          saoLcuParam->typeIdx       = -1;
-          saoLcuParam->offset[0]     = 0;
-          saoLcuParam->offset[1]     = 0;
-          saoLcuParam->offset[2]     = 0;
-          saoLcuParam->offset[3]     = 0;
-        }
-      }
-    }
-#endif
 
 #if ENC_DEC_TRACE
@@ -1489,14 +1375,9 @@
     g_bJustDoIt = g_bEncDecTraceDisable;
 #endif
-    if( m_pcCfg->getUseSBACRD() )
-    {
-       pcSbacCoders[uiSubStrm].load(m_pcSbacCoder);   //load back status of the entropy coder after encoding the LCU into relevant bitstream entropy coder
-
-
-       //Store probabilties of second LCU in line into buffer
-       if ( (depSliceSegmentsEnabled || (pcSlice->getPPS()->getNumSubstreams() > 1)) && (uiCol == uiTileLCUX+1) && m_pcCfg->getWaveFrontsynchro())
-      {
-        m_pcBufferSbacCoders[uiTileCol].loadContexts( &pcSbacCoders[uiSubStrm] );
-      }
+    pcSbacCoders[uiSubStrm].load(m_pcSbacCoder);   //load back status of the entropy coder after encoding the LCU into relevant bitstream entropy coder
+    //Store probabilties of second LCU in line into buffer
+    if ( (depSliceSegmentsEnabled || (pcSlice->getPPS()->getNumSubstreams() > 1)) && (uiCol == uiTileLCUX+1) && m_pcCfg->getWaveFrontsynchro())
+    {
+      m_pcBufferSbacCoders[uiTileCol].loadContexts( &pcSbacCoders[uiSubStrm] );
     }
   }
@@ -1870,4 +1751,5 @@
 }
 
+#if SVC_EXTENSION
 #if JCTVC_M0259_LAMBDAREFINEMENT
 Double TEncSlice::xCalEnhLambdaFactor( Double deltaQP , Double beta )
@@ -1888,3 +1770,4 @@
 }
 #endif
+#endif //SVC_EXTENSION
 //! \}
Index: trunk/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncSlice.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncSlice.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -65,8 +65,4 @@
   // encoder configuration
   TEncCfg*                m_pcCfg;                              ///< encoder configuration class
-  
-#if SVC_EXTENSION
-  TEncTop**               m_ppcTEncTop;
-#endif  
 
   // pictures
@@ -107,4 +103,9 @@
   UInt                    m_uiSliceIdx;
   std::vector<TEncSbac*> CTXMem;
+
+#if SVC_EXTENSION
+  TEncTop**               m_ppcTEncTop;
+#endif 
+
 public:
   TEncSlice();
@@ -152,8 +153,9 @@
   Double  xGetQPValueAccordingToLambda ( Double lambda );
 
+#if SVC_EXTENSION
 #if JCTVC_M0259_LAMBDAREFINEMENT
-private:
   Double  xCalEnhLambdaFactor( Double deltaQP , Double beta );
 #endif
+#endif //SVC_EXTENSION
 };
 
Index: trunk/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncTop.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncTop.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -129,5 +129,4 @@
   if (m_bUseSAO)
   {
-#if HM_CLEANUP_SAO
 #if AUXILIARY_PICTURES
     m_cEncSAO.create( getSourceWidth(), getSourceHeight(), m_chromaFormatIDC, g_uiMaxCUWidth, g_uiMaxCUHeight, g_uiMaxCUDepth );
@@ -140,11 +139,4 @@
     m_cEncSAO.createEncData();
 #endif
-#else
-    m_cEncSAO.setSaoLcuBoundary(getSaoLcuBoundary());
-    m_cEncSAO.setSaoLcuBasedOptimization(getSaoLcuBasedOptimization());
-    m_cEncSAO.setMaxNumOffsetsPerPic(getMaxNumOffsetsPerPic());
-    m_cEncSAO.create( getSourceWidth(), getSourceHeight(), g_uiMaxCUWidth, g_uiMaxCUHeight );
-    m_cEncSAO.createEncBuffer();
-#endif
   }
 #if ADAPTIVE_QP_SELECTION
@@ -161,33 +153,30 @@
                       g_uiMaxCUWidth, g_uiMaxCUHeight, m_RCKeepHierarchicalBit, m_RCUseLCUSeparateModel, m_GOPList );
   }
-  // if SBAC-based RD optimization is used
-  if( m_bUseSBACRD )
-  {
-    m_pppcRDSbacCoder = new TEncSbac** [g_uiMaxCUDepth+1];
+
+  m_pppcRDSbacCoder = new TEncSbac** [g_uiMaxCUDepth+1];
 #if FAST_BIT_EST
-    m_pppcBinCoderCABAC = new TEncBinCABACCounter** [g_uiMaxCUDepth+1];
-#else
-    m_pppcBinCoderCABAC = new TEncBinCABAC** [g_uiMaxCUDepth+1];
-#endif
-    
-    for ( Int iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
-    {
-      m_pppcRDSbacCoder[iDepth] = new TEncSbac* [CI_NUM];
+  m_pppcBinCoderCABAC = new TEncBinCABACCounter** [g_uiMaxCUDepth+1];
+#else
+  m_pppcBinCoderCABAC = new TEncBinCABAC** [g_uiMaxCUDepth+1];
+#endif
+
+  for ( Int iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+  {
+    m_pppcRDSbacCoder[iDepth] = new TEncSbac* [CI_NUM];
 #if FAST_BIT_EST
-      m_pppcBinCoderCABAC[iDepth] = new TEncBinCABACCounter* [CI_NUM];
-#else
-      m_pppcBinCoderCABAC[iDepth] = new TEncBinCABAC* [CI_NUM];
-#endif
-      
-      for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
-      {
-        m_pppcRDSbacCoder[iDepth][iCIIdx] = new TEncSbac;
+    m_pppcBinCoderCABAC[iDepth] = new TEncBinCABACCounter* [CI_NUM];
+#else
+    m_pppcBinCoderCABAC[iDepth] = new TEncBinCABAC* [CI_NUM];
+#endif
+
+    for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+    {
+      m_pppcRDSbacCoder[iDepth][iCIIdx] = new TEncSbac;
 #if FAST_BIT_EST
-        m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABACCounter;
-#else
-        m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABAC;
-#endif
-        m_pppcRDSbacCoder   [iDepth][iCIIdx]->init( m_pppcBinCoderCABAC [iDepth][iCIIdx] );
-      }
+      m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABACCounter;
+#else
+      m_pppcBinCoderCABAC [iDepth][iCIIdx] = new TEncBinCABAC;
+#endif
+      m_pppcRDSbacCoder   [iDepth][iCIIdx]->init( m_pppcBinCoderCABAC [iDepth][iCIIdx] );
     }
   }
@@ -226,24 +215,22 @@
     m_pcSbacCoders[ui].init( &m_pcBinCoderCABACs[ui] );
   }
-  if( m_bUseSBACRD )
-  {
-    m_ppppcRDSbacCoders      = new TEncSbac***    [iNumSubstreams];
-    m_ppppcBinCodersCABAC    = new TEncBinCABAC***[iNumSubstreams];
-    for ( UInt ui = 0 ; ui < iNumSubstreams ; ui++ )
-    {
-      m_ppppcRDSbacCoders[ui]  = new TEncSbac** [g_uiMaxCUDepth+1];
-      m_ppppcBinCodersCABAC[ui]= new TEncBinCABAC** [g_uiMaxCUDepth+1];
-      
-      for ( Int iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
-      {
-        m_ppppcRDSbacCoders[ui][iDepth]  = new TEncSbac*     [CI_NUM];
-        m_ppppcBinCodersCABAC[ui][iDepth]= new TEncBinCABAC* [CI_NUM];
-
-        for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
-        {
-          m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx] = new TEncSbac;
-          m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx] = new TEncBinCABAC;
-          m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx]->init( m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx] );
-        }
+
+  m_ppppcRDSbacCoders      = new TEncSbac***    [iNumSubstreams];
+  m_ppppcBinCodersCABAC    = new TEncBinCABAC***[iNumSubstreams];
+  for ( UInt ui = 0 ; ui < iNumSubstreams ; ui++ )
+  {
+    m_ppppcRDSbacCoders[ui]  = new TEncSbac** [g_uiMaxCUDepth+1];
+    m_ppppcBinCodersCABAC[ui]= new TEncBinCABAC** [g_uiMaxCUDepth+1];
+
+    for ( Int iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+    {
+      m_ppppcRDSbacCoders[ui][iDepth]  = new TEncSbac*     [CI_NUM];
+      m_ppppcBinCodersCABAC[ui][iDepth]= new TEncBinCABAC* [CI_NUM];
+
+      for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+      {
+        m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx] = new TEncSbac;
+        m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx] = new TEncBinCABAC;
+        m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx]->init( m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx] );
       }
     }
@@ -259,58 +246,50 @@
   if (m_cSPS.getUseSAO())
   {
-#if HM_CLEANUP_SAO
     m_cEncSAO.destroyEncData();
     m_cEncSAO.destroy();
-#else
-    m_cEncSAO.destroy();
-    m_cEncSAO.destroyEncBuffer();
-#endif
   }
   m_cLoopFilter.        destroy();
   m_cRateCtrl.          destroy();
-  // SBAC RD
-  if( m_bUseSBACRD )
-  {
-    Int iDepth;
+
+  Int iDepth;
+  for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+  {
+    for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
+    {
+      delete m_pppcRDSbacCoder[iDepth][iCIIdx];
+      delete m_pppcBinCoderCABAC[iDepth][iCIIdx];
+    }
+  }
+
+  for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
+  {
+    delete [] m_pppcRDSbacCoder[iDepth];
+    delete [] m_pppcBinCoderCABAC[iDepth];
+  }
+
+  delete [] m_pppcRDSbacCoder;
+  delete [] m_pppcBinCoderCABAC;
+
+  for ( UInt ui = 0; ui < m_iNumSubstreams; ui++ )
+  {
     for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
     {
       for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
       {
-        delete m_pppcRDSbacCoder[iDepth][iCIIdx];
-        delete m_pppcBinCoderCABAC[iDepth][iCIIdx];
-      }
-    }
-    
+        delete m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx];
+        delete m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx];
+      }
+    }
+
     for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
     {
-      delete [] m_pppcRDSbacCoder[iDepth];
-      delete [] m_pppcBinCoderCABAC[iDepth];
-    }
-    
-    delete [] m_pppcRDSbacCoder;
-    delete [] m_pppcBinCoderCABAC;
-
-    for ( UInt ui = 0; ui < m_iNumSubstreams; ui++ )
-    {
-      for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
-      {
-        for (Int iCIIdx = 0; iCIIdx < CI_NUM; iCIIdx ++ )
-        {
-          delete m_ppppcRDSbacCoders  [ui][iDepth][iCIIdx];
-          delete m_ppppcBinCodersCABAC[ui][iDepth][iCIIdx];
-        }
-      }
-
-      for ( iDepth = 0; iDepth < g_uiMaxCUDepth+1; iDepth++ )
-      {
-        delete [] m_ppppcRDSbacCoders  [ui][iDepth];
-        delete [] m_ppppcBinCodersCABAC[ui][iDepth];
-      }
-      delete[] m_ppppcRDSbacCoders  [ui];
-      delete[] m_ppppcBinCodersCABAC[ui];
-    }
-    delete[] m_ppppcRDSbacCoders;
-    delete[] m_ppppcBinCodersCABAC;
-  }
+      delete [] m_ppppcRDSbacCoders  [ui][iDepth];
+      delete [] m_ppppcBinCodersCABAC[ui][iDepth];
+    }
+    delete[] m_ppppcRDSbacCoders  [ui];
+    delete[] m_ppppcBinCodersCABAC[ui];
+  }
+  delete[] m_ppppcRDSbacCoders;
+  delete[] m_ppppcBinCodersCABAC;
   delete[] m_pcSbacCoders;
   delete[] m_pcBinCoderCABACs;
@@ -525,7 +504,4 @@
     TComPic *pcTopField;
     xGetNewPicBuffer( pcTopField );
-#if !HM_CLEANUP_SAO
-    pcTopField->getPicSym()->allocSaoParam(&m_cEncSAO);
-#endif
     pcTopField->setReconMark (false);
     
@@ -568,7 +544,4 @@
     TComPic* pcBottomField;
     xGetNewPicBuffer( pcBottomField );
-#if !HM_CLEANUP_SAO
-    pcBottomField->getPicSym()->allocSaoParam(&m_cEncSAO);
-#endif
     pcBottomField->setReconMark (false);
    
@@ -652,7 +625,4 @@
     TComPic *pcTopField;
     xGetNewPicBuffer( pcTopField );
-#if !HM_CLEANUP_SAO
-    pcTopField->getPicSym()->allocSaoParam(&m_cEncSAO);
-#endif
     pcTopField->setReconMark (false);
     
@@ -706,7 +676,4 @@
     TComPic* pcBottomField;
     xGetNewPicBuffer( pcBottomField );
-#if !HM_CLEANUP_SAO
-    pcBottomField->getPicSym()->allocSaoParam(&m_cEncSAO);
-#endif
     pcBottomField->setReconMark (false);
     
@@ -912,10 +879,4 @@
 #endif
     }
-#if !HM_CLEANUP_SAO
-    if (getUseSAO())
-    {
-      rpcPic->getPicSym()->allocSaoParam(&m_cEncSAO);
-    }
-#endif
     m_cListPic.pushBack( rpcPic );
   }
@@ -1001,5 +962,4 @@
   
   m_cSPS.setTMVPFlagsPresent(false);
-  m_cSPS.setUseLossless   ( m_useLossless  );
 
   m_cSPS.setMaxTrSize   ( 1 << m_uiQuadtreeTULog2MaxSize );
@@ -1038,5 +998,5 @@
   m_cSPS.setMaxTLayers( m_maxTempLayer );
   m_cSPS.setTemporalIdNestingFlag( ( m_maxTempLayer == 1 ) ? true : false );
-  for ( i = 0; i < m_cSPS.getMaxTLayers(); i++ )
+  for ( i = 0; i < min(m_cSPS.getMaxTLayers(),(UInt) MAX_TLAYER); i++ )
   {
     m_cSPS.setMaxDecPicBuffering(m_maxDecPicBuffering[i], i);
@@ -1098,49 +1058,7 @@
   Bool bUseDQP = (getMaxCuDQPDepth() > 0)? true : false;
 
-#if REPN_FORMAT_IN_VPS
-  Int lowestQP;
-#if O0096_REP_FORMAT_INDEX
-  if( m_layerId == 0 )
-  {
-    lowestQP = - m_cSPS.getQpBDOffsetY();
-  }
-  else
-  {
-    lowestQP = - (m_cVPS.getVpsRepFormat( m_cVPS.getVpsRepFormatIdx( m_cSPS.getUpdateRepFormatFlag() ? m_cSPS.getUpdateRepFormatIndex() : m_layerId ) )->getBitDepthVpsLuma() - 8) * 6;
-  }
-#else
-  if( m_layerId == 0 || m_cSPS.getUpdateRepFormatFlag() )
-  {
-    lowestQP = - m_cSPS.getQpBDOffsetY();
-  }
-  else
-  {
-    lowestQP = - (m_cVPS.getVpsRepFormat( m_cVPS.getVpsRepFormatIdx( m_layerId ) )->getBitDepthVpsLuma() - 8) * 6;
-  }
-#endif
-#else
-  Int lowestQP = - m_cSPS.getQpBDOffsetY();
-#endif
-
-  if(getUseLossless())
-  {
-    if ((getMaxCuDQPDepth() == 0) && (getMaxDeltaQP() == 0 ) && (getQP() == lowestQP) )
-    {
-      bUseDQP = false;
-    }
-    else
-    {
-      bUseDQP = true;
-    }
-  }
-  else
-  {
-    if(bUseDQP == false)
-    {
-      if((getMaxDeltaQP() != 0 )|| getUseAdaptiveQP())
-      {
-        bUseDQP = true;
-      }
-    }
+  if((getMaxDeltaQP() != 0 )|| getUseAdaptiveQP())
+  {
+    bUseDQP = true;
   }
 
Index: trunk/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- trunk/source/Lib/TLibEncoder/TEncTop.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/TEncTop.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -73,12 +73,5 @@
   UInt                    m_uiNumAllPicCoded;             ///< number of coded pictures
   TComList<TComPic*>      m_cListPic;                     ///< dynamic list of pictures
-#if SVC_EXTENSION 
-  static Int              m_iSPSIdCnt;                    ///< next Id number for SPS    
-  static Int              m_iPPSIdCnt;                    ///< next Id number for PPS    
-#if AVC_SYNTAX
-  fstream*                m_pBLSyntaxFile;
-#endif
-#endif
-  
+ 
   // encoder search
   TEncSearch              m_cSearch;                      ///< encoder search class
@@ -130,5 +123,9 @@
   
 #if SVC_EXTENSION
-
+  static Int              m_iSPSIdCnt;                    ///< next Id number for SPS    
+  static Int              m_iPPSIdCnt;                    ///< next Id number for PPS    
+#if AVC_SYNTAX
+  fstream*                m_pBLSyntaxFile;
+#endif
   TEncTop**               m_ppcTEncTop;
   TEncTop*                getLayerEnc(UInt layer)   { return m_ppcTEncTop[layer]; }
@@ -163,5 +160,5 @@
   Void  xInitRPS          (Bool isFieldCoding);           ///< initialize PPS from encoder options
 #if SVC_EXTENSION
-  Void xInitILRP();
+  Void  xInitILRP();
 #endif
 public:
@@ -210,4 +207,9 @@
   Int getReferencePictureSetIdxForSOP(TComSlice* slice, Int POCCurr, Int GOPid );
   TComScalingList*        getScalingList        () { return  &m_scalingList;         }
+  // -------------------------------------------------------------------------------------------------------------------
+  // encoder function
+  // -------------------------------------------------------------------------------------------------------------------
+
+  /// encode several number of pictures until end-of-sequence
 #if SVC_EXTENSION
   Void                    setLayerEnc(TEncTop** p) {m_ppcTEncTop = p;}
@@ -224,12 +226,4 @@
 #endif
   Window&  getScaledRefLayerWindow(Int x)            { return m_scaledRefLayerWindow[x]; }
-#endif //SVC_EXTENSION
-
-  // -------------------------------------------------------------------------------------------------------------------
-  // encoder function
-  // -------------------------------------------------------------------------------------------------------------------
-
-  /// encode several number of pictures until end-of-sequence
-#if SVC_EXTENSION
   TComPic** getIlpList() { return m_cIlpPic; }
 #if REF_IDX_MFM
@@ -281,2 +275,3 @@
 
 #endif // __TENCTOP__
+
Index: trunk/source/Lib/TLibEncoder/WeightPredAnalysis.cpp
===================================================================
--- trunk/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 588)
+++ trunk/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibEncoder/WeightPredAnalysis.h
===================================================================
--- trunk/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 588)
+++ trunk/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibVideoIO/TVideoIOYuv.cpp
===================================================================
--- trunk/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 588)
+++ trunk/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/TLibVideoIO/TVideoIOYuv.h
===================================================================
--- trunk/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 588)
+++ trunk/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/libmd5/MD5.h
===================================================================
--- trunk/source/Lib/libmd5/MD5.h	(revision 588)
+++ trunk/source/Lib/libmd5/MD5.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
Index: trunk/source/Lib/libmd5/libmd5.h
===================================================================
--- trunk/source/Lib/libmd5/libmd5.h	(revision 588)
+++ trunk/source/Lib/libmd5/libmd5.h	(revision 595)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
- * Copyright (c) 2010-2013, ITU/ISO/IEC
+ * Copyright (c) 2010-2014, ITU/ISO/IEC
  * All rights reserved.
  *
