Index: /trunk/build/linux/app/TAppEncoder/makefile
===================================================================
--- /trunk/build/linux/app/TAppEncoder/makefile	(revision 1412)
+++ /trunk/build/linux/app/TAppEncoder/makefile	(revision 1413)
@@ -57,4 +57,14 @@
 STAT_RELEASE_PREREQS	= $(LIB_DIR)/libTLibEncoder$(HBD)Static.a $(LIB_DIR)/libTLibCommon$(HBD)Static.a $(LIB_DIR)/libTLibVideoIO$(HBD)Static.a $(LIB_DIR)/libTAppCommon$(HBD)Static.a  $(LIB_DIR)/libTLibRenderer$(HBD)Static.a
 
+ifeq ($(EXTENSION_360_VIDEO), 1)
+  DYN_DEBUG_LIBS      += -lTAppEncHelper360$(HBD)d -lTLib360$(HBD)d
+  DYN_DEBUG_PREREQS   += $(LIB_DIR)/libTAppEncHelper360$(HBD)d.a $(LIB_DIR)/libTLib360$(HBD)d.a
+  STAT_DEBUG_LIBS     += -lTAppEncHelper360$(HBD)Staticd -lTLib360$(HBD)Staticd
+  STAT_DEBUG_PREREQS  += $(LIB_DIR)/libTAppEncHelper360$(HBD)Staticd.a $(LIB_DIR)/libTLib360$(HBD)Staticd.a
+  DYN_RELEASE_LIBS    += -lTAppEncHelper360$(HBD) -lTLib360$(HBD)
+  DYN_RELEASE_PREREQS += $(LIB_DIR)/libTAppEncHelper360$(HBD).a $(LIB_DIR)/libTLib360$(HBD).a
+  STAT_RELEASE_LIBS   += -lTAppEncHelper360$(HBD)Static -lTLib360$(HBD)Static
+  STAT_RELEASE_PREREQS+= $(LIB_DIR)/libTAppEncHelper360$(HBD)Static.a $(LIB_DIR)/libTLib360$(HBD)Static.a
+endif
 
 # name of the base makefile
Index: /trunk/build/linux/common/makefile.base
===================================================================
--- /trunk/build/linux/common/makefile.base	(revision 1412)
+++ /trunk/build/linux/common/makefile.base	(revision 1413)
@@ -47,6 +47,6 @@
 
 # default cpp flags for all configurations
-#CPPFLAGS          = -Wall -fPIC $(DEFS) -I$(CURDIR)/$(INC_DIR) $(USER_INC_DIRS)
-CPPFLAGS          = -fPIC $(DEFS)  $(ADDDEFS) -I$(CURDIR)/$(INC_DIR) $(USER_INC_DIRS) -Wall -Wshadow -Wno-sign-compare -Werror
+#CPPFLAGS          = -Wall $(DEFS) -I$(CURDIR)/$(INC_DIR) $(USER_INC_DIRS)
+CPPFLAGS          = $(DEFS) $(ADDDEFS) -I$(CURDIR)/$(INC_DIR) $(USER_INC_DIRS) -Wall -Wshadow -Wno-sign-compare -Werror
 
 ########## 
@@ -61,4 +61,10 @@
 ifeq ($(HIGHBITDEPTH), 1)
 CPPFLAGS+="-DRExt__HIGH_BIT_DEPTH_SUPPORT=1"
+endif
+
+ifeq ($(EXTENSION_360_VIDEO), 1)
+  CPPFLAGS+=-DEXTENSION_360_VIDEO=1
+else
+  CPPFLAGS+=-DEXTENSION_360_VIDEO=0
 endif
 
Index: /trunk/build/linux/lib/TLibDecoder/makefile
===================================================================
--- /trunk/build/linux/lib/TLibDecoder/makefile	(revision 1412)
+++ /trunk/build/linux/lib/TLibDecoder/makefile	(revision 1413)
@@ -51,4 +51,5 @@
 				$(OBJ_DIR)/TDecSlice.o \
 				$(OBJ_DIR)/TDecTop.o \
+				$(OBJ_DIR)/TDecConformance.o \
 
 LIBS				= -lpthread
Index: /trunk/build/linux/lib/TLibDecoderAnalyser/makefile
===================================================================
--- /trunk/build/linux/lib/TLibDecoderAnalyser/makefile	(revision 1412)
+++ /trunk/build/linux/lib/TLibDecoderAnalyser/makefile	(revision 1413)
@@ -51,4 +51,5 @@
 				$(OBJ_DIR)/TDecSlice.o \
 				$(OBJ_DIR)/TDecTop.o \
+				$(OBJ_DIR)/TDecConformance.o \
 
 LIBS				= -lpthread
Index: /trunk/build/linux/makefile
===================================================================
--- /trunk/build/linux/makefile	(revision 1412)
+++ /trunk/build/linux/makefile	(revision 1413)
@@ -9,4 +9,8 @@
 endif
 
+EXTENSION_360_VIDEO?=0
+export EXTENSION_360_VIDEO
+
+
 all:
 	$(MAKE) -C lib/TLibVideoIO 	MM32=$(M32) ADDDEFS=$(ADDDEFS)
@@ -17,4 +21,9 @@
 	$(MAKE) -C lib/TLibExtractor    MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C lib/TAppCommon       MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	@if [ $(EXTENSION_360_VIDEO) -eq 1 ] ; then \
+	  $(MAKE) -C lib/TLib360                MM32=$(M32) ; \
+	  $(MAKE) -C lib/TAppEncHelper360       MM32=$(M32) ; \
+	  $(MAKE) -C app/TApp360Convert         MM32=$(M32) ; \
+	fi
 	$(MAKE) -C app/TAppDecoder      MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C app/TAppEncoder      MM32=$(M32) ADDDEFS=$(ADDDEFS)
@@ -34,4 +43,10 @@
 	$(MAKE) -C lib/TLibExtractor    debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C lib/TAppCommon       debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	@if [ $(EXTENSION_360_VIDEO) -eq 1 ] ; then \
+	  $(MAKE) -C lib/TLib360                debug MM32=$(M32) ; \
+	  $(MAKE) -C lib/TAppEncHelper360       debug MM32=$(M32) ; \
+	  $(MAKE) -C app/TApp360Convert         debug MM32=$(M32) ; \
+	fi
+
 	$(MAKE) -C app/TAppDecoder      debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C app/TAppEncoder      debug MM32=$(M32) ADDDEFS=$(ADDDEFS)
@@ -51,4 +66,9 @@
 	$(MAKE) -C lib/TLibExtractor    release MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C lib/TAppCommon       release MM32=$(M32) ADDDEFS=$(ADDDEFS)
+	@if [ $(EXTENSION_360_VIDEO) -eq 1 ] ; then \
+	  $(MAKE) -C lib/TLib360                release MM32=$(M32) ; \
+	  $(MAKE) -C lib/TAppEncHelper360       release MM32=$(M32) ; \
+	  $(MAKE) -C app/TApp360Convert         release MM32=$(M32) ; \
+	fi
 	$(MAKE) -C app/TAppDecoder      release MM32=$(M32) ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C app/TAppEncoder      release MM32=$(M32) ADDDEFS=$(ADDDEFS)
@@ -69,4 +89,10 @@
 
 	$(MAKE) -C lib/TAppCommon       clean MM32=$(M32)
+	@if [ $(EXTENSION_360_VIDEO) -eq 1 ] ; then \
+	  $(MAKE) -C lib/TLib360                  clean MM32=$(M32) ; \
+	  $(MAKE) -C lib/TAppEncHelper360         clean MM32=$(M32) ; \
+	  $(MAKE) -C app/TApp360Convert           clean MM32=$(M32) ; \
+	fi
+
 	$(MAKE) -C app/TAppDecoder      clean MM32=$(M32)
 	$(MAKE) -C app/TAppEncoder      clean MM32=$(M32)
@@ -86,4 +112,10 @@
 	$(MAKE) -C lib/TLibExtractor    MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C lib/TAppCommon       MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	@if [ $(EXTENSION_360_VIDEO) -eq 1 ] ; then \
+	  $(MAKE) -C lib/TLib360                MM32=$(M32) HIGHBITDEPTH=1 ; \
+	  $(MAKE) -C lib/TAppEncHelper360       MM32=$(M32) HIGHBITDEPTH=1 ; \
+	  $(MAKE) -C app/TApp360Convert         MM32=$(M32) HIGHBITDEPTH=1 ; \
+	fi
+
 	$(MAKE) -C app/TAppDecoder      MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C app/TAppEncoder      MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
@@ -101,4 +133,9 @@
 	$(MAKE) -C lib/TLibExtractor    debug M32=$(M32)  HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C lib/TAppCommon       debug MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	@if [ $(EXTENSION_360_VIDEO) -eq 1 ] ; then \
+	  $(MAKE) -C lib/TLib360                debug MM32=$(M32) HIGHBITDEPTH=1 ; \
+	  $(MAKE) -C lib/TAppEncHelper360       debug MM32=$(M32) HIGHBITDEPTH=1 ; \
+	  $(MAKE) -C app/TApp360Convert         debug MM32=$(M32) HIGHBITDEPTH=1 ; \
+	fi
 	$(MAKE) -C app/TAppDecoder      debug MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C app/TAppEncoder      debug MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
@@ -116,4 +153,9 @@
 	$(MAKE) -C lib/TLibExtractor    release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C lib/TAppCommon       release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
+	@if [ $(EXTENSION_360_VIDEO) -eq 1 ] ; then \
+	  $(MAKE) -C lib/TLib360                release MM32=$(M32) HIGHBITDEPTH=1 ; \
+	  $(MAKE) -C lib/TAppEncHelper360       release MM32=$(M32) HIGHBITDEPTH=1 ; \
+	  $(MAKE) -C app/TApp360Convert         release MM32=$(M32) HIGHBITDEPTH=1 ; \
+	fi
 	$(MAKE) -C app/TAppDecoder      release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
 	$(MAKE) -C app/TAppEncoder      release MM32=$(M32) HIGHBITDEPTH=1 ADDDEFS=$(ADDDEFS)
@@ -131,4 +173,9 @@
 	$(MAKE) -C lib/TLibExtractor    clean MM32=$(M32) HIGHBITDEPTH=1  
 	$(MAKE) -C lib/TAppCommon       clean MM32=$(M32) HIGHBITDEPTH=1
+	@if [ $(EXTENSION_360_VIDEO) -eq 1 ] ; then \
+	  $(MAKE) -C lib/TLib360                  clean MM32=$(M32) HIGHBITDEPTH=1 ; \
+	  $(MAKE) -C lib/TAppEncHelper360         clean MM32=$(M32) HIGHBITDEPTH=1 ; \
+	  $(MAKE) -C app/TApp360Convert           clean MM32=$(M32) HIGHBITDEPTH=1 ; \
+	fi
 	$(MAKE) -C app/TAppDecoder      clean MM32=$(M32) HIGHBITDEPTH=1
 	$(MAKE) -C app/TAppEncoder      clean MM32=$(M32) HIGHBITDEPTH=1
Index: /trunk/build/vc2010/TAppDecoderAnalyser_vc2010.vcxproj
===================================================================
--- /trunk/build/vc2010/TAppDecoderAnalyser_vc2010.vcxproj	(revision 1412)
+++ /trunk/build/vc2010/TAppDecoderAnalyser_vc2010.vcxproj	(revision 1413)
@@ -186,5 +186,5 @@
     </ProjectReference>
     <ProjectReference Include="TLibDecoderAnalyser_vc2010.vcxproj">
-      <Project>{f8b77a48-af6c-4746-a89f-b706aba6ad94}</Project>
+      <Project>{68C1251A-55D8-47C9-9052-62F785BD437A}</Project>
       <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
     </ProjectReference>
Index: /trunk/build/vc2010/TLibDecoderAnalyser_vc2010.vcxproj
===================================================================
--- /trunk/build/vc2010/TLibDecoderAnalyser_vc2010.vcxproj	(revision 1412)
+++ /trunk/build/vc2010/TLibDecoderAnalyser_vc2010.vcxproj	(revision 1413)
@@ -150,4 +150,5 @@
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecConformance.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp" />
@@ -165,4 +166,5 @@
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecConformance.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h" />
Index: /trunk/build/vc2010/TLibDecoder_vc2010.vcxproj
===================================================================
--- /trunk/build/vc2010/TLibDecoder_vc2010.vcxproj	(revision 1412)
+++ /trunk/build/vc2010/TLibDecoder_vc2010.vcxproj	(revision 1413)
@@ -150,4 +150,5 @@
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecConformance.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp" />
@@ -165,4 +166,5 @@
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecConformance.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h" />
Index: /trunk/build/vc2012/TAppDecoderAnalyser_vc2012.vcxproj
===================================================================
--- /trunk/build/vc2012/TAppDecoderAnalyser_vc2012.vcxproj	(revision 1412)
+++ /trunk/build/vc2012/TAppDecoderAnalyser_vc2012.vcxproj	(revision 1413)
@@ -190,5 +190,5 @@
     </ProjectReference>
     <ProjectReference Include="TLibDecoderAnalyser_vc2012.vcxproj">
-      <Project>{f8b77a48-af6c-4746-a89f-b706aba6ad94}</Project>
+      <Project>{68C1251A-55D8-47C9-9052-62F785BD437A}</Project>
       <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
     </ProjectReference>
Index: /trunk/build/vc2012/TLibDecoderAnalyser_vc2012.vcxproj
===================================================================
--- /trunk/build/vc2012/TLibDecoderAnalyser_vc2012.vcxproj	(revision 1412)
+++ /trunk/build/vc2012/TLibDecoderAnalyser_vc2012.vcxproj	(revision 1413)
@@ -154,4 +154,5 @@
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecConformance.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp" />
@@ -169,4 +170,5 @@
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecConformance.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h" />
Index: /trunk/build/vc2012/TLibDecoder_vc2012.vcxproj
===================================================================
--- /trunk/build/vc2012/TLibDecoder_vc2012.vcxproj	(revision 1412)
+++ /trunk/build/vc2012/TLibDecoder_vc2012.vcxproj	(revision 1413)
@@ -154,4 +154,5 @@
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecConformance.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp" />
@@ -169,4 +170,5 @@
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecConformance.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h" />
Index: /trunk/build/vc2013/TAppDecoderAnalyser_vc2013.vcxproj
===================================================================
--- /trunk/build/vc2013/TAppDecoderAnalyser_vc2013.vcxproj	(revision 1412)
+++ /trunk/build/vc2013/TAppDecoderAnalyser_vc2013.vcxproj	(revision 1413)
@@ -190,5 +190,5 @@
     </ProjectReference>
     <ProjectReference Include="TLibDecoderAnalyser_vc2013.vcxproj">
-      <Project>{f8b77a48-af6c-4746-a89f-b706aba6ad94}</Project>
+      <Project>{68C1251A-55D8-47C9-9052-62F785BD437A}</Project>
       <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
     </ProjectReference>
Index: /trunk/build/vc2013/TLibDecoderAnalyser_vc2013.vcxproj
===================================================================
--- /trunk/build/vc2013/TLibDecoderAnalyser_vc2013.vcxproj	(revision 1412)
+++ /trunk/build/vc2013/TLibDecoderAnalyser_vc2013.vcxproj	(revision 1413)
@@ -154,4 +154,5 @@
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecConformance.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp" />
@@ -169,4 +170,5 @@
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecConformance.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h" />
Index: /trunk/build/vc2013/TLibDecoder_vc2013.vcxproj
===================================================================
--- /trunk/build/vc2013/TLibDecoder_vc2013.vcxproj	(revision 1412)
+++ /trunk/build/vc2013/TLibDecoder_vc2013.vcxproj	(revision 1413)
@@ -154,4 +154,5 @@
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecConformance.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp" />
@@ -169,4 +170,5 @@
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecConformance.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h" />
Index: /trunk/build/vc2015/TAppDecoderAnalyser_vc2015.vcxproj
===================================================================
--- /trunk/build/vc2015/TAppDecoderAnalyser_vc2015.vcxproj	(revision 1412)
+++ /trunk/build/vc2015/TAppDecoderAnalyser_vc2015.vcxproj	(revision 1413)
@@ -191,5 +191,5 @@
     </ProjectReference>
     <ProjectReference Include="TLibDecoderAnalyser_vc2015.vcxproj">
-      <Project>{f8b77a48-af6c-4746-a89f-b706aba6ad94}</Project>
+      <Project>{68C1251A-55D8-47C9-9052-62F785BD437A}</Project>
       <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
     </ProjectReference>
Index: /trunk/build/vc2015/TLibCommon_vc2015.vcxproj
===================================================================
--- /trunk/build/vc2015/TLibCommon_vc2015.vcxproj	(revision 1412)
+++ /trunk/build/vc2015/TLibCommon_vc2015.vcxproj	(revision 1413)
@@ -172,5 +172,7 @@
     <ClCompile Include="..\..\source\Lib\TLibCommon\TComSampleAdaptiveOffset.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibCommon\TComSlice.cpp" />
-    <ClCompile Include="..\..\source\Lib\TLibCommon\TComTrQuant.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibCommon\TComTrQuant.cpp" >
+      <AdditionalOptions Condition="'$(Configuration)|$(Platform)'=='Release|x64'">/d2Qvec-sse2only %(AdditionalOptions)</AdditionalOptions>
+    </ClCompile>
     <ClCompile Include="..\..\source\Lib\TLibCommon\TComTU.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibCommon\TComWedgelet.cpp" />
Index: /trunk/build/vc2015/TLibDecoderAnalyser_vc2015.vcxproj
===================================================================
--- /trunk/build/vc2015/TLibDecoderAnalyser_vc2015.vcxproj	(revision 1412)
+++ /trunk/build/vc2015/TLibDecoderAnalyser_vc2015.vcxproj	(revision 1413)
@@ -155,4 +155,5 @@
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecConformance.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp" />
@@ -170,4 +171,5 @@
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecConformance.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h" />
Index: /trunk/build/vc2015/TLibDecoder_vc2015.vcxproj
===================================================================
--- /trunk/build/vc2015/TLibDecoder_vc2015.vcxproj	(revision 1412)
+++ /trunk/build/vc2015/TLibDecoder_vc2015.vcxproj	(revision 1413)
@@ -155,4 +155,5 @@
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.cpp" />
+    <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecConformance.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecCu.cpp" />
     <ClCompile Include="..\..\source\Lib\TLibDecoder\TDecEntropy.cpp" />
@@ -170,4 +171,5 @@
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecBinCoderCABAC.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCAVLC.h" />
+    <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecConformance.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecCu.h" />
     <ClInclude Include="..\..\source\Lib\TLibDecoder\TDecEntropy.h" />
Index: /trunk/cfg/3D-HEVC/NonCTC/misc/fullCfg_31view.cfg
===================================================================
--- /trunk/cfg/3D-HEVC/NonCTC/misc/fullCfg_31view.cfg	(revision 1413)
+++ /trunk/cfg/3D-HEVC/NonCTC/misc/fullCfg_31view.cfg	(revision 1413)
@@ -0,0 +1,669 @@
+#======== Legend for comments ===================== 
+# (m) specification per layer/dimension/layerset possible
+# (c) cyclic repetition of values, if not given for all layers/dimensions/layersets. (e.g. 5 layers and 1 2 3 -> 1 2 3 1 2  )
+
+#======== File I/O =====================
+
+InputFile_0                   :                              
+InputFile_1                   : 
+InputFile_2                   : 
+InputFile_3                   : 
+InputFile_4                   : 
+InputFile_5                   : 
+InputFile_6                   : 
+InputFile_7                   : 
+InputFile_8                   : 
+InputFile_9                   : 
+InputFile_10                  : 
+InputFile_11                  : 
+InputFile_12                  : 
+InputFile_13                  : 
+InputFile_14                  : 
+InputFile_15                  : 
+InputFile_16                  : 
+InputFile_17                  : 
+InputFile_18                  : 
+InputFile_19                  : 
+InputFile_20                  : 
+InputFile_21                  : 
+InputFile_22                  : 
+InputFile_23                  : 
+InputFile_24                  : 
+InputFile_25                  : 
+InputFile_26                  : 
+InputFile_27                  : 
+InputFile_28                  : 
+InputFile_29                  : 
+InputFile_30                  : 
+InputFile_31                  : 
+InputFile_32                  : 
+InputFile_33                  : 
+InputFile_34                  : 
+InputFile_35                  : 
+InputFile_36                  : 
+InputFile_37                  : 
+InputFile_38                  : 
+InputFile_39                  : 
+InputFile_40                  : 
+InputFile_41                  : 
+InputFile_42                  : 
+InputFile_43                  : 
+InputFile_44                  : 
+InputFile_45                  : 
+InputFile_46                  : 
+InputFile_47                  : 
+InputFile_48                  : 
+InputFile_49                  : 
+InputFile_50                  : 
+InputFile_51                  : 
+InputFile_52                  : 
+InputFile_53                  : 
+InputFile_54                  : 
+InputFile_55                  : 
+InputFile_56                  : 
+InputFile_57                  : 
+InputFile_58                  : 
+InputFile_59                  : 
+InputFile_60                  : 
+InputFile_61                  : 
+InputFile_62                  : 
+InputFile_63                  :
+InputFile_64                  :
+InputFile_65                  :
+InputFile_66                  :
+InputFile_67                  :
+InputFile_68                  :
+InputFile_69                  :
+InputFile_70                  :
+InputFile_71                  :
+InputFile_72                  :
+InputFile_73                  :
+InputFile_74                  :
+InputFile_75                  :
+InputFile_76                  :
+InputFile_77                  :
+InputFile_78                  :
+InputFile_79                  :
+InputFile_80                  :
+InputFile_81                  :
+InputFile_82                  :
+InputFile_83                  :
+InputFile_84                  :
+InputFile_85                  :
+InputFile_86                  :
+InputFile_87                  :
+InputFile_88                  :
+InputFile_89                  :
+InputFile_90                  :
+InputFile_91                  :
+InputFile_92                  :
+InputFile_93                  :
+InputFile_94                  :
+InputFile_95                  :
+InputFile_96                  :
+InputFile_97                  :
+InputFile_98                  :
+InputFile_99                  :
+InputFile_100                 :
+InputFile_101                 :
+InputFile_102                 :
+InputFile_103                 :
+InputFile_104                 :
+InputFile_105                 :
+InputFile_106                 :
+InputFile_107                 :
+InputFile_108                 :
+InputFile_109                 :
+InputFile_110                 :
+InputFile_111                 :
+InputFile_112                 :
+InputFile_113                 :
+InputFile_114                 :
+InputFile_115                 :
+InputFile_116                 :
+InputFile_117                 :
+InputFile_118                 :
+InputFile_119                 :
+InputFile_120                 :
+InputFile_121                 :
+InputFile_122                 :
+InputFile_123                 :
+InputFile_124                 :
+InputFile_125                 :
+InputFile_126                 :
+InputFile_127                 :
+
+
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   :                              
+ReconFile_1                   : 
+ReconFile_2                   : 
+ReconFile_3                   : 
+ReconFile_4                   : 
+ReconFile_5                   : 
+ReconFile_6                   : 
+ReconFile_7                   : 
+ReconFile_8                   : 
+ReconFile_9                   : 
+ReconFile_10                  : 
+ReconFile_11                  : 
+ReconFile_12                  : 
+ReconFile_13                  : 
+ReconFile_14                  : 
+ReconFile_15                  : 
+ReconFile_16                  : 
+ReconFile_17                  : 
+ReconFile_18                  : 
+ReconFile_19                  : 
+ReconFile_20                  : 
+ReconFile_21                  : 
+ReconFile_22                  : 
+ReconFile_23                  : 
+ReconFile_24                  : 
+ReconFile_25                  : 
+ReconFile_26                  : 
+ReconFile_27                  : 
+ReconFile_28                  : 
+ReconFile_29                  : 
+ReconFile_30                  : 
+ReconFile_31                  : 
+ReconFile_32                  : 
+ReconFile_33                  : 
+ReconFile_34                  : 
+ReconFile_35                  : 
+ReconFile_36                  : 
+ReconFile_37                  : 
+ReconFile_38                  : 
+ReconFile_39                  : 
+ReconFile_40                  : 
+ReconFile_41                  : 
+ReconFile_42                  : 
+ReconFile_43                  : 
+ReconFile_44                  : 
+ReconFile_45                  : 
+ReconFile_46                  : 
+ReconFile_47                  : 
+ReconFile_48                  : 
+ReconFile_49                  : 
+ReconFile_50                  : 
+ReconFile_51                  : 
+ReconFile_52                  : 
+ReconFile_53                  : 
+ReconFile_54                  : 
+ReconFile_55                  : 
+ReconFile_56                  : 
+ReconFile_57                  : 
+ReconFile_58                  : 
+ReconFile_59                  : 
+ReconFile_60                  : 
+ReconFile_61                  : 
+ReconFile_62                  : 
+ReconFile_63                  :
+ReconFile_64                  :
+ReconFile_65                  :
+ReconFile_66                  :
+ReconFile_67                  :
+ReconFile_68                  :
+ReconFile_69                  :
+ReconFile_70                  :
+ReconFile_71                  :
+ReconFile_72                  :
+ReconFile_73                  :
+ReconFile_74                  :
+ReconFile_75                  :
+ReconFile_76                  :
+ReconFile_77                  :
+ReconFile_78                  :
+ReconFile_79                  :
+ReconFile_80                  :
+ReconFile_81                  :
+ReconFile_82                  :
+ReconFile_83                  :
+ReconFile_84                  :
+ReconFile_85                  :
+ReconFile_86                  :
+ReconFile_87                  :
+ReconFile_88                  :
+ReconFile_89                  :
+ReconFile_90                  :
+ReconFile_91                  :
+ReconFile_92                  :
+ReconFile_93                  :
+ReconFile_94                  :
+ReconFile_95                  :
+ReconFile_96                  :
+ReconFile_97                  :
+ReconFile_98                  :
+ReconFile_99                  :
+ReconFile_100                 :
+ReconFile_101                 :
+ReconFile_102                 :
+ReconFile_103                 :
+ReconFile_104                 :
+ReconFile_105                 :
+ReconFile_106                 :
+ReconFile_107                 :
+ReconFile_108                 :
+ReconFile_109                 :
+ReconFile_110                 :
+ReconFile_111                 :
+ReconFile_112                 :
+ReconFile_113                 :
+ReconFile_114                 :
+ReconFile_115                 :
+ReconFile_116                 :
+ReconFile_117                 :
+ReconFile_118                 :
+ReconFile_119                 :
+ReconFile_120                 :
+ReconFile_121                 :
+ReconFile_122                 :
+ReconFile_123                 :
+ReconFile_124                 :
+ReconFile_125                 :
+ReconFile_126                 :
+ReconFile_127                 :
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+NumberOfLayers                : 62          # Number of layers
+
+TargetEncLayerIdList          :             # Layer Id in Nuh to be encoded, (empty:-> all layers will be encode) 
+
+FramesToBeEncoded             : 3           # Number of frames to be coded
+FrameRate                     : 30          # Frame Rate per second
+SourceWidth                   : 1024        # Input  frame width
+SourceHeight                  : 768         # Input  frame height
+
+
+OutputVpsInfo                 : 0           # Output VPS information
+
+
+#======== VPS ============================
+ScalabilityMask               : 3           # Scalability Mask             ( 2: View Scalability, 3: View + Depth Scalability )
+DimensionIdLen                : 1 8           # Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex                : 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18 19 19 20 20 21 21 22 22 23 23 24 24 25 25 26 26 27 27 28 28 29 29 30 30         # ViewOrderIndex, per layer (m)
+LayerIdInNuh                  : 0           # Layer Id in NAL unit header, (0: no explicit signalling, otherwise per layer ) (m)
+SplittingFlag                 : 0           # Splitting Flag 
+
+DepthFlag                     :   0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1  # DepthFlag  (m) 
+ViewId                        : 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18 19 19 20 20 21 21 22 22 23 23 24 24 25 25 26 26 27 27 28 28 29 29 30 30
+AuxId                         :             # Auxiliary Id, per layer (m)
+
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 2            # Number of layer sets    
+LayerIdsInSet_0               : 0            # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61# Indices in VPS of layers in layer set 1
+
+
+ShareParameterSets            : 1
+
+
+
+
+
+#======== VPS / Output layer sets ================
+DefaultTargetOutputLayerIdc   : 0            # Specifies output layers of layer sets, 0: output all layers, 1: output highest layer, 2: specified by LayerIdsInDefOutputLayerSet
+
+OutputLayerSetIdx             :              # Indices of layer sets used to derive additional output layer sets
+
+#======== VPS / PTLI ================
+Profile                       : main main 3d-main   # Profile indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+Level                         : none none none             # Level   indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+Tier                          : main main main             # Tier    indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+InblFlag                      : 0    0    0                # Inbl    indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+
+ProfileTierLevelIdx_0         : 1                          # VpsProfileTierLevel indices of layers in output layer set 0 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_1         : 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1              : 0           # Indices in VPS of direct reference layers 
+DirectRefLayers_2              : 0  1
+DirectRefLayers_3              : 1  2
+DirectRefLayers_4              : 2  3
+DirectRefLayers_5              : 3  4
+DirectRefLayers_6              : 4  5
+DirectRefLayers_7              : 5  6
+DirectRefLayers_8              : 0  1
+DirectRefLayers_9              : 1  8
+DirectRefLayers_10             : 8  9
+DirectRefLayers_11             : 9  10
+DirectRefLayers_12             : 10  11
+DirectRefLayers_13             : 11  12
+DirectRefLayers_14             : 12  13
+DirectRefLayers_15             : 13  14
+DirectRefLayers_16             : 0   1 
+DirectRefLayers_17             : 1   16
+DirectRefLayers_18             : 16  17
+DirectRefLayers_19             : 17  18
+DirectRefLayers_20             : 18  19
+DirectRefLayers_21             : 19  20
+DirectRefLayers_22             : 20  21
+DirectRefLayers_23             : 21  22
+DirectRefLayers_24             : 0   1 
+DirectRefLayers_25             : 1   24
+DirectRefLayers_26             : 24  25
+DirectRefLayers_27             : 25  26
+DirectRefLayers_28             : 26  27
+DirectRefLayers_29             : 27  28
+DirectRefLayers_30             : 28  29
+DirectRefLayers_31             : 29  30
+DirectRefLayers_32             : 0   1  
+DirectRefLayers_33             : 1   32
+DirectRefLayers_34             : 32  33
+DirectRefLayers_35             : 33  34
+DirectRefLayers_36             : 34  35
+DirectRefLayers_37             : 35  36
+DirectRefLayers_38             : 36  37
+DirectRefLayers_39             : 37  38
+DirectRefLayers_40             : 0  1
+DirectRefLayers_41             : 1  40
+DirectRefLayers_42             : 40  41
+DirectRefLayers_43             : 41  42
+DirectRefLayers_44             : 42  43
+DirectRefLayers_45             : 43  44
+DirectRefLayers_46             : 44  45
+DirectRefLayers_47             : 45  46
+DirectRefLayers_48             :  0   1  
+DirectRefLayers_49             :  1  48
+DirectRefLayers_50             : 48  49
+DirectRefLayers_51             : 49  50
+DirectRefLayers_52             : 50  51
+DirectRefLayers_53             : 51  52
+DirectRefLayers_54             : 52  53
+DirectRefLayers_55             : 53  54
+DirectRefLayers_56             :  0   1  
+DirectRefLayers_57             :  1  56
+DirectRefLayers_58             : 56  57
+DirectRefLayers_59             : 57  58
+DirectRefLayers_60             : 58  59
+DirectRefLayers_61             : 59  60
+
+
+DependencyTypes_1              : 6
+DependencyTypes_2              : 2 0
+DependencyTypes_3              : 2 6
+DependencyTypes_4              : 2 0
+DependencyTypes_5              : 2 6
+DependencyTypes_6              : 2 0
+DependencyTypes_7              : 2 6
+DependencyTypes_8              : 2 0
+DependencyTypes_9              : 2 6
+DependencyTypes_10             : 2 0
+DependencyTypes_11             : 2 6
+DependencyTypes_12             : 2 0
+DependencyTypes_13             : 2 6
+DependencyTypes_14             : 2 0
+DependencyTypes_15             : 2 6
+DependencyTypes_16             : 2 0
+DependencyTypes_17             : 2 6
+DependencyTypes_18             : 2 0
+DependencyTypes_19             : 2 6
+DependencyTypes_20             : 2 0
+DependencyTypes_21             : 2 6
+DependencyTypes_22             : 2 0
+DependencyTypes_23             : 2 6
+DependencyTypes_24             : 2 0
+DependencyTypes_25             : 2 6
+DependencyTypes_26             : 2 0
+DependencyTypes_27             : 2 6
+DependencyTypes_28             : 2 0
+DependencyTypes_29             : 2 6
+DependencyTypes_30             : 2 0
+DependencyTypes_31             : 2 6
+DependencyTypes_32             : 2 0
+DependencyTypes_33             : 2 6
+DependencyTypes_34             : 2 0
+DependencyTypes_35             : 2 6
+DependencyTypes_36             : 2 0
+DependencyTypes_37             : 2 6
+DependencyTypes_38             : 2 0
+DependencyTypes_39             : 2 6
+DependencyTypes_40             : 2 0
+DependencyTypes_41             : 2 6
+DependencyTypes_42             : 2 0
+DependencyTypes_43             : 2 6
+DependencyTypes_44             : 2 0
+DependencyTypes_45             : 2 6
+DependencyTypes_46             : 2 0
+DependencyTypes_47             : 2 6
+DependencyTypes_48             : 2 0
+DependencyTypes_49             : 2 6
+DependencyTypes_50             : 2 0
+DependencyTypes_51             : 2 6
+DependencyTypes_52             : 2 0
+DependencyTypes_53             : 2 6
+DependencyTypes_54             : 2 0
+DependencyTypes_55             : 2 6
+DependencyTypes_56             : 2 0
+DependencyTypes_57             : 2 6
+DependencyTypes_58             : 2 0
+DependencyTypes_59             : 2 6
+DependencyTypes_60             : 2 0
+DependencyTypes_61             : 2 6
+
+
+#========== Camera parameters ==========
+BaseViewCameraNumbers         : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31        # camera numbers of coded views ( in coding order per view )
+CameraParameterFile           : cam_pars.txt  # camera parameter file
+CodedCamParsPrecision         : 5           # precision used for coding of camera parameters (in units of 2^(-x) luma samples)
+
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 24          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+
+#                         CbQPoffset  QPfactor     betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset CrQPoffset  cOffsetDiv2      temporal_id   #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0         interCompPred     
+Frame1:     B    8     1    0   0     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0                                            0
+Frame2:     B    4     2    0   0     0.3536   0        0        0        2      3     -4 -6  4           1     4     5     1 1 0 0 1       0                                            0
+Frame3:     B    2     3    0   0     0.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1         0                                            0
+Frame4:     B    1     4    0   0     0.68     0        0        0        2      4     -1  1  3 7         1     1     5     1 0 1 1 1       0                                            0
+Frame5:     B    3     4    0   0     0.68     0        0        0        2      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0                                            0
+Frame6:     B    6     3    0   0     0.3536   0        0        0        2      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       0                                            0                                                
+Frame7:     B    5     4    0   0     0.68     0        0        0        2      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0                                            0
+Frame8:     B    7     4    0   0     0.68     0        0        0        2      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0                                            0
+                                                                              
+FrameI_l1:  I    0     0    0   0     0.442    0        0        0        0      0                        0                                 0                                            1                    
+Frame1_l1:  B    8     1    0   0     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0                                            1             
+Frame2_l1:  B    4     2    0   0     0.3536   0        0        0        2      3     -4 -6  4           1     4     5     1 1 0 0 1       0                                            1             
+Frame3_l1:  B    2     3    0   0     0.3536   0        0        0        2      4     -2 -4  2 6         1     2     4     1 1 1 1         0                                            1             
+Frame4_l1:  B    1     4    0   0     0.68     0        0        0        2      4     -1  1  3 7         1     1     5     1 0 1 1 1       0                                            1             
+Frame5_l1:  B    3     4    0   0     0.68     0        0        0        2      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0                                            1             
+Frame6_l1:  B    6     3    0   0     0.3536   0        0        0        2      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       0                                            1             
+Frame7_l1:  B    5     4    0   0     0.68     0        0        0        2      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0                                            1             
+Frame8_l1:  B    7     4    0   0     0.68     0        0        0        2      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0                                            1
+
+FrameI_l2:  P    0     3    0   0     0.442    0        0        0        1      0                        0                                 1            0         0          -1         1
+Frame1_l2:  B    8     4    0   0     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1         1
+Frame2_l2:  B    4     5    0   0     0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       1            0         1          -1         1
+Frame3_l2:  B    2     6    0   0     0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         1            0         1          -1         1
+Frame4_l2:  B    1     7    0   0     0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       1            0         1          -1         1
+Frame5_l2:  B    3     7    0   0     0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       1            0         2          -1         1
+Frame6_l2:  B    6     6    0   0     0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       1            0         2          -1         1
+Frame7_l2:  B    5     7    0   0     0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       1            0         2          -1         1
+Frame8_l2:  B    7     7    0   0     0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       1            0         2          -1         1
+
+
+LayerIdxInVpsToGopDefIdx: 0 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+
+#======== Quantization =============
+QP                            : 25 30       # QP ( mc )
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+SliceChromaQPOffsetPeriodicity: 0           # Used in conjunction with Slice Cb/Cr QpOffsetIntraOrPeriodic. Use 0 (default) to disable periodic nature.
+SliceCbQpOffsetIntraOrPeriodic: 0           # Chroma Cb QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
+SliceCrQpOffsetIntraOrPeriodic: 0           # Chroma Cr QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0 1         # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1 0         # Sample adaptive offset  (0: OFF, 1: ON) (mc)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag           : 1                  # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across                                                       
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag: 0  # Value of PPS flag.
+CUTransquantBypassFlagForce: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 1                # Rate control: keep hierarchical bit allocation in rate control algorithm
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+#DepthMADPred                        : 0                # 0: Disable Depth based MAD prediction for extended view 1: Enable Depth based MAD prediction for extended view
+#TargetBitAssign                     : 0                # Manual assignment of target bit-rate
+#ViewWiseTargetBits                  : 950000 315000 358000      # View-wise target bit-rate setting
+
+#============ Rate Control URQ ======================
+#RateCtrl                           : 0                # 0: Disable rate control 1: Enable rate control with total target
+#DepthMADPred                       : 0                # 0: Disable Depth based MAD prediction for extended view 1: Enable Depth based MAD prediction for extended view
+#TargetBitAssign                    : 0                # Manual assignment of target bit-rate
+#ViewWiseTargetBits                 : 952 315 360      # View-wise target bit-rate setting
+#TargetBitrate                      : 1500             # input target bitrate when RateCtrl is enable
+#NumLCUInUnit                       : 1                # Number of LCU in an Unit. Fraction is not allowed
+#========== multiview coding tools ==========
+IvMvPredFlag                        : 1 1              # Inter-view motion prediction
+IvResPredFlag                       : 1                # Advanced inter-view residual prediction (0:off, 1:on)
+IlluCompEnable                      : 1                # Enable Illumination compensation ( 0: off, 1: on ) (v/d)
+IlluCompLowLatencyEnc               : 0                # Enable low-latency Illumination compensation encoding( 0: off, 1: on )
+ViewSynthesisPredFlag               : 1                # View synthesis prediction 
+DepthRefinementFlag                 : 1                # Disparity refined by depth DoNBDV
+IvMvScalingFlag                     : 1                # Interview motion vector scaling
+Log2SubPbSizeMinus3                 : 0                # Log2 of sub-PU size for IvMvPred (2...6)
+Log2MpiSubPbSizeMinus3              : 0                # Log2 of sub-PU size minus 3 for MPI (0 ... 3) and smaller than or equal to log2(maxCUSize)-3
+DepthBasedBlkPartFlag               : 1                # Depth-based Block Partitioning
+
+#========== depth coding tools ==========
+VSO                                 : 0                # use of view synthesis optimization for depth coding
+IntraWedgeFlag                      : 1
+IntraContourFlag                    : 1                 # use of intra-view prediction mode
+IntraSdcFlag                        : 1
+DLT                                 : 1
+QTL                                 : 1
+QtPredFlag                          : 1
+InterSdcFlag                        : 1                             # use of inter sdc
+MpiFlag                             : 1
+DepthIntraSkip                      : 1     
+
+#========== view synthesis optimization (VSO) ==========
+VSOConfig                 : [cx0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) B(oo2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][cx2 B(cc1) I(s1.25 s1.5 s1.75)] # VSO configuration string
+#VSOConfig                 : [ox0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) B(oo2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][ox2 B(cc1) I(s1.25 s1.5 s1.75)] # VSO configuration string for FCO = 1
+WVSO                      : 0                                    # use of WVSO (Depth distortion metric with a weighted depth fidelity term) 
+VSOWeight                 : 10                                   # weight of VSO ( in SAD case, cf. squared in SSE case )
+VSDWeight                 : 1                                    # weight of VSD ( in SAD case, cf. squared in SSE case )
+DWeight                   : 1                                    # weight of depth distortion itself ( in SAD case, cf. squared in SSE case )
+UseEstimatedVSD           : 0                                    # Model based VSD estimation instead of rendering based for some encoder decisions      
+
+
+WarnUnknowParameter       : 1
+#========== Supplemental enhancement information ==========
+SeiCfgFileName_0                    :                  
+SeiCfgFileName_1                    :                 
+SeiCfgFileName_2                    :                 
+SeiCfgFileName_3                    :                 
+SeiCfgFileName_4                    :                 
+SeiCfgFileName_5                    :                 
+SeiCfgFileName_6                    :                 
+SeiCfgFileName_7                    :                 
+SeiCfgFileName_8                    :                 
+SeiCfgFileName_9                    :                 
+SeiCfgFileName_10                   :                 
+SeiCfgFileName_11                   :                 
+SeiCfgFileName_12                   :                 
+SeiCfgFileName_13                   :                 
+SeiCfgFileName_14                   :                 
+
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /trunk/cfg/HM/cfg_HDR/encoder_randomaccess_main10_HDR_ICtCp_classAGH.cfg
===================================================================
--- /trunk/cfg/HM/cfg_HDR/encoder_randomaccess_main10_HDR_ICtCp_classAGH.cfg	(revision 1413)
+++ /trunk/cfg/HM/cfg_HDR/encoder_randomaccess_main10_HDR_ICtCp_classAGH.cfg	(revision 1413)
@@ -0,0 +1,174 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+InputFile                     : src.yuv
+InputBitDepth                 : 12          # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 24          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920         # Input  frame width
+SourceHeight                  : 1080         # Input  frame height
+FramesToBeEncoded             : 3         # Number of frames to be coded
+
+#======== Profile ================
+Profile                       : main10
+Level                         : 4.1
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 16           # GOP Size (number of B slice = GOPSize-1)
+ReWriteParamSetsFlag          : 1           # Write parameter sets with every IRAP
+
+IntraQPOffset                 : -3
+LambdaFromQpEnable            : 1           # see JCTVC-X0038 for suitable parameters for IntraQPOffset, QPoffset, QPOffsetModelOff, QPOffsetModelScale when enabled
+#        Type POC QPoffset QPOffsetModelOff QPOffsetModelScale CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs
+Frame1:  B   16   1        0.0                      0.0            0          0          1.0      0            0              0           2                3         -16 -24 -32            0  
+Frame2:  B    8   1       -4.8848                   0.2061         0          0          1.0      0            0              1           2                3         -8  -16   8            1       8        4         1 1 0 1    
+Frame3:  B    4   4       -5.7476                   0.2286         0          0          1.0      0            0              2           2                4         -4  -12   4  12        1       4        4         1 1 1 1 
+Frame4:  B    2   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                5         -2  -10   2   6  14    1       2        5         1 1 1 1 1 
+Frame5:  B    1   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1    1  3    7  15    1       1        6         1 0 1 1 1 1  
+Frame6:  B    3   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3   1   5  13    1      -2        6         1 1 1 1 1 0 
+Frame7:  B    6   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2   -6   2  10        1      -3        6         0 1 1 1 1 0 
+Frame8:  B    5   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -5   1   3  11    1       1        5         1 1 1 1 1  
+Frame9:  B    7   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3  -7   1   9    1      -2        6         1 1 1 1 1 0 
+Frame10: B   12   4       -5.7476                   0.2286         0          0          1.0      0            0              2           2                3         -4  -12   4            1      -5        6         0 0 1 1 1 0 
+Frame11: B   10   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2  -10   2   6        1       2        4         1 1 1 1 
+Frame12: B    9   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -9   1   3   7    1       1        5         1 1 1 1 1 
+Frame13: B   11   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3 -11   1   5    1      -2        6         1 1 1 1 1 0 
+Frame14: B   14   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2   -6 -14   2        1      -3        6         0 1 1 1 1 0 
+Frame15: B   13   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -5 -13   1   3    1       1        5         1 1 1 1 1 
+Frame16: B   15   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3 -7  -15   1    1      -2        6         1 1 1 1 1 0 
+
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 256         # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+ASR			                      : 1           # Adaptive Search Range
+MinSearchWindow               : 64
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+LumaLevelToDeltaQPMode        : 1           # Change luma delta QP based on average luma 
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+SliceChromaQPOffsetPeriodicity: 0           # Used in conjunction with Slice Cb/Cr QpOffsetIntraOrPeriodic. Use 0 (default) to disable periodic nature.
+SliceCbQpOffsetIntraOrPeriodic: 0           # Chroma Cb QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
+SliceCrQpOffsetIntraOrPeriodic: 0           # Chroma Cr QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
+CbQpOffset					  : 6 
+CrQpOffset					  : 6 
+WCGPPSEnable                  : 1
+WCGPPSChromaQpScale           : -0.46       # Linear chroma QP offset mapping (scale)
+WCGPPSChromaQpOffset          : 10.00       # Linear chroma QP offset mapping (offset)
+WCGPPSCbQpScale               : 0.90        # Scale factor depending on capture and representation color space (with BT.2020 container use 1.14 for BT.709 material and 1.04 for P3 material)
+WCGPPSCrQpScale               : 1.60        # Scale factor depending on capture and representation color space (with BT.2020 container use 1.79 for BT.709 material and 1.39 for P3 material)
+
+#=========== Deblock Filter ============
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+#============ VUI ================
+VuiParametersPresent                : 1
+VideoSignalTypePresent              : 1
+VideoFullRange                      : 0
+ColourDescriptionPresent            : 1
+ColourPrimaries                     : 9
+TransferCharacteristics             : 16
+MatrixCoefficients                  : 14
+SEIMasteringDisplayColourVolume     : 1
+SEIMasteringDisplayMaxLuminance     : 40000000
+SEIMasteringDisplayMinLuminance     : 47
+SEIMasteringDisplayPrimaries        : 13250,34500,7500,3000,34000,16000
+SEIMasteringDisplayWhitePoint       : 15635,16450
+ChromaLocInfoPresent                : 1 
+ChromaSampleLocTypeTopField         : 2
+ChromaSampleLocTypeBottomField      : 2
+
+SEIDecodedPictureHash 				: 0
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: /trunk/cfg/HM/cfg_HDR/encoder_randomaccess_main10_HDR_ICtCp_classBCD.cfg
===================================================================
--- /trunk/cfg/HM/cfg_HDR/encoder_randomaccess_main10_HDR_ICtCp_classBCD.cfg	(revision 1413)
+++ /trunk/cfg/HM/cfg_HDR/encoder_randomaccess_main10_HDR_ICtCp_classBCD.cfg	(revision 1413)
@@ -0,0 +1,174 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+InputFile                     : src.yuv
+InputBitDepth                 : 12          # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 24          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1920         # Input  frame width
+SourceHeight                  : 1080         # Input  frame height
+FramesToBeEncoded             : 3         # Number of frames to be coded
+
+#======== Profile ================
+Profile                       : main10
+Level                         : 4.1
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 16           # GOP Size (number of B slice = GOPSize-1)
+ReWriteParamSetsFlag          : 1           # Write parameter sets with every IRAP
+
+IntraQPOffset                 : -3
+LambdaFromQpEnable            : 1           # see JCTVC-X0038 for suitable parameters for IntraQPOffset, QPoffset, QPOffsetModelOff, QPOffsetModelScale when enabled
+#        Type POC QPoffset QPOffsetModelOff QPOffsetModelScale CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs
+Frame1:  B   16   1        0.0                      0.0            0          0          1.0      0            0              0           2                3         -16 -24 -32            0  
+Frame2:  B    8   1       -4.8848                   0.2061         0          0          1.0      0            0              1           2                3         -8  -16   8            1       8        4         1 1 0 1    
+Frame3:  B    4   4       -5.7476                   0.2286         0          0          1.0      0            0              2           2                4         -4  -12   4  12        1       4        4         1 1 1 1 
+Frame4:  B    2   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                5         -2  -10   2   6  14    1       2        5         1 1 1 1 1 
+Frame5:  B    1   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1    1  3    7  15    1       1        6         1 0 1 1 1 1  
+Frame6:  B    3   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3   1   5  13    1      -2        6         1 1 1 1 1 0 
+Frame7:  B    6   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2   -6   2  10        1      -3        6         0 1 1 1 1 0 
+Frame8:  B    5   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -5   1   3  11    1       1        5         1 1 1 1 1  
+Frame9:  B    7   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3  -7   1   9    1      -2        6         1 1 1 1 1 0 
+Frame10: B   12   4       -5.7476                   0.2286         0          0          1.0      0            0              2           2                3         -4  -12   4            1      -5        6         0 0 1 1 1 0 
+Frame11: B   10   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2  -10   2   6        1       2        4         1 1 1 1 
+Frame12: B    9   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -9   1   3   7    1       1        5         1 1 1 1 1 
+Frame13: B   11   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3 -11   1   5    1      -2        6         1 1 1 1 1 0 
+Frame14: B   14   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2   -6 -14   2        1      -3        6         0 1 1 1 1 0 
+Frame15: B   13   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -5 -13   1   3    1       1        5         1 1 1 1 1 
+Frame16: B   15   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3 -7  -15   1    1      -2        6         1 1 1 1 1 0 
+
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 256         # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+ASR			                      : 1           # Adaptive Search Range
+MinSearchWindow               : 64
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+LumaLevelToDeltaQPMode        : 1           # Change luma delta QP based on average luma 
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+SliceChromaQPOffsetPeriodicity: 0           # Used in conjunction with Slice Cb/Cr QpOffsetIntraOrPeriodic. Use 0 (default) to disable periodic nature.
+SliceCbQpOffsetIntraOrPeriodic: 0           # Chroma Cb QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
+SliceCrQpOffsetIntraOrPeriodic: 0           # Chroma Cr QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
+CbQpOffset					  : 8 
+CrQpOffset					  : 7 
+WCGPPSEnable                  : 1
+WCGPPSChromaQpScale           : -0.46       # Linear chroma QP offset mapping (scale)
+WCGPPSChromaQpOffset          : 10.00       # Linear chroma QP offset mapping (offset)
+WCGPPSCbQpScale               : 0.50        # Scale factor depending on capture and representation color space (with BT.2020 container use 1.14 for BT.709 material and 1.04 for P3 material)
+WCGPPSCrQpScale               : 0.90        # Scale factor depending on capture and representation color space (with BT.2020 container use 1.79 for BT.709 material and 1.39 for P3 material)
+
+#=========== Deblock Filter ============
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+#============ VUI ================
+VuiParametersPresent                : 1
+VideoSignalTypePresent              : 1
+VideoFullRange                      : 0
+ColourDescriptionPresent            : 1
+ColourPrimaries                     : 9
+TransferCharacteristics             : 16
+MatrixCoefficients                  : 14
+SEIMasteringDisplayColourVolume     : 1
+SEIMasteringDisplayMaxLuminance     : 40000000
+SEIMasteringDisplayMinLuminance     : 47
+SEIMasteringDisplayPrimaries        : 13250,34500,7500,3000,34000,16000
+SEIMasteringDisplayWhitePoint       : 15635,16450
+ChromaLocInfoPresent                : 1 
+ChromaSampleLocTypeTopField         : 2
+ChromaSampleLocTypeBottomField      : 2
+
+SEIDecodedPictureHash 				: 0
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: /trunk/cfg/HM/cfg_HDR/encoder_randomaccess_main10_HDR_YCbCr_classAGH.cfg
===================================================================
--- /trunk/cfg/HM/cfg_HDR/encoder_randomaccess_main10_HDR_YCbCr_classAGH.cfg	(revision 1413)
+++ /trunk/cfg/HM/cfg_HDR/encoder_randomaccess_main10_HDR_YCbCr_classAGH.cfg	(revision 1413)
@@ -0,0 +1,163 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main10
+Level                         : 4.1
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 16           # GOP Size (number of B slice = GOPSize-1)
+ReWriteParamSetsFlag          : 1           # Write parameter sets with every IRAP
+
+IntraQPOffset                 : -3
+LambdaFromQpEnable            : 1           # see JCTVC-X0038 for suitable parameters for IntraQPOffset, QPoffset, QPOffsetModelOff, QPOffsetModelScale when enabled
+#        Type POC QPoffset QPOffsetModelOff QPOffsetModelScale CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs
+Frame1:  B   16   1        0.0                      0.0            0          0          1.0      0            0              0           2                3         -16 -24 -32            0  
+Frame2:  B    8   1       -4.8848                   0.2061         0          0          1.0      0            0              1           2                3         -8  -16   8            1       8        4         1 1 0 1    
+Frame3:  B    4   4       -5.7476                   0.2286         0          0          1.0      0            0              2           2                4         -4  -12   4  12        1       4        4         1 1 1 1 
+Frame4:  B    2   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                5         -2  -10   2   6  14    1       2        5         1 1 1 1 1 
+Frame5:  B    1   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1    1  3    7  15    1       1        6         1 0 1 1 1 1  
+Frame6:  B    3   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3   1   5  13    1      -2        6         1 1 1 1 1 0 
+Frame7:  B    6   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2   -6   2  10        1      -3        6         0 1 1 1 1 0 
+Frame8:  B    5   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -5   1   3  11    1       1        5         1 1 1 1 1  
+Frame9:  B    7   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3  -7   1   9    1      -2        6         1 1 1 1 1 0 
+Frame10: B   12   4       -5.7476                   0.2286         0          0          1.0      0            0              2           2                3         -4  -12   4            1      -5        6         0 0 1 1 1 0 
+Frame11: B   10   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2  -10   2   6        1       2        4         1 1 1 1 
+Frame12: B    9   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -9   1   3   7    1       1        5         1 1 1 1 1 
+Frame13: B   11   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3 -11   1   5    1      -2        6         1 1 1 1 1 0 
+Frame14: B   14   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2   -6 -14   2        1      -3        6         0 1 1 1 1 0 
+Frame15: B   13   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -5 -13   1   3    1       1        5         1 1 1 1 1 
+Frame16: B   15   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3 -7  -15   1    1      -2        6         1 1 1 1 1 0 
+
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 256         # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+ASR			                      : 1           # Adaptive Search Range
+MinSearchWindow               : 64
+
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+LumaLevelToDeltaQPMode        : 1           # Change luma delta QP based on average luma 
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+SliceChromaQPOffsetPeriodicity: 0           # Used in conjunction with Slice Cb/Cr QpOffsetIntraOrPeriodic. Use 0 (default) to disable periodic nature.
+SliceCbQpOffsetIntraOrPeriodic: 0           # Chroma Cb QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
+SliceCrQpOffsetIntraOrPeriodic: 0           # Chroma Cr QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
+WCGPPSEnable                  : 1
+WCGPPSChromaQpScale           : -0.46       # Linear chroma QP offset mapping (scale)
+WCGPPSChromaQpOffset          : 9.26        # Linear chroma QP offset mapping (offset)
+WCGPPSCbQpScale               : 1.14        # Scale factor depending on capture and representation color space (with BT.2020 container use 1.14 for BT.709 material and 1.04 for P3 material)
+WCGPPSCrQpScale               : 1.79        # Scale factor depending on capture and representation color space (with BT.2020 container use 1.79 for BT.709 material and 1.39 for P3 material)
+
+#=========== Deblock Filter ============
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+#============ VUI ================
+VuiParametersPresent                : 1
+VideoSignalTypePresent              : 1
+VideoFullRange                      : 0
+ColourDescriptionPresent            : 1
+ColourPrimaries                     : 9
+TransferCharacteristics             : 16
+MatrixCoefficients                  : 9
+SEIMasteringDisplayColourVolume     : 1
+SEIMasteringDisplayMaxLuminance     : 40000000
+SEIMasteringDisplayMinLuminance     : 47
+SEIMasteringDisplayPrimaries        : 13250,34500,7500,3000,34000,16000
+SEIMasteringDisplayWhitePoint       : 15635,16450
+ChromaLocInfoPresent                : 1 
+ChromaSampleLocTypeTopField         : 2
+ChromaSampleLocTypeBottomField      : 2
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: /trunk/cfg/HM/cfg_HDR/encoder_randomaccess_main10_HDR_YCbCr_classBCD.cfg
===================================================================
--- /trunk/cfg/HM/cfg_HDR/encoder_randomaccess_main10_HDR_YCbCr_classBCD.cfg	(revision 1413)
+++ /trunk/cfg/HM/cfg_HDR/encoder_randomaccess_main10_HDR_YCbCr_classBCD.cfg	(revision 1413)
@@ -0,0 +1,162 @@
+#======== File I/O =====================
+BitstreamFile                 : str.bin
+ReconFile                     : rec.yuv
+
+#======== Profile ================
+Profile                       : main10
+Level                         : 4.1
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 16           # GOP Size (number of B slice = GOPSize-1)
+ReWriteParamSetsFlag          : 1           # Write parameter sets with every IRAP
+
+IntraQPOffset                 : -3
+LambdaFromQpEnable            : 1           # see JCTVC-X0038 for suitable parameters for IntraQPOffset, QPoffset, QPOffsetModelOff, QPOffsetModelScale when enabled
+#        Type POC QPoffset QPOffsetModelOff QPOffsetModelScale CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs
+Frame1:  B   16   1        0.0                      0.0            0          0          1.0      0            0              0           2                3         -16 -24 -32            0  
+Frame2:  B    8   1       -4.8848                   0.2061         0          0          1.0      0            0              1           2                3         -8  -16   8            1       8        4         1 1 0 1    
+Frame3:  B    4   4       -5.7476                   0.2286         0          0          1.0      0            0              2           2                4         -4  -12   4  12        1       4        4         1 1 1 1 
+Frame4:  B    2   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                5         -2  -10   2   6  14    1       2        5         1 1 1 1 1 
+Frame5:  B    1   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1    1  3    7  15    1       1        6         1 0 1 1 1 1  
+Frame6:  B    3   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3   1   5  13    1      -2        6         1 1 1 1 1 0 
+Frame7:  B    6   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2   -6   2  10        1      -3        6         0 1 1 1 1 0 
+Frame8:  B    5   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -5   1   3  11    1       1        5         1 1 1 1 1  
+Frame9:  B    7   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3  -7   1   9    1      -2        6         1 1 1 1 1 0 
+Frame10: B   12   4       -5.7476                   0.2286         0          0          1.0      0            0              2           2                3         -4  -12   4            1      -5        6         0 0 1 1 1 0 
+Frame11: B   10   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2  -10   2   6        1       2        4         1 1 1 1 
+Frame12: B    9   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -9   1   3   7    1       1        5         1 1 1 1 1 
+Frame13: B   11   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3 -11   1   5    1      -2        6         1 1 1 1 1 0 
+Frame14: B   14   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2   -6 -14   2        1      -3        6         0 1 1 1 1 0 
+Frame15: B   13   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -5 -13   1   3    1       1        5         1 1 1 1 1 
+Frame16: B   15   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3 -7  -15   1    1      -2        6         1 1 1 1 1 0 
+
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 256         # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+ASR			                      : 1           # Adaptive Search Range
+MinSearchWindow               : 64
+
+#======== Quantization =============
+QP                            : 32          # Quantization parameter(0-51)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+LumaLevelToDeltaQPMode        : 1           # Change luma delta QP based on average luma 
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+SliceChromaQPOffsetPeriodicity: 0           # Used in conjunction with Slice Cb/Cr QpOffsetIntraOrPeriodic. Use 0 (default) to disable periodic nature.
+SliceCbQpOffsetIntraOrPeriodic: 0           # Chroma Cb QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
+SliceCrQpOffsetIntraOrPeriodic: 0           # Chroma Cr QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
+WCGPPSEnable                  : 1
+WCGPPSChromaQpScale           : -0.46       # Linear chroma QP offset mapping (scale)
+WCGPPSChromaQpOffset          : 9.26        # Linear chroma QP offset mapping (offset)
+WCGPPSCbQpScale               : 1.04        # Scale factor depending on capture and representation color space (with BT.2020 container use 1.14 for BT.709 material and 1.04 for P3 material)
+WCGPPSCrQpScale               : 1.39        # Scale factor depending on capture and representation color space (with BT.2020 container use 1.79 for BT.709 material and 1.39 for P3 material)
+
+#=========== Deblock Filter ============
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 10          # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+#============ Slices ================
+SliceMode                : 0                # 0: Disable all slice options.
+                                            # 1: Enforce maximum number of LCU in an slice,
+                                            # 2: Enforce maximum number of bytes in an 'slice'
+                                            # 3: Enforce maximum number of tiles in a slice
+SliceArgument            : 1500             # Argument for 'SliceMode'.
+                                            # If SliceMode==1 it represents max. SliceGranularity-sized blocks per slice.
+                                            # If SliceMode==2 it represents max. bytes per slice.
+                                            # If SliceMode==3 it represents max. tiles per slice.
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+#============ PCM ================
+PCMEnabledFlag                      : 0                # 0: No PCM mode
+PCMLog2MaxSize                      : 5                # Log2 of maximum PCM block size.
+PCMLog2MinSize                      : 3                # Log2 of minimum PCM block size.
+PCMInputBitDepthFlag                : 1                # 0: PCM bit-depth is internal bit-depth. 1: PCM bit-depth is input bit-depth.
+PCMFilterDisableFlag                : 0                # 0: Enable loop filtering on I_PCM samples. 1: Disable loop filtering on I_PCM samples.
+
+#============ Tiles ================
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
+                                                       # 1: the column and row boundaries are distributed uniformly
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
+
+LFCrossTileBoundaryFlag             : 1                # In-loop filtering is across or not across tile boundary.
+                                                       # 0:not across, 1: across 
+
+#============ WaveFront ================
+WaveFrontSynchro                    : 0                # 0:  No WaveFront synchronisation (WaveFrontSubstreams must be 1 in this case).
+                                                       # >0: WaveFront synchronises with the LCU above and to the right by this many LCUs.
+
+#=========== Quantization Matrix =================
+ScalingList                   : 0                      # ScalingList 0 : off, 1 : default, 2 : file read
+ScalingListFile               : scaling_list.txt       # Scaling List file name. If file is not exist, use Default Matrix.
+
+#============ Lossless ================
+TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
+
+#============ Rate Control ======================
+RateControl                         : 0                # Rate control: enable rate control
+TargetBitrate                       : 1000000          # Rate control: target bitrate, in bps
+KeepHierarchicalBit                 : 2                # Rate control: 0: equal bit allocation; 1: fixed ratio bit allocation; 2: adaptive ratio bit allocation
+LCULevelRateControl                 : 1                # Rate control: 1: LCU level RC; 0: picture level RC
+RCLCUSeparateModel                  : 1                # Rate control: use LCU level separate R-lambda model
+InitialQP                           : 0                # Rate control: initial QP
+RCForceIntraQP                      : 0                # Rate control: force intra QP to be equal to initial QP
+
+#============ VUI ================
+VuiParametersPresent                : 1
+VideoSignalTypePresent              : 1
+VideoFullRange                      : 0
+ColourDescriptionPresent            : 1
+ColourPrimaries                     : 9
+TransferCharacteristics             : 16
+MatrixCoefficients                  : 9
+SEIMasteringDisplayColourVolume     : 1
+SEIMasteringDisplayMaxLuminance     : 40000000
+SEIMasteringDisplayMinLuminance     : 47
+SEIMasteringDisplayPrimaries        : 13250,34500,7500,3000,34000,16000
+SEIMasteringDisplayWhitePoint       : 15635,16450
+ChromaLocInfoPresent                : 1 
+ChromaSampleLocTypeTopField         : 2
+ChromaSampleLocTypeBottomField      : 2
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
+
Index: /trunk/cfg/HM/encoder_intra_high_throughput_rext.cfg
===================================================================
--- /trunk/cfg/HM/encoder_intra_high_throughput_rext.cfg	(revision 1412)
+++ /trunk/cfg/HM/encoder_intra_high_throughput_rext.cfg	(revision 1413)
@@ -21,6 +21,7 @@
 #======== Coding Structure =============
 IntraPeriod                   : 1           # Period of I-Frame ( -1 = only first)
-DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CDR, 2:IDR
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
 GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+ReWriteParamSetsFlag          : 1           # Write parameter sets with every IRAP
 #        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures  
 
@@ -78,10 +79,10 @@
 
 #============ Tiles ================
-UniformSpacingIdc                   : 0                # 0: the column boundaries are indicated by ColumnWidth array, the row boundaries are indicated by RowHeight array
+TileUniformSpacing                  : 0                # 0: the column boundaries are indicated by TileColumnWidth array, the row boundaries are indicated by TileRowHeight array
                                                        # 1: the column and row boundaries are distributed uniformly
-NumTileColumnsMinus1                : 0                # Number of columns in a picture minus 1
-ColumnWidthArray                    : 2 3              # Array containing ColumnWidth values in units of LCU (from left to right in picture)   
-NumTileRowsMinus1                   : 0                # Number of rows in a picture minus 1
-RowHeightArray                      : 2                # Array containing RowHeight values in units of LCU (from top to bottom in picture)
+NumTileColumnsMinus1                : 0                # Number of tile columns in a picture minus 1
+TileColumnWidthArray                : 2 3              # Array containing tile column width values in units of CTU (from left to right in picture)   
+NumTileRowsMinus1                   : 0                # Number of tile rows in a picture minus 1
+TileRowHeightArray                  : 2                # Array containing tile row height values in units of CTU (from top to bottom in picture)
 
 LFCrossTileBoundaryFlag           : 1                  # In-loop filtering is across or not across tile boundary.
@@ -97,5 +98,5 @@
 
 #============ Lossless ================
-TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+TransquantBypassEnable     : 0                         # Value of PPS flag.
 CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
 
Index: /trunk/cfg/HM/encoder_intra_main.cfg
===================================================================
--- /trunk/cfg/HM/encoder_intra_main.cfg	(revision 1412)
+++ /trunk/cfg/HM/encoder_intra_main.cfg	(revision 1413)
@@ -19,6 +19,7 @@
 #======== Coding Structure =============
 IntraPeriod                   : 1           # Period of I-Frame ( -1 = only first)
-DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
 GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+ReWriteParamSetsFlag          : 1           # Write parameter sets with every IRAP
 #        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures 
 
@@ -39,5 +40,4 @@
 
 #=========== Deblock Filter ============
-
 LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
@@ -96,5 +96,5 @@
 
 #============ Lossless ================
-TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+TransquantBypassEnable     : 0                         # Value of PPS flag.
 CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
 
Index: /trunk/cfg/HM/encoder_intra_main10.cfg
===================================================================
--- /trunk/cfg/HM/encoder_intra_main10.cfg	(revision 1412)
+++ /trunk/cfg/HM/encoder_intra_main10.cfg	(revision 1413)
@@ -19,6 +19,7 @@
 #======== Coding Structure =============
 IntraPeriod                   : 1           # Period of I-Frame ( -1 = only first)
-DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
 GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+ReWriteParamSetsFlag          : 1           # Write parameter sets with every IRAP
 #        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures  
 
@@ -39,5 +40,4 @@
 
 #=========== Deblock Filter ============
-
 LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
@@ -96,5 +96,5 @@
 
 #============ Lossless ================
-TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+TransquantBypassEnable     : 0                         # Value of PPS flag.
 CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
 
Index: /trunk/cfg/HM/encoder_intra_main_rext.cfg
===================================================================
--- /trunk/cfg/HM/encoder_intra_main_rext.cfg	(revision 1412)
+++ /trunk/cfg/HM/encoder_intra_main_rext.cfg	(revision 1413)
@@ -20,6 +20,7 @@
 #======== Coding Structure =============
 IntraPeriod                   : 1           # Period of I-Frame ( -1 = only first)
-DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
 GOPSize                       : 1           # GOP Size (number of B slice = GOPSize-1)
+ReWriteParamSetsFlag          : 1           # Write parameter sets with every IRAP
 #        Type POC QPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures  
 
@@ -96,5 +97,5 @@
 
 #============ Lossless ================
-TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+TransquantBypassEnable     : 0                         # Value of PPS flag.
 CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
 
Index: /trunk/cfg/HM/encoder_lowdelay_P_main.cfg
===================================================================
--- /trunk/cfg/HM/encoder_lowdelay_P_main.cfg	(revision 1412)
+++ /trunk/cfg/HM/encoder_lowdelay_P_main.cfg	(revision 1413)
@@ -21,9 +21,13 @@
 DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
 GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
-#        Type POC QPoffset CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
-Frame1:  P    1   3        0          0          0.4624   0            0               0           4                4         -1 -5 -9 -13       0
-Frame2:  P    2   2        0          0          0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
-Frame3:  P    3   3        0          0          0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
-Frame4:  P    4   1        0          0          0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+ReWriteParamSetsFlag          : 1           # Write parameter sets with every IRAP
+
+IntraQPOffset                 : -1
+LambdaFromQpEnable            : 1           # see JCTVC-X0038 for suitable parameters for IntraQPOffset, QPoffset, QPOffsetModelOff, QPOffsetModelScale when enabled
+#        Type POC QPoffset QPOffsetModelOff QPOffsetModelScale CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs
+Frame1:  P    1   5       -6.5                      0.2590         0          0          1.0   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  P    2   4       -6.5                      0.2590         0          0          1.0   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  P    3   5       -6.5                      0.2590         0          0          1.0   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1           
+Frame4:  P    4   1        0.0                      0.0            0          0          1.0   0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
 
 #=========== Motion Search =============
@@ -103,5 +107,5 @@
 
 #============ Lossless ================
-TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+TransquantBypassEnable     : 0                         # Value of PPS flag.
 CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
 
Index: /trunk/cfg/HM/encoder_lowdelay_P_main10.cfg
===================================================================
--- /trunk/cfg/HM/encoder_lowdelay_P_main10.cfg	(revision 1412)
+++ /trunk/cfg/HM/encoder_lowdelay_P_main10.cfg	(revision 1413)
@@ -21,9 +21,13 @@
 DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
 GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
-#        Type POC QPoffset CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
-Frame1:  P    1   3        0          0          0.4624   0            0               0           4                4         -1 -5 -9 -13       0
-Frame2:  P    2   2        0          0          0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
-Frame3:  P    3   3        0          0          0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
-Frame4:  P    4   1        0          0          0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+ReWriteParamSetsFlag          : 1           # Write parameter sets with every IRAP
+
+IntraQPOffset                 : -1
+LambdaFromQpEnable            : 1           # see JCTVC-X0038 for suitable parameters for IntraQPOffset, QPoffset, QPOffsetModelOff, QPOffsetModelScale when enabled
+#        Type POC QPoffset QPOffsetModelOff QPOffsetModelScale CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs
+Frame1:  P    1   5       -6.5                      0.2590         0          0          1.0   0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  P    2   4       -6.5                      0.2590         0          0          1.0   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  P    3   5       -6.5                      0.2590         0          0          1.0   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1           
+Frame4:  P    4   1        0.0                      0.0            0          0          1.0   0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
 
 #=========== Motion Search =============
@@ -103,5 +107,5 @@
 
 #============ Lossless ================
-TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+TransquantBypassEnable     : 0                         # Value of PPS flag.
 CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
 
Index: /trunk/cfg/HM/encoder_lowdelay_main.cfg
===================================================================
--- /trunk/cfg/HM/encoder_lowdelay_main.cfg	(revision 1412)
+++ /trunk/cfg/HM/encoder_lowdelay_main.cfg	(revision 1413)
@@ -21,9 +21,13 @@
 DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
 GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
-#        Type POC QPoffset CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
-Frame1:  B    1   3        0          0          0.4624   0            0               0           4                4         -1 -5 -9 -13       0
-Frame2:  B    2   2        0          0          0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
-Frame3:  B    3   3        0          0          0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
-Frame4:  B    4   1        0          0          0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+ReWriteParamSetsFlag          : 1           # Write parameter sets with every IRAP
+
+IntraQPOffset                 : -1 
+LambdaFromQpEnable            : 1           # see JCTVC-X0038 for suitable parameters for IntraQPOffset, QPoffset, QPOffsetModelOff, QPOffsetModelScale when enabled
+#        Type POC QPoffset QPOffsetModelOff QPOffsetModelScale CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs
+Frame1:  B    1   5       -6.5                      0.2590         0          0          1.0      0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  B    2   4       -6.5                      0.2590         0          0          1.0      0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  B    3   5       -6.5                      0.2590         0          0          1.0      0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1
+Frame4:  B    4   1        0.0                      0.0            0          0          1.0      0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
 
 #=========== Motion Search =============
@@ -103,5 +107,5 @@
 
 #============ Lossless ================
-TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+TransquantBypassEnable     : 0                         # Value of PPS flag.
 CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
 
Index: /trunk/cfg/HM/encoder_lowdelay_main10.cfg
===================================================================
--- /trunk/cfg/HM/encoder_lowdelay_main10.cfg	(revision 1412)
+++ /trunk/cfg/HM/encoder_lowdelay_main10.cfg	(revision 1413)
@@ -21,9 +21,13 @@
 DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
 GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
-#        Type POC QPoffset CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
-Frame1:  B    1   3        0          0          0.4624   0            0               0           4                4         -1 -5 -9 -13       0
-Frame2:  B    2   2        0          0          0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
-Frame3:  B    3   3        0          0          0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
-Frame4:  B    4   1        0          0          0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+ReWriteParamSetsFlag          : 1           # Write parameter sets with every IRAP
+
+IntraQPOffset                 : -1 
+LambdaFromQpEnable            : 1           # see JCTVC-X0038 for suitable parameters for IntraQPOffset, QPoffset, QPOffsetModelOff, QPOffsetModelScale when enabled
+#        Type POC QPoffset QPOffsetModelOff QPOffsetModelScale CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs
+Frame1:  B    1   5       -6.5                      0.2590         0          0          1.0      0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  B    2   4       -6.5                      0.2590         0          0          1.0      0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  B    3   5       -6.5                      0.2590         0          0          1.0      0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1
+Frame4:  B    4   1        0.0                      0.0            0          0          1.0      0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
 
 #=========== Motion Search =============
@@ -103,5 +107,5 @@
 
 #============ Lossless ================
-TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+TransquantBypassEnable     : 0                         # Value of PPS flag.
 CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
 
Index: /trunk/cfg/HM/encoder_lowdelay_main_rext.cfg
===================================================================
--- /trunk/cfg/HM/encoder_lowdelay_main_rext.cfg	(revision 1412)
+++ /trunk/cfg/HM/encoder_lowdelay_main_rext.cfg	(revision 1413)
@@ -22,9 +22,13 @@
 DecodingRefreshType           : 0           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
 GOPSize                       : 4           # GOP Size (number of B slice = GOPSize-1)
-#        Type POC QPoffset CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2  temporal_id #ref_pics_active #ref_pics reference pictures predict deltaRPS #ref_idcs reference idcs 
-Frame1:  B    1   3        0          0          0.4624   0            0               0           4                4         -1 -5 -9 -13       0
-Frame2:  B    2   2        0          0          0.4624   0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
-Frame3:  B    3   3        0          0          0.4624   0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1            
-Frame4:  B    4   1        0          0          0.578    0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
+ReWriteParamSetsFlag          : 1           # Write parameter sets with every IRAP
+
+IntraQPOffset                 : -1 
+LambdaFromQpEnable            : 1           # see JCTVC-X0038 for suitable parameters for IntraQPOffset, QPoffset, QPOffsetModelOff, QPOffsetModelScale when enabled
+#        Type POC QPoffset QPOffsetModelOff QPOffsetModelScale CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs
+Frame1:  B    1   5       -6.5                      0.2590         0          0          1.0      0            0               0           4                4         -1 -5 -9 -13       0
+Frame2:  B    2   4       -6.5                      0.2590         0          0          1.0      0            0               0           4                4         -1 -2 -6 -10       1      -1       5         1 1 1 0 1
+Frame3:  B    3   5       -6.5                      0.2590         0          0          1.0      0            0               0           4                4         -1 -3 -7 -11       1      -1       5         0 1 1 1 1
+Frame4:  B    4   1        0.0                      0.0            0          0          1.0      0            0               0           4                4         -1 -4 -8 -12       1      -1       5         0 1 1 1 1
 
 #=========== Motion Search =============
@@ -104,5 +108,5 @@
 
 #============ Lossless ================
-TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+TransquantBypassEnable     : 0                         # Value of PPS flag.
 CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
 
Index: /trunk/cfg/HM/encoder_randomaccess_main.cfg
===================================================================
--- /trunk/cfg/HM/encoder_randomaccess_main.cfg	(revision 1412)
+++ /trunk/cfg/HM/encoder_randomaccess_main.cfg	(revision 1413)
@@ -20,18 +20,32 @@
 IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
 DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
-GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
-#        Type POC QPoffset CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
-Frame1:  B    8   1        0          0          0.442    0            0              0           2                3         -8 -12 -16             0
-Frame2:  B    4   2        0          0          0.3536   0            0              1           2                3         -4  -8   4             1       4        4         1 1 0 1
-Frame3:  B    2   3        0          0          0.3536   0            0              2           2                4         -2  -6   2 6           1       2        4         1 1 1 1
-Frame4:  B    1   4        0          0          0.68     0            0              3           2                4         -1   1   3 7           1       1        5         1 0 1 1 1
-Frame5:  B    3   4        0          0          0.68     0            0              3           2                4         -1  -3   1 5           1      -2        5         1 1 1 1 0
-Frame6:  B    6   3        0          0          0.3536   0            0              2           2                3         -2  -6   2             1      -3        5         0 1 1 1 0
-Frame7:  B    5   4        0          0          0.68     0            0              3           2                4         -1  -5   1 3           1       1        4         1 1 1 1
-Frame8:  B    7   4        0          0          0.68     0            0              3           2                4         -1  -3  -7 1           1      -2        5         1 1 1 1 0
+GOPSize                       : 16           # GOP Size (number of B slice = GOPSize-1)
+ReWriteParamSetsFlag          : 1           # Write parameter sets with every IRAP
+
+IntraQPOffset                 : -3
+LambdaFromQpEnable            : 1           # see JCTVC-X0038 for suitable parameters for IntraQPOffset, QPoffset, QPOffsetModelOff, QPOffsetModelScale when enabled
+#        Type POC QPoffset QPOffsetModelOff QPOffsetModelScale CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs
+Frame1:  B   16   1        0.0                      0.0            0          0          1.0      0            0              0           2                3         -16 -24 -32            0  
+Frame2:  B    8   1       -4.8848                   0.2061         0          0          1.0      0            0              1           2                3         -8  -16   8            1       8        4         1 1 0 1    
+Frame3:  B    4   4       -5.7476                   0.2286         0          0          1.0      0            0              2           2                4         -4  -12   4  12        1       4        4         1 1 1 1 
+Frame4:  B    2   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                5         -2  -10   2   6  14    1       2        5         1 1 1 1 1 
+Frame5:  B    1   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1    1  3    7  15    1       1        6         1 0 1 1 1 1  
+Frame6:  B    3   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3   1   5  13    1      -2        6         1 1 1 1 1 0 
+Frame7:  B    6   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2   -6   2  10        1      -3        6         0 1 1 1 1 0 
+Frame8:  B    5   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -5   1   3  11    1       1        5         1 1 1 1 1  
+Frame9:  B    7   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3  -7   1   9    1      -2        6         1 1 1 1 1 0 
+Frame10: B   12   4       -5.7476                   0.2286         0          0          1.0      0            0              2           2                3         -4  -12   4            1      -5        6         0 0 1 1 1 0 
+Frame11: B   10   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2  -10   2   6        1       2        4         1 1 1 1 
+Frame12: B    9   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -9   1   3   7    1       1        5         1 1 1 1 1 
+Frame13: B   11   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3 -11   1   5    1      -2        6         1 1 1 1 1 0 
+Frame14: B   14   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2   -6 -14   2        1      -3        6         0 1 1 1 1 0 
+Frame15: B   13   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -5 -13   1   3    1       1        5         1 1 1 1 1 
+Frame16: B   15   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3 -7  -15   1    1      -2        6         1 1 1 1 1 0 
 
 #=========== Motion Search =============
 FastSearch                    : 1           # 0:Full search  1:TZ search
-SearchRange                   : 64          # (0: Search range is a Full frame)
+SearchRange                   : 384         # (0: Search range is a Full frame)
+ASR                           : 1           # Adaptive motion search range
+MinSearchWindow               : 96          # Minimum motion search window size for the adaptive window ME
 BipredSearchRange             : 4           # Search range for bi-prediction refinement
 HadamardME                    : 1           # Use of hadamard measure for fractional ME
@@ -121,3 +135,2 @@
 ### DO NOT ADD ANYTHING BELOW THIS LINE ###
 ### DO NOT DELETE THE EMPTY LINE BELOW ###
-
Index: /trunk/cfg/HM/encoder_randomaccess_main10.cfg
===================================================================
--- /trunk/cfg/HM/encoder_randomaccess_main10.cfg	(revision 1412)
+++ /trunk/cfg/HM/encoder_randomaccess_main10.cfg	(revision 1413)
@@ -20,18 +20,33 @@
 IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
 DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
-GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
-#        Type POC QPoffset CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
-Frame1:  B    8   1        0          0          0.442    0            0              0           2                3         -8 -12 -16             0
-Frame2:  B    4   2        0          0          0.3536   0            0              1           2                3         -4  -8   4             1       4        4         1 1 0 1
-Frame3:  B    2   3        0          0          0.3536   0            0              2           2                4         -2  -6   2 6           1       2        4         1 1 1 1
-Frame4:  B    1   4        0          0          0.68     0            0              3           2                4         -1   1   3 7           1       1        5         1 0 1 1 1
-Frame5:  B    3   4        0          0          0.68     0            0              3           2                4         -1  -3   1 5           1      -2        5         1 1 1 1 0
-Frame6:  B    6   3        0          0          0.3536   0            0              2           2                3         -2  -6   2             1      -3        5         0 1 1 1 0
-Frame7:  B    5   4        0          0          0.68     0            0              3           2                4         -1  -5   1 3           1       1        4         1 1 1 1
-Frame8:  B    7   4        0          0          0.68     0            0              3           2                4         -1  -3  -7 1           1      -2        5         1 1 1 1 0
+GOPSize                       : 16           # GOP Size (number of B slice = GOPSize-1)
+ReWriteParamSetsFlag          : 1           # Write parameter sets with every IRAP
+
+IntraQPOffset                 : -3
+LambdaFromQpEnable            : 1           # see JCTVC-X0038 for suitable parameters for IntraQPOffset, QPoffset, QPOffsetModelOff, QPOffsetModelScale when enabled
+#        Type POC QPoffset QPOffsetModelOff QPOffsetModelScale CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs
+Frame1:  B   16   1        0.0                      0.0            0          0          1.0      0            0              0           2                3         -16 -24 -32            0  
+Frame2:  B    8   1       -4.8848                   0.2061         0          0          1.0      0            0              1           2                3         -8  -16   8            1       8        4         1 1 0 1    
+Frame3:  B    4   4       -5.7476                   0.2286         0          0          1.0      0            0              2           2                4         -4  -12   4  12        1       4        4         1 1 1 1 
+Frame4:  B    2   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                5         -2  -10   2   6  14    1       2        5         1 1 1 1 1 
+Frame5:  B    1   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1    1  3    7  15    1       1        6         1 0 1 1 1 1  
+Frame6:  B    3   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3   1   5  13    1      -2        6         1 1 1 1 1 0 
+Frame7:  B    6   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2   -6   2  10        1      -3        6         0 1 1 1 1 0 
+Frame8:  B    5   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -5   1   3  11    1       1        5         1 1 1 1 1  
+Frame9:  B    7   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3  -7   1   9    1      -2        6         1 1 1 1 1 0 
+Frame10: B   12   4       -5.7476                   0.2286         0          0          1.0      0            0              2           2                3         -4  -12   4            1      -5        6         0 0 1 1 1 0 
+Frame11: B   10   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2  -10   2   6        1       2        4         1 1 1 1 
+Frame12: B    9   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -9   1   3   7    1       1        5         1 1 1 1 1 
+Frame13: B   11   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3 -11   1   5    1      -2        6         1 1 1 1 1 0 
+Frame14: B   14   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2   -6 -14   2        1      -3        6         0 1 1 1 1 0 
+Frame15: B   13   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -5 -13   1   3    1       1        5         1 1 1 1 1 
+Frame16: B   15   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3 -7  -15   1    1      -2        6         1 1 1 1 1 0 
+
 
 #=========== Motion Search =============
 FastSearch                    : 1           # 0:Full search  1:TZ search
-SearchRange                   : 64          # (0: Search range is a Full frame)
+SearchRange                   : 384         # (0: Search range is a Full frame)
+ASR                           : 1           # Adaptive motion search range
+MinSearchWindow               : 96          # Minimum motion search window size for the adaptive window ME
 BipredSearchRange             : 4           # Search range for bi-prediction refinement
 HadamardME                    : 1           # Use of hadamard measure for fractional ME
@@ -121,3 +136,2 @@
 ### DO NOT ADD ANYTHING BELOW THIS LINE ###
 ### DO NOT DELETE THE EMPTY LINE BELOW ###
-
Index: /trunk/cfg/HM/encoder_randomaccess_main_rext.cfg
===================================================================
--- /trunk/cfg/HM/encoder_randomaccess_main_rext.cfg	(revision 1412)
+++ /trunk/cfg/HM/encoder_randomaccess_main_rext.cfg	(revision 1413)
@@ -21,18 +21,32 @@
 IntraPeriod                   : 32          # Period of I-Frame ( -1 = only first)
 DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
-GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
-#        Type POC QPoffset CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
-Frame1:  B    8   1        0          0          0.442    0            0              0           2                3         -8 -12 -16             0
-Frame2:  B    4   2        0          0          0.3536   0            0              1           2                3         -4  -8   4             1       4        4         1 1 0 1
-Frame3:  B    2   3        0          0          0.3536   0            0              2           2                4         -2  -6   2 6           1       2        4         1 1 1 1
-Frame4:  B    1   4        0          0          0.68     0            0              3           2                4         -1   1   3 7           1       1        5         1 0 1 1 1
-Frame5:  B    3   4        0          0          0.68     0            0              3           2                4         -1  -3   1 5           1      -2        5         1 1 1 1 0
-Frame6:  B    6   3        0          0          0.3536   0            0              2           2                3         -2  -6   2             1      -3        5         0 1 1 1 0
-Frame7:  B    5   4        0          0          0.68     0            0              3           2                4         -1  -5   1 3           1       1        4         1 1 1 1
-Frame8:  B    7   4        0          0          0.68     0            0              3           2                4         -1  -3  -7 1           1      -2        5         1 1 1 1 0
+GOPSize                       : 16           # GOP Size (number of B slice = GOPSize-1)
+ReWriteParamSetsFlag          : 1           # Write parameter sets with every IRAP
+
+IntraQPOffset                 : -3
+LambdaFromQpEnable            : 1           # see JCTVC-X0038 for suitable parameters for IntraQPOffset, QPoffset, QPOffsetModelOff, QPOffsetModelScale when enabled
+#        Type POC QPoffset QPOffsetModelOff QPOffsetModelScale CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs
+Frame1:  B   16   1        0.0                      0.0            0          0          1.0      0            0              0           2                3         -16 -24 -32            0  
+Frame2:  B    8   1       -4.8848                   0.2061         0          0          1.0      0            0              1           2                3         -8  -16   8            1       8        4         1 1 0 1    
+Frame3:  B    4   4       -5.7476                   0.2286         0          0          1.0      0            0              2           2                4         -4  -12   4  12        1       4        4         1 1 1 1 
+Frame4:  B    2   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                5         -2  -10   2   6  14    1       2        5         1 1 1 1 1 
+Frame5:  B    1   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1    1  3    7  15    1       1        6         1 0 1 1 1 1  
+Frame6:  B    3   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3   1   5  13    1      -2        6         1 1 1 1 1 0 
+Frame7:  B    6   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2   -6   2  10        1      -3        6         0 1 1 1 1 0 
+Frame8:  B    5   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -5   1   3  11    1       1        5         1 1 1 1 1  
+Frame9:  B    7   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3  -7   1   9    1      -2        6         1 1 1 1 1 0 
+Frame10: B   12   4       -5.7476                   0.2286         0          0          1.0      0            0              2           2                3         -4  -12   4            1      -5        6         0 0 1 1 1 0 
+Frame11: B   10   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2  -10   2   6        1       2        4         1 1 1 1 
+Frame12: B    9   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -9   1   3   7    1       1        5         1 1 1 1 1 
+Frame13: B   11   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3 -11   1   5    1      -2        6         1 1 1 1 1 0 
+Frame14: B   14   5       -5.90                     0.2333         0          0          1.0      0            0              3           2                4         -2   -6 -14   2        1      -3        6         0 1 1 1 1 0 
+Frame15: B   13   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -5 -13   1   3    1       1        5         1 1 1 1 1 
+Frame16: B   15   6       -7.1444                   0.3            0          0          1.0      0            0              4           2                5         -1   -3 -7  -15   1    1      -2        6         1 1 1 1 1 0 
 
 #=========== Motion Search =============
 FastSearch                    : 1           # 0:Full search  1:TZ search
-SearchRange                   : 64          # (0: Search range is a Full frame)
+SearchRange                   : 384         # (0: Search range is a Full frame)
+ASR                           : 1           # Adaptive motion search range
+MinSearchWindow               : 96          # Minimum motion search window size for the adaptive window ME
 BipredSearchRange             : 4           # Search range for bi-prediction refinement
 HadamardME                    : 1           # Use of hadamard measure for fractional ME
@@ -108,5 +122,5 @@
 
 #============ Lossless ================
-TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+TransquantBypassEnable     : 0                         # Value of PPS flag.
 CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
 
Index: /trunk/cfg/HM/misc/encoder_lowdelay_main_field_coding.cfg
===================================================================
--- /trunk/cfg/HM/misc/encoder_lowdelay_main_field_coding.cfg	(revision 1412)
+++ /trunk/cfg/HM/misc/encoder_lowdelay_main_field_coding.cfg	(revision 1413)
@@ -1,10 +1,3 @@
 #======== File I/O =====================
-InputFile                     :             # Input filename
-InputBitDepth                 :             # Input bitdepth
-FrameRate                     :             # Frame Rate per second
-FrameSkip                     :             # Number of frames to be skipped in input
-SourceWidth                   :             # Input  frame width
-SourceHeight                  :             # Input  frame height
-FramesToBeEncoded             :             # Number of frames to be coded
 FieldCoding                   : 1           # (0: Frame based coding, 1: Field based coding)
 TopFieldFirst                 : 1           # Field parity order (1: Top field first, 0: Bottom field first)
@@ -39,14 +32,13 @@
 DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
 GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
-
-#        Type POC QPoffset CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures                predict deltaRPS #ref_idcs reference idcs 
-Frame1:  B    2   3        0          0          0.4624   0            0              0           8                8         -1 -2 -9 -10	-17 -18 -25 -26        0
-Frame2:  B    3   4        0          0          0.4624   0            0              0           8                9         -1 -2 -3 -10 -11 -18 -19 -26 -27    1      -1       9         1 1 1 1 1 1 1 1 1
-Frame3:  B    4   2        0          0          0.4624   0            0              0           8                8         -1 -2 -3 -4  -11 -12 -19 -20        1      -1       10        1 1 1 1 1 1 1 0 0 1
-Frame4:  B    5   3        0          0          0.4624   0            0              0           8                9         -1 -2 -3 -4  -5  -12 -13 -20 -21    1      -1       9         1 1 1 1 1 1 1 1 1
-Frame5:  B    6   3        0          0          0.4624   0            0              0           8                8         -1 -2 -5 -6  -13 -14 -21 -22        1      -1       10        1 0 0 1 1 1 1 1 1 1
-Frame6:  B    7   4        0          0          0.4624   0            0              0           8                9         -1 -2 -3 -6  -7  -14 -15 -22 -23    1      -1       9         1 1 1 1 1 1 1 1 1
-Frame7:  B    8   1        0          0          0.578    0            0              0           8                8         -1 -2 -7 -8  -15 -16 -23 -24        1      -1       10        1 0 0 1 1 1 1 1 1 1
-Frame8:  B    9   1        0          0          0.578    0            0              0           8                9         -1 -2 -3 -8  -9  -16 -17 -24 -25    1      -1       9         1 1 1 1 1 1 1 1 1
+#        Type POC QPoffset QPOffsetModelOff QPOffsetModelScale CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures                predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    2   3        0.0                      0.0        0          0          0.4624   0            0              0           8                8         -1 -2 -9 -10	-17 -18 -25 -26        0
+Frame2:  B    3   4        0.0                      0.0        0          0          0.4624   0            0              0           8                9         -1 -2 -3 -10 -11 -18 -19 -26 -27    1      -1       9         1 1 1 1 1 1 1 1 1
+Frame3:  B    4   2        0.0                      0.0        0          0          0.4624   0            0              0           8                8         -1 -2 -3 -4  -11 -12 -19 -20        1      -1       10        1 1 1 1 1 1 1 0 0 1
+Frame4:  B    5   3        0.0                      0.0        0          0          0.4624   0            0              0           8                9         -1 -2 -3 -4  -5  -12 -13 -20 -21    1      -1       9         1 1 1 1 1 1 1 1 1
+Frame5:  B    6   3        0.0                      0.0        0          0          0.4624   0            0              0           8                8         -1 -2 -5 -6  -13 -14 -21 -22        1      -1       10        1 0 0 1 1 1 1 1 1 1
+Frame6:  B    7   4        0.0                      0.0        0          0          0.4624   0            0              0           8                9         -1 -2 -3 -6  -7  -14 -15 -22 -23    1      -1       9         1 1 1 1 1 1 1 1 1
+Frame7:  B    8   1        0.0                      0.0        0          0          0.578    0            0              0           8                8         -1 -2 -7 -8  -15 -16 -23 -24        1      -1       10        1 0 0 1 1 1 1 1 1 1
+Frame8:  B    9   1        0.0                      0.0        0          0          0.578    0            0              0           8                9         -1 -2 -3 -8  -9  -16 -17 -24 -25    1      -1       9         1 1 1 1 1 1 1 1 1
 
 #=========== Motion Search =============
@@ -70,9 +62,9 @@
 
 #=========== Deblock Filter ============
-LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1=constant params in PPS, param = base_param)
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
 LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter)
 LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6
 LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
-DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream)
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
 
 #=========== Misc. ============
@@ -126,6 +118,6 @@
 
 #============ Lossless ================
-TransquantBypassEnableFlag          : 0                # Value of PPS flag.
-CUTransquantBypassFlagForce: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
+TransquantBypassEnable     : 0                         # Value of PPS flag.
+CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
 
 #============ Rate Control ======================
Index: /trunk/cfg/HM/misc/encoder_randomaccess_main_2tids.cfg
===================================================================
--- /trunk/cfg/HM/misc/encoder_randomaccess_main_2tids.cfg	(revision 1412)
+++ /trunk/cfg/HM/misc/encoder_randomaccess_main_2tids.cfg	(revision 1413)
@@ -21,13 +21,13 @@
 DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
 GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
-#        Type POC QPoffset CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
-Frame1:  B    8   1        0          0          0.442    0            0              0           4                4         -8 -10 -12 -16         0
-Frame2:  B    4   2        0          0          0.3536   0            0              0           2                3         -4 -6  4               1       4        5         1 1 0 0 1
-Frame3:  B    2   3        0          0          0.3536   0            0              0           2                4         -2 -4  2 6             1       2        4         1 1 1 1  
-Frame4:  B    1   4        0          0          0.68     0            0              1           2                4         -1  1  3 7             1       1        5         1 0 1 1 1 
-Frame5:  B    3   4        0          0          0.68     0            0              1           2                4         -1 -3  1 5             1      -2        5         1 1 1 1 0
-Frame6:  B    6   3        0          0          0.3536   0            0              0           2                4         -2 -4 -6 2             1      -3        5         1 1 1 1 0
-Frame7:  B    5   4        0          0          0.68     0            0              1           2                4         -1 -5  1 3             1       1        5         1 0 1 1 1  
-Frame8:  B    7   4        0          0          0.68     0            0              1           2                4         -1 -3 -7 1             1      -2        5         1 1 1 1 0
+#        Type POC QPoffset QPOffsetModelOff QPOffsetModelScale CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics reference pictures     predict deltaRPS #ref_idcs reference idcs 
+Frame1:  B    8   1        0.0                      0.0        0          0          0.442    0            0              0           4                4         -8 -10 -12 -16         0
+Frame2:  B    4   2        0.0                      0.0        0          0          0.3536   0            0              0           2                3         -4 -6  4               1       4        5         1 1 0 0 1
+Frame3:  B    2   3        0.0                      0.0        0          0          0.3536   0            0              0           2                4         -2 -4  2 6             1       2        4         1 1 1 1  
+Frame4:  B    1   4        0.0                      0.0        0          0          0.68     0            0              1           2                4         -1  1  3 7             1       1        5         1 0 1 1 1 
+Frame5:  B    3   4        0.0                      0.0        0          0          0.68     0            0              1           2                4         -1 -3  1 5             1      -2        5         1 1 1 1 0
+Frame6:  B    6   3        0.0                      0.0        0          0          0.3536   0            0              0           2                4         -2 -4 -6 2             1      -3        5         1 1 1 1 0
+Frame7:  B    5   4        0.0                      0.0        0          0          0.68     0            0              1           2                4         -1 -5  1 3             1       1        5         1 0 1 1 1  
+Frame8:  B    7   4        0.0                      0.0        0          0          0.68     0            0              1           2                4         -1 -3 -7 1             1      -2        5         1 1 1 1 0
 
 #=========== Motion Search =============
@@ -107,5 +107,5 @@
 
 #============ Lossless ================
-TransquantBypassEnableFlag : 0                         # Value of PPS flag.
+TransquantBypassEnable     : 0                         # Value of PPS flag.
 CUTransquantBypassFlagForce: 0                         # Force transquant bypass mode, when transquant_bypass_enable_flag is enabled
 
Index: /trunk/cfg/HM/misc/encoder_randomaccess_main_field_coding.cfg
===================================================================
--- /trunk/cfg/HM/misc/encoder_randomaccess_main_field_coding.cfg	(revision 1412)
+++ /trunk/cfg/HM/misc/encoder_randomaccess_main_field_coding.cfg	(revision 1413)
@@ -43,22 +43,22 @@
 #                   When EfficientFieldIRAPEnabled=1 is enabled, this has no additional effect
 
-#        Type POC QPoffset CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics  reference pictures   predict deltaRPS #ref_idcs reference idcs 
+#        Type POC QPoffset QPOffsetModelOff QPOffsetModelScale CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics  reference pictures   predict deltaRPS #ref_idcs reference idcs 
               
-Frame1:  B    17  1        0          0          0.442    0            0              0           4                4         -16 -17 -20 -21        0
-Frame2:  B    16  1        0          0          0.442    0            0              0           3                3         -15 -16 1              1       1        5         1 1 0 0 1
-Frame3:  B    8   2        0          0          0.3536   0            0              0           2                4         -7 -8 8 9              1       8        4         1 1 1 1
-Frame4:  B    9   2        0          0          0.3536   0            0              0           2                5         -1 -8 -9 7 8           1      -1        5         1 1 1 1 1
-Frame5:  B    4   3        0          0          0.3536   0            0              0           2                6         -3 -4 4 5 12 13        1       5        6         1 1 1 1 1 1
-Frame6:  B    5   3        0          0          0.3536   0            0              0           2                7         -1 -4 -5 3 4 11 12     1      -1        7         1 1 1 1 1 1 1 
-Frame7:  B    2   3        0          0          0.3536   0            0              0           2                8         -1 -2 2 3 6 7 14 15    1       3        8         1 1 1 1 1 1 1 1  
-Frame8:  B    3   4        0          0          0.68     0            0              0           2                8         -1 -2 1 2 5 6 13 14    1      -1        9         1 0 1 1 1 1 1 1 1 
-Frame9:  B    6   3        0          0          0.3536   0            0              0           2                6         -1 -2 2 3 10 11        1      -3        9         0 0 1 1 1 1 1 1 0
-Frame10: B    7   4        0          0          0.68     0            0              0           2                7         -1 -2 -3 1 2 9 10      1      -1        7         1 1 1 1 1 1 1 
-Frame11: B    12  3        0          0          0.3536   0            0              0           2                4         -3 -4 4 5              1      -5        8         0 0 0 1 1 1 1 0
-Frame12: B    13  3        0          0          0.3536   0            0              0           2                5         -1 -4 -5 3 4           1      -1        5         1 1 1 1 1
-Frame13: B    10  3        0          0          0.3536   0            0              0           2                6         -1 -2 2 3 6 7          1       3        6         1 1 1 1 1 1
-Frame14: B    11  4        0          0          0.68     0            0              0           2                7         -1 -2 -3 1 2 5 6       1      -1        7         1 1 1 1 1 1 1
-Frame15: B    14  3        0          0          0.3536   0            0              0           2                5         -1 -2 -5 2 3           1      -3        8         0 1 0 1 1 1 1 0
-Frame16: B    15  4        0          0          0.68     0            0              0           2                6         -1 -2 -3 -6 1 2        1      -1        6         1 1 1 1 1 1 
+Frame1:  B    17  1        0.0                      0.0        0          0          0.442    0            0              0           4                4         -16 -17 -20 -21        0
+Frame2:  B    16  1        0.0                      0.0        0          0          0.442    0            0              0           3                3         -15 -16 1              1       1        5         1 1 0 0 1
+Frame3:  B    8   2        0.0                      0.0        0          0          0.3536   0            0              0           2                4         -7 -8 8 9              1       8        4         1 1 1 1
+Frame4:  B    9   2        0.0                      0.0        0          0          0.3536   0            0              0           2                5         -1 -8 -9 7 8           1      -1        5         1 1 1 1 1
+Frame5:  B    4   3        0.0                      0.0        0          0          0.3536   0            0              0           2                6         -3 -4 4 5 12 13        1       5        6         1 1 1 1 1 1
+Frame6:  B    5   3        0.0                      0.0        0          0          0.3536   0            0              0           2                7         -1 -4 -5 3 4 11 12     1      -1        7         1 1 1 1 1 1 1 
+Frame7:  B    2   3        0.0                      0.0        0          0          0.3536   0            0              0           2                8         -1 -2 2 3 6 7 14 15    1       3        8         1 1 1 1 1 1 1 1  
+Frame8:  B    3   4        0.0                      0.0        0          0          0.68     0            0              0           2                8         -1 -2 1 2 5 6 13 14    1      -1        9         1 0 1 1 1 1 1 1 1 
+Frame9:  B    6   3        0.0                      0.0        0          0          0.3536   0            0              0           2                6         -1 -2 2 3 10 11        1      -3        9         0 0 1 1 1 1 1 1 0
+Frame10: B    7   4        0.0                      0.0        0          0          0.68     0            0              0           2                7         -1 -2 -3 1 2 9 10      1      -1        7         1 1 1 1 1 1 1 
+Frame11: B    12  3        0.0                      0.0        0          0          0.3536   0            0              0           2                4         -3 -4 4 5              1      -5        8         0 0 0 1 1 1 1 0
+Frame12: B    13  3        0.0                      0.0        0          0          0.3536   0            0              0           2                5         -1 -4 -5 3 4           1      -1        5         1 1 1 1 1
+Frame13: B    10  3        0.0                      0.0        0          0          0.3536   0            0              0           2                6         -1 -2 2 3 6 7          1       3        6         1 1 1 1 1 1
+Frame14: B    11  4        0.0                      0.0        0          0          0.68     0            0              0           2                7         -1 -2 -3 1 2 5 6       1      -1        7         1 1 1 1 1 1 1
+Frame15: B    14  3        0.0                      0.0        0          0          0.3536   0            0              0           2                5         -1 -2 -5 2 3           1      -3        8         0 1 0 1 1 1 1 0
+Frame16: B    15  4        0.0                      0.0        0          0          0.68     0            0              0           2                6         -1 -2 -3 -6 1 2        1      -1        6         1 1 1 1 1 1 
 
 #=========== Motion Search =============
@@ -138,5 +138,5 @@
 
 #============ Lossless ================
-TransquantBypassEnableFlag: 0  # Value of PPS flag.
+TransquantBypassEnable     : 0  # Value of PPS flag.
 CUTransquantBypassFlagForce: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
 
Index: /trunk/cfg/HM/misc/encoder_randomaccess_main_field_coding_simple_GOP.cfg
===================================================================
--- /trunk/cfg/HM/misc/encoder_randomaccess_main_field_coding_simple_GOP.cfg	(revision 1412)
+++ /trunk/cfg/HM/misc/encoder_randomaccess_main_field_coding_simple_GOP.cfg	(revision 1413)
@@ -42,22 +42,22 @@
 # simple field coding GOP: When EfficientFieldIRAPEnabled=1 is enabled, the order of frames 16 and 17 is exchanged
 
-#        Type POC QPoffset CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics  reference pictures   predict deltaRPS #ref_idcs reference idcs 
+#        Type POC QPoffset QPOffsetModelOff QPOffsetModelScale CbQPoffset CrQPoffset QPfactor tcOffsetDiv2 betaOffsetDiv2 temporal_id #ref_pics_active #ref_pics  reference pictures   predict deltaRPS #ref_idcs reference idcs 
               
-Frame1:  B    16  1        0          0          0.442    0            0              0           8                8         -15 -16 -19 -20 -23 -24 -31 -32        0
-Frame2:  B    17  1        0          0          0.442    0            0              0           4                9         -1  -16 -17 -20 -21 -24 -25 -32 -33    1      -1        9         1 1 1 1 1 1 1 1 1
-Frame3:  B    8   2        0          0          0.3536   0            0              0           4                6         -7  -8  -11 -12  8   9                 1       9        10        1 1 1 1 1 0 0 0 0 1
-Frame4:  B    9   3        0          0          0.3536   0            0              0           4                7         -1  -8  -9  -12 -13  7   8             1      -1        7         1 1 1 1 1 1 1
-Frame5:  B    4   3        0          0          0.3536   0            0              0           4                8         -3  -4  -7  -8   4   5   12  13        1       5        8         1 1 1 1 1 1 1 1
-Frame6:  B    5   4        0          0          0.68     0            0              0           4                9         -1  -4  -5  -8  -9   3   4   11  12    1      -1        9         1 1 1 1 1 1 1 1 1 
-Frame7:  B    2   3        0          0          0.3536   0            0              0           4                8         -1  -2   2   3   6   7   14  15        1       3        10        1 1 1 0 0 1 1 1 1 1  
-Frame8:  B    3   4        0          0          0.68     0            0              0           4                9         -1  -2  -3   1   2   5   6   13  14    1      -1        9         1 1 1 1 1 1 1 1 1 
-Frame9:  B    6   3        0          0          0.3536   0            0              0           4                8         -1  -2  -5  -6   2   3   10  11        1      -3        10        0 1 1 1 1 1 1 1 1 0
-Frame10: B    7   4        0          0          0.68     0            0              0           4                9         -1  -2  -3  -6  -7   1   2   9   10    1      -1        9         1 1 1 1 1 1 1 1 1 
-Frame11: B    12  3        0          0          0.3536   0            0              0           4                8         -3  -4  -7  -8  -11 -12  4   5         1      -5        10        0 1 1 1 1 1 1 1 1 0
-Frame12: B    13  4        0          0          0.68     0            0              0           4                9         -1  -4  -5  -8  -9  -12 -13  3   4     1      -1        9         1 1 1 1 1 1 1 1 1
-Frame13: B    10  3        0          0          0.3536   0            0              0           4                8         -1  -2  -9  -10  2   3   6   7         1       3        10        1 1 1 0 0 1 1 1 1 1
-Frame14: B    11  4        0          0          0.68     0            0              0           4                9         -1  -2  -3  -10 -11  1   2   5   6     1      -1        9         1 1 1 1 1 1 1 1 1
-Frame15: B    14  3        0          0          0.3536   0            0              0           4                8         -1  -2  -5  -6  -13 -14  2   3         1      -3        10        0 1 1 1 1 1 1 1 1 0
-Frame16: B    15  4        0          0          0.68     0            0              0           4                9         -1  -2  -3  -6  -7  -14 -15  1   2     1      -1        9         1 1 1 1 1 1 1 1 1  
+Frame1:  B    16  1        0.0                      0.0        0          0          0.442    0            0              0           8                8         -15 -16 -19 -20 -23 -24 -31 -32        0
+Frame2:  B    17  1        0.0                      0.0        0          0          0.442    0            0              0           4                9         -1  -16 -17 -20 -21 -24 -25 -32 -33    1      -1        9         1 1 1 1 1 1 1 1 1
+Frame3:  B    8   2        0.0                      0.0        0          0          0.3536   0            0              0           4                6         -7  -8  -11 -12  8   9                 1       9        10        1 1 1 1 1 0 0 0 0 1
+Frame4:  B    9   3        0.0                      0.0        0          0          0.3536   0            0              0           4                7         -1  -8  -9  -12 -13  7   8             1      -1        7         1 1 1 1 1 1 1
+Frame5:  B    4   3        0.0                      0.0        0          0          0.3536   0            0              0           4                8         -3  -4  -7  -8   4   5   12  13        1       5        8         1 1 1 1 1 1 1 1
+Frame6:  B    5   4        0.0                      0.0        0          0          0.68     0            0              0           4                9         -1  -4  -5  -8  -9   3   4   11  12    1      -1        9         1 1 1 1 1 1 1 1 1 
+Frame7:  B    2   3        0.0                      0.0        0          0          0.3536   0            0              0           4                8         -1  -2   2   3   6   7   14  15        1       3        10        1 1 1 0 0 1 1 1 1 1  
+Frame8:  B    3   4        0.0                      0.0        0          0          0.68     0            0              0           4                9         -1  -2  -3   1   2   5   6   13  14    1      -1        9         1 1 1 1 1 1 1 1 1 
+Frame9:  B    6   3        0.0                      0.0        0          0          0.3536   0            0              0           4                8         -1  -2  -5  -6   2   3   10  11        1      -3        10        0 1 1 1 1 1 1 1 1 0
+Frame10: B    7   4        0.0                      0.0        0          0          0.68     0            0              0           4                9         -1  -2  -3  -6  -7   1   2   9   10    1      -1        9         1 1 1 1 1 1 1 1 1 
+Frame11: B    12  3        0.0                      0.0        0          0          0.3536   0            0              0           4                8         -3  -4  -7  -8  -11 -12  4   5         1      -5        10        0 1 1 1 1 1 1 1 1 0
+Frame12: B    13  4        0.0                      0.0        0          0          0.68     0            0              0           4                9         -1  -4  -5  -8  -9  -12 -13  3   4     1      -1        9         1 1 1 1 1 1 1 1 1
+Frame13: B    10  3        0.0                      0.0        0          0          0.3536   0            0              0           4                8         -1  -2  -9  -10  2   3   6   7         1       3        10        1 1 1 0 0 1 1 1 1 1
+Frame14: B    11  4        0.0                      0.0        0          0          0.68     0            0              0           4                9         -1  -2  -3  -10 -11  1   2   5   6     1      -1        9         1 1 1 1 1 1 1 1 1
+Frame15: B    14  3        0.0                      0.0        0          0          0.3536   0            0              0           4                8         -1  -2  -5  -6  -13 -14  2   3         1      -3        10        0 1 1 1 1 1 1 1 1 0
+Frame16: B    15  4        0.0                      0.0        0          0          0.68     0            0              0           4                9         -1  -2  -3  -6  -7  -14 -15  1   2     1      -1        9         1 1 1 1 1 1 1 1 1  
 
 #=========== Motion Search =============
@@ -137,5 +137,5 @@
 
 #============ Lossless ================
-TransquantBypassEnableFlag: 0  # Value of PPS flag.
+TransquantBypassEnable     : 0  # Value of PPS flag.
 CUTransquantBypassFlagForce: 0 # Constant lossless-value signaling per CU, if TransquantBypassEnableFlag is 1.
 
Index: /trunk/cfg/HM/per-sequence/Campfire.cfg
===================================================================
--- /trunk/cfg/HM/per-sequence/Campfire.cfg	(revision 1413)
+++ /trunk/cfg/HM/per-sequence/Campfire.cfg	(revision 1413)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : Campfire_3840x2160_30fps_10bit_420_bt709_videoRange.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 3840        # Input  frame width
+SourceHeight                  : 2160        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 5.1
Index: /trunk/cfg/HM/per-sequence/CatRobot.cfg
===================================================================
--- /trunk/cfg/HM/per-sequence/CatRobot.cfg	(revision 1413)
+++ /trunk/cfg/HM/per-sequence/CatRobot.cfg	(revision 1413)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : CatRobot_3840x2160_60fps_10bit_420_jvet.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 3840        # Input  frame width
+SourceHeight                  : 2160        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 5.1
Index: /trunk/cfg/HM/per-sequence/DaylightRoad2.cfg
===================================================================
--- /trunk/cfg/HM/per-sequence/DaylightRoad2.cfg	(revision 1413)
+++ /trunk/cfg/HM/per-sequence/DaylightRoad2.cfg	(revision 1413)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : DaylightRoad2_3840x2160_60fps_10bit_420.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 3840        # Input  frame width
+SourceHeight                  : 2160        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 5.1
Index: /trunk/cfg/HM/per-sequence/Drums100.cfg
===================================================================
--- /trunk/cfg/HM/per-sequence/Drums100.cfg	(revision 1413)
+++ /trunk/cfg/HM/per-sequence/Drums100.cfg	(revision 1413)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : Drums_3840x2160_100fps_10bit_420_jvet.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 100          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 3840        # Input  frame width
+SourceHeight                  : 2160        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 5.2
Index: /trunk/cfg/HM/per-sequence/Robot_444.cfg
===================================================================
--- /trunk/cfg/HM/per-sequence/Robot_444.cfg	(revision 1413)
+++ /trunk/cfg/HM/per-sequence/Robot_444.cfg	(revision 1413)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_robot_1280x720_30_8bit_300_444.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 6.2
Index: /trunk/cfg/HM/per-sequence/Robot_RGB.cfg
===================================================================
--- /trunk/cfg/HM/per-sequence/Robot_RGB.cfg	(revision 1413)
+++ /trunk/cfg/HM/per-sequence/Robot_RGB.cfg	(revision 1413)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_robot_1280x720_30_8bit_300.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: /trunk/cfg/HM/per-sequence/Rollercoaster2.cfg
===================================================================
--- /trunk/cfg/HM/per-sequence/Rollercoaster2.cfg	(revision 1413)
+++ /trunk/cfg/HM/per-sequence/Rollercoaster2.cfg	(revision 1413)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : RollerCoaster2_3840x2160_60fps_10bit_420.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 3840        # Input  frame width
+SourceHeight                  : 2160        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 5.1
Index: /trunk/cfg/HM/per-sequence/Tango2.cfg
===================================================================
--- /trunk/cfg/HM/per-sequence/Tango2.cfg	(revision 1413)
+++ /trunk/cfg/HM/per-sequence/Tango2.cfg	(revision 1413)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : Tango2_3840x2160_60fps_10bit_420.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 3840        # Input  frame width
+SourceHeight                  : 2160        # Input  frame height
+FramesToBeEncoded             : 294         # Number of frames to be coded
+
+Level                         : 5.1
Index: /trunk/cfg/HM/per-sequence/ToddlerFountain2.cfg
===================================================================
--- /trunk/cfg/HM/per-sequence/ToddlerFountain2.cfg	(revision 1413)
+++ /trunk/cfg/HM/per-sequence/ToddlerFountain2.cfg	(revision 1413)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : ToddlerFountain2_3840x2160_60fps_10bit_420.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 60          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 3840        # Input  frame width
+SourceHeight                  : 2160        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 5.1
Index: /trunk/cfg/HM/per-sequence/TrafficFlow.cfg
===================================================================
--- /trunk/cfg/HM/per-sequence/TrafficFlow.cfg	(revision 1413)
+++ /trunk/cfg/HM/per-sequence/TrafficFlow.cfg	(revision 1413)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : TrafficFlow_3840x2160_30fps_10bit_420_jvet.yuv
+InputBitDepth                 : 10          # Input bitdepth
+InputChromaFormat             : 420         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 3840        # Input  frame width
+SourceHeight                  : 2160        # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 5
Index: /trunk/cfg/HM/per-sequence/Viking_444.cfg
===================================================================
--- /trunk/cfg/HM/per-sequence/Viking_444.cfg	(revision 1413)
+++ /trunk/cfg/HM/per-sequence/Viking_444.cfg	(revision 1413)
@@ -0,0 +1,11 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_444/sc_viking_1280x720_30_8bit_300_444.yuv
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+
+Level                         : 6.2
Index: /trunk/cfg/HM/per-sequence/Viking_RGB.cfg
===================================================================
--- /trunk/cfg/HM/per-sequence/Viking_RGB.cfg	(revision 1413)
+++ /trunk/cfg/HM/per-sequence/Viking_RGB.cfg	(revision 1413)
@@ -0,0 +1,14 @@
+#======== File I/O ===============
+InputFile                     : HEVC_yuv/ScreenContent_RGB/sc_viking_1280x720_30_8bit_300.rgb
+InputBitDepth                 : 8           # Input bitdepth
+InputChromaFormat             : 444         # Ratio of luminance to chrominance samples
+FrameRate                     : 30          # Frame Rate per second
+FrameSkip                     : 0           # Number of frames to be skipped in input
+SourceWidth                   : 1280        # Input  frame width
+SourceHeight                  : 720         # Input  frame height
+FramesToBeEncoded             : 300         # Number of frames to be coded
+InputColourSpaceConvert       : RGBtoGBR    # Non-normative colour space conversion to apply to input video
+SNRInternalColourSpace        : 1           # Evaluate SNRs in GBR order
+OutputInternalColourSpace     : 0           # Convert recon output back to RGB order. Use --OutputColourSpaceConvert GBRtoRGB on decoder to produce a matching output file.
+
+Level                         : 6.2
Index: /trunk/cfg/MV-HEVC/NonCTC/fullCfg_63view.cfg
===================================================================
--- /trunk/cfg/MV-HEVC/NonCTC/fullCfg_63view.cfg	(revision 1413)
+++ /trunk/cfg/MV-HEVC/NonCTC/fullCfg_63view.cfg	(revision 1413)
@@ -0,0 +1,545 @@
+#======== Legend for comments ===================== 
+# (m) specification per layer/dimension/layerset possible
+# (c) cyclic repetition of values, if not given for all layers/dimensions/layersets. (e.g. 5 layers and 1 2 3 -> 1 2 3 1 2  )
+
+#======== File I/O =====================
+
+InputFile_0                   :                              
+InputFile_1                   : 
+InputFile_2                   : 
+InputFile_3                   : 
+InputFile_4                   : 
+InputFile_5                   : 
+InputFile_6                   : 
+InputFile_7                   : 
+InputFile_8                   : 
+InputFile_9                   : 
+InputFile_10                  : 
+InputFile_11                  : 
+InputFile_12                  : 
+InputFile_13                  : 
+InputFile_14                  : 
+InputFile_15                  : 
+InputFile_16                  : 
+InputFile_17                  : 
+InputFile_18                  : 
+InputFile_19                  : 
+InputFile_20                  : 
+InputFile_21                  : 
+InputFile_22                  : 
+InputFile_23                  : 
+InputFile_24                  : 
+InputFile_25                  : 
+InputFile_26                  : 
+InputFile_27                  : 
+InputFile_28                  : 
+InputFile_29                  : 
+InputFile_30                  : 
+InputFile_31                  : 
+InputFile_32                  : 
+InputFile_33                  : 
+InputFile_34                  : 
+InputFile_35                  : 
+InputFile_36                  : 
+InputFile_37                  : 
+InputFile_38                  : 
+InputFile_39                  : 
+InputFile_40                  : 
+InputFile_41                  : 
+InputFile_42                  : 
+InputFile_43                  : 
+InputFile_44                  : 
+InputFile_45                  : 
+InputFile_46                  : 
+InputFile_47                  : 
+InputFile_48                  : 
+InputFile_49                  : 
+InputFile_50                  : 
+InputFile_51                  : 
+InputFile_52                  : 
+InputFile_53                  : 
+InputFile_54                  : 
+InputFile_55                  : 
+InputFile_56                  : 
+InputFile_57                  : 
+InputFile_58                  : 
+InputFile_59                  : 
+InputFile_60                  : 
+InputFile_61                  : 
+InputFile_62                  : 
+InputFile_63                  :
+InputFile_64                  :
+InputFile_65                  :
+InputFile_66                  :
+InputFile_67                  :
+InputFile_68                  :
+InputFile_69                  :
+InputFile_70                  :
+InputFile_71                  :
+InputFile_72                  :
+InputFile_73                  :
+InputFile_74                  :
+InputFile_75                  :
+InputFile_76                  :
+InputFile_77                  :
+InputFile_78                  :
+InputFile_79                  :
+InputFile_80                  :
+InputFile_81                  :
+InputFile_82                  :
+InputFile_83                  :
+InputFile_84                  :
+InputFile_85                  :
+InputFile_86                  :
+InputFile_87                  :
+InputFile_88                  :
+InputFile_89                  :
+InputFile_90                  :
+InputFile_91                  :
+InputFile_92                  :
+InputFile_93                  :
+InputFile_94                  :
+InputFile_95                  :
+InputFile_96                  :
+InputFile_97                  :
+InputFile_98                  :
+InputFile_99                  :
+InputFile_100                 :
+InputFile_101                 :
+InputFile_102                 :
+InputFile_103                 :
+InputFile_104                 :
+InputFile_105                 :
+InputFile_106                 :
+InputFile_107                 :
+InputFile_108                 :
+InputFile_109                 :
+InputFile_110                 :
+InputFile_111                 :
+InputFile_112                 :
+InputFile_113                 :
+InputFile_114                 :
+InputFile_115                 :
+InputFile_116                 :
+InputFile_117                 :
+InputFile_118                 :
+InputFile_119                 :
+InputFile_120                 :
+InputFile_121                 :
+InputFile_122                 :
+InputFile_123                 :
+InputFile_124                 :
+InputFile_125                 :
+InputFile_126                 :
+InputFile_127                 :
+
+
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   :                              
+ReconFile_1                   : 
+ReconFile_2                   : 
+ReconFile_3                   : 
+ReconFile_4                   : 
+ReconFile_5                   : 
+ReconFile_6                   : 
+ReconFile_7                   : 
+ReconFile_8                   : 
+ReconFile_9                   : 
+ReconFile_10                  : 
+ReconFile_11                  : 
+ReconFile_12                  : 
+ReconFile_13                  : 
+ReconFile_14                  : 
+ReconFile_15                  : 
+ReconFile_16                  : 
+ReconFile_17                  : 
+ReconFile_18                  : 
+ReconFile_19                  : 
+ReconFile_20                  : 
+ReconFile_21                  : 
+ReconFile_22                  : 
+ReconFile_23                  : 
+ReconFile_24                  : 
+ReconFile_25                  : 
+ReconFile_26                  : 
+ReconFile_27                  : 
+ReconFile_28                  : 
+ReconFile_29                  : 
+ReconFile_30                  : 
+ReconFile_31                  : 
+ReconFile_32                  : 
+ReconFile_33                  : 
+ReconFile_34                  : 
+ReconFile_35                  : 
+ReconFile_36                  : 
+ReconFile_37                  : 
+ReconFile_38                  : 
+ReconFile_39                  : 
+ReconFile_40                  : 
+ReconFile_41                  : 
+ReconFile_42                  : 
+ReconFile_43                  : 
+ReconFile_44                  : 
+ReconFile_45                  : 
+ReconFile_46                  : 
+ReconFile_47                  : 
+ReconFile_48                  : 
+ReconFile_49                  : 
+ReconFile_50                  : 
+ReconFile_51                  : 
+ReconFile_52                  : 
+ReconFile_53                  : 
+ReconFile_54                  : 
+ReconFile_55                  : 
+ReconFile_56                  : 
+ReconFile_57                  : 
+ReconFile_58                  : 
+ReconFile_59                  : 
+ReconFile_60                  : 
+ReconFile_61                  : 
+ReconFile_62                  : 
+ReconFile_63                  :
+ReconFile_64                  :
+ReconFile_65                  :
+ReconFile_66                  :
+ReconFile_67                  :
+ReconFile_68                  :
+ReconFile_69                  :
+ReconFile_70                  :
+ReconFile_71                  :
+ReconFile_72                  :
+ReconFile_73                  :
+ReconFile_74                  :
+ReconFile_75                  :
+ReconFile_76                  :
+ReconFile_77                  :
+ReconFile_78                  :
+ReconFile_79                  :
+ReconFile_80                  :
+ReconFile_81                  :
+ReconFile_82                  :
+ReconFile_83                  :
+ReconFile_84                  :
+ReconFile_85                  :
+ReconFile_86                  :
+ReconFile_87                  :
+ReconFile_88                  :
+ReconFile_89                  :
+ReconFile_90                  :
+ReconFile_91                  :
+ReconFile_92                  :
+ReconFile_93                  :
+ReconFile_94                  :
+ReconFile_95                  :
+ReconFile_96                  :
+ReconFile_97                  :
+ReconFile_98                  :
+ReconFile_99                  :
+ReconFile_100                 :
+ReconFile_101                 :
+ReconFile_102                 :
+ReconFile_103                 :
+ReconFile_104                 :
+ReconFile_105                 :
+ReconFile_106                 :
+ReconFile_107                 :
+ReconFile_108                 :
+ReconFile_109                 :
+ReconFile_110                 :
+ReconFile_111                 :
+ReconFile_112                 :
+ReconFile_113                 :
+ReconFile_114                 :
+ReconFile_115                 :
+ReconFile_116                 :
+ReconFile_117                 :
+ReconFile_118                 :
+ReconFile_119                 :
+ReconFile_120                 :
+ReconFile_121                 :
+ReconFile_122                 :
+ReconFile_123                 :
+ReconFile_124                 :
+ReconFile_125                 :
+ReconFile_126                 :
+ReconFile_127                 :
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+NumberOfLayers                : 63           # Number of layers
+
+TargetEncLayerIdList          :             # Layer Id in Nuh to be encoded, (empty:-> all layers will be encode) 
+
+FramesToBeEncoded             : 3           # Number of frames to be coded
+FrameRate                     : 30          # Frame Rate per second
+SourceWidth                   : 1024        # Input  frame width
+SourceHeight                  : 768         # Input  frame height
+
+
+OutputVpsInfo                 : 0           # Output VPS information
+
+
+#======== VPS ============================
+ScalabilityMask               : 2           # Scalability Mask             ( Scalability Mask: 2: Multiview, 8: Auxiliary, 10: Multiview + Auxiliary )
+DimensionIdLen                : 8           # Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex                : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62        # ViewOrderIndex, per layer (m)
+LayerIdInNuh                  : 0           # Layer Id in NAL unit header, (0: no explicit signalling, otherwise per layer ) (m)
+SplittingFlag                 : 0           # Splitting Flag 
+ViewId                        : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62        # ViewId, per ViewOrderIndex (m)
+AuxId                         :             # Auxiliary Id, per layer (m)
+
+#======== VPS / Layer sets ================
+VpsNumLayerSets               : 2            # Number of layer sets    
+LayerIdsInSet_0               : 0            # Indices in VPS of layers in layer set 0
+LayerIdsInSet_1               : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 # Indices in VPS of layers in layer set 1
+
+
+ShareParameterSets            : 1
+
+
+
+
+
+#======== VPS / Output layer sets ================
+DefaultTargetOutputLayerIdc   : 0            # Specifies output layers of layer sets, 0: output all layers, 1: output highest layer, 2: specified by LayerIdsInDefOutputLayerSet
+
+OutputLayerSetIdx             :              # Indices of layer sets used to derive additional output layer sets
+
+#======== VPS / PTLI ================
+Profile                       : main main multiview-main   # Profile indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+Level                         : none none none             # Level   indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+Tier                          : main main main             # Tier    indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+InblFlag                      : 0    0    0                # Inbl    indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+
+ProfileTierLevelIdx_0         : 1                          # VpsProfileTierLevel indices of layers in output layer set 0 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_1         : 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1             : 0           # Indices in VPS of direct reference layers 
+DirectRefLayers_2             : 1            # Indices in VPS of direct reference layers 
+DirectRefLayers_3             : 2            # Indices in VPS of direct reference layers 
+DirectRefLayers_4             : 3            # Indices in VPS of direct reference layers 
+DirectRefLayers_5             : 0            # Indices in VPS of direct reference layers 
+DirectRefLayers_6             : 5       
+DirectRefLayers_7             : 6       
+DirectRefLayers_8             : 7       
+DirectRefLayers_9             : 0       
+DirectRefLayers_10            : 9       
+DirectRefLayers_11            : 10    
+DirectRefLayers_12            : 11      
+DirectRefLayers_13            : 0       
+DirectRefLayers_14            : 13      
+DirectRefLayers_15            : 14      
+DirectRefLayers_16            : 15    
+DirectRefLayers_17            : 0      
+DirectRefLayers_18            : 17      
+DirectRefLayers_19            : 18      
+DirectRefLayers_20            : 19      
+DirectRefLayers_21            : 0     
+DirectRefLayers_22            : 21      
+DirectRefLayers_23            : 22      
+DirectRefLayers_24            : 23      
+DirectRefLayers_25            : 0     
+DirectRefLayers_26            : 25    
+DirectRefLayers_27            : 26      
+DirectRefLayers_28            : 27      
+DirectRefLayers_29            : 0       
+DirectRefLayers_30            : 29      
+DirectRefLayers_31            : 30    
+DirectRefLayers_32            : 31      
+DirectRefLayers_33            : 0       
+DirectRefLayers_34            : 33      
+DirectRefLayers_35            : 34      
+DirectRefLayers_36            : 35    
+DirectRefLayers_37            : 0       
+DirectRefLayers_38            : 37      
+DirectRefLayers_39            : 38      
+DirectRefLayers_40            : 39      
+DirectRefLayers_41            : 0     
+DirectRefLayers_42            : 41      
+DirectRefLayers_43            : 42      
+DirectRefLayers_44            : 43      
+DirectRefLayers_45            : 0       
+DirectRefLayers_46            : 45    
+DirectRefLayers_47            : 46      
+DirectRefLayers_48            : 47      
+DirectRefLayers_49            : 0       
+DirectRefLayers_50            : 49      
+DirectRefLayers_51            : 50    
+DirectRefLayers_52            : 51      
+DirectRefLayers_53            : 0       
+DirectRefLayers_54            : 53      
+DirectRefLayers_55            : 54      
+DirectRefLayers_56            : 55    
+DirectRefLayers_57            : 0      
+DirectRefLayers_58            : 57      
+DirectRefLayers_59            : 58      
+DirectRefLayers_60            : 59      
+DirectRefLayers_61            : 0     
+DirectRefLayers_62            : 61      
+
+
+DependencyTypes_1              : 2           # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_2              : 2           # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_3              : 2           # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_4              : 2           # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_5              : 2           # Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_6              : 2
+DependencyTypes_7              : 2
+DependencyTypes_8              : 2
+DependencyTypes_9              : 2
+DependencyTypes_10             : 2
+DependencyTypes_11             : 2
+DependencyTypes_12             : 2
+DependencyTypes_13             : 2
+DependencyTypes_14             : 2
+DependencyTypes_15             : 2
+DependencyTypes_16             : 2
+DependencyTypes_17             : 2
+DependencyTypes_18             : 2
+DependencyTypes_19             : 2
+DependencyTypes_20             : 2
+DependencyTypes_21             : 2
+DependencyTypes_22             : 2
+DependencyTypes_23             : 2
+DependencyTypes_24             : 2
+DependencyTypes_25             : 2
+DependencyTypes_26             : 2
+DependencyTypes_27             : 2
+DependencyTypes_28             : 2
+DependencyTypes_29             : 2
+DependencyTypes_30             : 2
+DependencyTypes_31             : 2
+DependencyTypes_32             : 2
+DependencyTypes_33             : 2
+DependencyTypes_34             : 2
+DependencyTypes_35             : 2
+DependencyTypes_36             : 2
+DependencyTypes_37             : 2
+DependencyTypes_38             : 2
+DependencyTypes_39             : 2
+DependencyTypes_40             : 2
+DependencyTypes_41             : 2
+DependencyTypes_42             : 2
+DependencyTypes_43             : 2
+DependencyTypes_44             : 2
+DependencyTypes_45             : 2
+DependencyTypes_46             : 2
+DependencyTypes_47             : 2
+DependencyTypes_48             : 2
+DependencyTypes_49             : 2
+DependencyTypes_50             : 2
+DependencyTypes_51             : 2
+DependencyTypes_52             : 2
+DependencyTypes_53             : 2
+DependencyTypes_54             : 2
+DependencyTypes_55             : 2
+DependencyTypes_56             : 2
+DependencyTypes_57             : 2
+DependencyTypes_58             : 2
+DependencyTypes_59             : 2
+DependencyTypes_60             : 2
+DependencyTypes_61             : 2
+DependencyTypes_62             : 2
+
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 24          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+
+#                      CbQPoffset    QPfactor     betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset  CrQPoffset  tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+
+Frame1:     B    8     1    0  0     0.442    0        0        0        4      4     -8 -10 -12 -16     0      0
+Frame2:     B    4     2    0  0     0.3536   0        0        0        2      3     -4 -6  4           1      4    5     1 1 0 0 1         0
+Frame3:     B    2     3    0  0     0.3536   0        0        0        2      4     -2 -4  2 6         1      2    4     1 1 1 1           0
+Frame4:     B    1     4    0  0     0.68     0        0        0        2      4     -1  1  3 7         1      1    5     1 0 1 1 1         0
+Frame5:     B    3     4    0  0     0.68     0        0        0        2      4     -1 -3  1 5         1     -2    5     1 1 1 1 0         0
+Frame6:     B    6     3    0  0     0.3536   0        0        0        2      4     -2 -4 -6 2         1     -3    5     1 1 1 1 0         0
+Frame7:     B    5     4    0  0     0.68     0        0        0        2      4     -1 -5  1 3         1      1    5     1 0 1 1 1         0
+Frame8:     B    7     4    0  0     0.68     0        0        0        2      4     -1 -3 -7 1         1     -2    5     1 1 1 1 0         0
+                                     
+FrameI_l1:  P    0     3    0  0     0.442    0        0        0        1      0                        0                                   1          0         0          -1        
+Frame1_l1:  B    8     4    0  0     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   1          0         1          -1        
+Frame2_l1:  B    4     5    0  0     0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1         1          0         1          -1        
+Frame3_l1:  B    2     6    0  0     0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1           1          0         1          -1        
+Frame4_l1:  B    1     7    0  0     0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1         1          0         1          -1        
+Frame5_l1:  B    3     7    0  0     0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0         1          0         2          -1        
+Frame6_l1:  B    6     6    0  0     0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0         1          0         2          -1        
+Frame7_l1:  B    5     7    0  0     0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1         1          0         2          -1        
+Frame8_l1:  B    7     7    0  0     0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0         1          0         2          -1        
+                                    
+
+LayerIdxInVpsToGopDefIdx      : 0  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1  1    # Maps layerIdx in Vps to GOP definition (per layer)
+
+
+
+
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+DispSearchRangeRestriction    : 1           # Limit Search range for vertical component of disparity vector
+VerticalDispSearchRange       : 56          # Vertical Search range in pixel
+
+#======== Quantization =============
+QP                            : 25
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+SliceChromaQPOffsetPeriodicity: 0           # Used in conjunction with Slice Cb/Cr QpOffsetIntraOrPeriodic. Use 0 (default) to disable periodic nature.
+SliceCbQpOffsetIntraOrPeriodic: 0           # Chroma Cb QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
+SliceCrQpOffsetIntraOrPeriodic: 0           # Chroma Cr QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Misc. ============
+InternalBitDepth              : 8           # codec operating bit-depth
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON) (mc)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /trunk/cfg/MV-HEVC/NonConforming/delta_aux_3view.cfg
===================================================================
--- /trunk/cfg/MV-HEVC/NonConforming/delta_aux_3view.cfg	(revision 1413)
+++ /trunk/cfg/MV-HEVC/NonConforming/delta_aux_3view.cfg	(revision 1413)
@@ -0,0 +1,158 @@
+#======== Legend for comments ===================== 
+# (m) specification per layer/dimension/layerset possible
+# (c) cyclic repetition of values, if not given for all layers/dimensions/layersets. (e.g. 5 layers and 1 2 3 -> 1 2 3 1 2  )
+
+
+NumberOfLayers         : 6       
+
+#======== VPS ============================
+ScalabilityMask        : 10        # Scalability Mask             ( Scalability Mask: 2: Multiview, 8: Auxiliary, 10: Multiview + Auxiliary )
+DimensionIdLen         : 4 4       #  Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex         : 0 0 1 1 2 2    #  # ViewOrderIndex, per layer (m)
+AuxId                  : 0 2 0 2 0 2 # Auxiliary Id, per layer (m), ( 0: none, 1: Alpha, 2: Depth )
+LayerIdInNuh           : 0 1 2 3 4 5   #  Layer Id in NAL unit header, (0: no explicit signalling, otherwise per layer ) (m)
+
+#======== VPS/ Layer sets ================
+VpsNumLayerSets        : 2           #  Number of layer sets    
+LayerIdsInSet_0        : 0           #  Indices in VPS of layers in layer set 0  (here: LS 0)
+LayerIdsInSet_1        : 0 2 4       #  Indices in VPS of layers in layer set 1  (here: LS 1)
+
+NumAddLayerSets        : 2           #  Additional layer sets for independent decodable non-base layer
+HighestLayerIdxPlus1_0 : -1 1        # Highest layer idx plus 1 for the 0-th additional layer set, per independent layer (m) (first value will be ignored) (here: LS 2)
+HighestLayerIdxPlus1_1 : -1 3        # Highest layer idx plus 1 for the 1-th additional layer set, per independent layer (m) (first value will be ignored) (here: LS 3)
+
+#======== VPS / Output layer sets ================
+OutputLayerSetIdx           : 1 1 1 1 1 3 3 3 3 3 3 #  Indices of layer sets used to derive additional output layer sets
+
+# TREE 0 (LS Idx (1))
+LayerIdsInAddOutputLayerSet_0 : 0 2     #  Indices in VPS of output layers in additional output layer set 0   (here: OLS 4)
+LayerIdsInAddOutputLayerSet_1 : 0 4     #  Indices in VPS of output layers in additional output layer set 1   (here: OLS 5)
+LayerIdsInAddOutputLayerSet_2 : 2 4     #  Indices in VPS of output layers in additional output layer set 2   (here: OLS 6)
+LayerIdsInAddOutputLayerSet_3 : 2       #  Indices in VPS of output layers in additional output layer set 3   (here: OLS 7)
+LayerIdsInAddOutputLayerSet_4 : 4       #  Indices in VPS of output layers in additional output layer set 4   (here: OLS 8)
+                                                                                                              
+# TREE 1 (additional LS  (3))                                                                                          
+LayerIdsInAddOutputLayerSet_5 : 1        #  Indices in VPS of output layers in additional output layer set 5  (here: OLS 9)
+LayerIdsInAddOutputLayerSet_6 : 1 3      #  Indices in VPS of output layers in additional output layer set 6  (here: OLS 10)
+LayerIdsInAddOutputLayerSet_7 : 1 5      #  Indices in VPS of output layers in additional output layer set 7  (here: OLS 11)
+LayerIdsInAddOutputLayerSet_8 : 3 5      #  Indices in VPS of output layers in additional output layer set 8  (here: OLS 12)
+LayerIdsInAddOutputLayerSet_9 : 3        #  Indices in VPS of output layers in additional output layer set 9  (here: OLS 13)
+LayerIdsInAddOutputLayerSet_10: 5        #  Indices in VPS of output layers in additional output layer set 10 (here: OLS 14)
+
+
+#======== VPS / PTLI ================
+
+Profile                       : main main multiview-main main  # Profile indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+Level                         : none none none           none  # Level   indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+Tier                          : main main main           main  # Tier    indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+InblFlag                      : 0    0    0              1     # Inbl    indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+
+# For OLS corresponding to layer set
+ProfileTierLevelIdx_0         : 1                          # VpsProfileTierLevel indices of layers in output layer set 0 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_1         : 1  2  2                    # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+# For OLS corresponding to additional layer sets 
+ProfileTierLevelIdx_2         : 3                          # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 1  2  2                    # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+# For additional OLS
+ProfileTierLevelIdx_4         : 1  2 -1                    # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 -1  2                    # VpsProfileTierLevel indices of layers in output layer set 5 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_6         : 1  2  2                    # VpsProfileTierLevel indices of layers in output layer set 6 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_7         : 1  2 -1                    # VpsProfileTierLevel indices of layers in output layer set 7 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_8         : 1 -1  2                    # VpsProfileTierLevel indices of layers in output layer set 8 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_9         : 1 -1 -1                    # VpsProfileTierLevel indices of layers in output layer set 9 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_10        : 1  2 -1                    # VpsProfileTierLevel indices of layers in output layer set 10 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_11        : 1 -1  2                    # VpsProfileTierLevel indices of layers in output layer set 11 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_12        : 1  2  2                    # VpsProfileTierLevel indices of layers in output layer set 12 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_13        : 1  2 -1                    # VpsProfileTierLevel indices of layers in output layer set 13 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_14        : 1 -1  2                    # VpsProfileTierLevel indices of layers in output layer set 14 (m) (should be -1, when layer is not necessary)
+
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1      :          #  Indices in VPS of direct reference layers 
+DirectRefLayers_2      : 0        #  Indices in VPS of direct reference layers 
+DirectRefLayers_3      : 1        #  Indices in VPS of direct reference layers 
+DirectRefLayers_4      : 0        #  Indices in VPS of direct reference layers 
+DirectRefLayers_5      : 1        #  Indices in VPS of direct reference layers 
+
+DependencyTypes_1      :          #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_2      : 2        #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_3      : 2        #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_4      : 2        #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_5      : 2        #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+
+
+#======== Coding Structure =============
+
+#                      CbQPoffset    QPfactor     betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset  CrQPoffset  tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+Frame1:     B    8     1    0      0  0.442    0        0        0        4      4     -8 -10 -12 -16     0      0
+Frame2:     B    4     2    0      0  0.3536   0        0        0        2      3     -4 -6  4           1      4    5     1 1 0 0 1       0
+Frame3:     B    2     3    0      0  0.3536   0        0        0        2      4     -2 -4  2 6         1      2    4     1 1 1 1         0
+Frame4:     B    1     4    0      0  0.68     0        0        0        2      4     -1  1  3 7         1      1    5     1 0 1 1 1       0
+Frame5:     B    3     4    0      0  0.68     0        0        0        2      4     -1 -3  1 5         1     -2    5     1 1 1 1 0       0
+Frame6:     B    6     3    0      0  0.3536   0        0        0        2      4     -2 -4 -6 2         1     -3    5     1 1 1 1 0       0
+Frame7:     B    5     4    0      0  0.68     0        0        0        2      4     -1 -5  1 3         1      1    5     1 0 1 1 1       0
+Frame8:     B    7     4    0      0  0.68     0        0        0        2      4     -1 -3 -7 1         1     -2    5     1 1 1 1 0       0
+
+FrameI_l1:  I    0     0    0      0  0.442    0        0        0        0      0                        0                                 0             
+Frame1_l1:  B    8     1    0      0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0             
+Frame2_l1:  B    4     2    0      0  0.3536   0        0        0        2      3     -4 -6  4           1      4    5     1 1 0 0 1       0             
+Frame3_l1:  B    2     3    0      0  0.3536   0        0        0        2      4     -2 -4  2 6         1      2    4     1 1 1 1         0             
+Frame4_l1:  B    1     4    0      0  0.68     0        0        0        2      4     -1  1  3 7         1      1    5     1 0 1 1 1       0             
+Frame5_l1:  B    3     4    0      0  0.68     0        0        0        2      4     -1 -3  1 5         1     -2    5     1 1 1 1 0       0             
+Frame6_l1:  B    6     3    0      0  0.3536   0        0        0        2      4     -2 -4 -6 2         1     -3    5     1 1 1 1 0       0             
+Frame7_l1:  B    5     4    0      0  0.68     0        0        0        2      4     -1 -5  1 3         1      1    5     1 0 1 1 1       0             
+Frame8_l1:  B    7     4    0      0  0.68     0        0        0        2      4     -1 -3 -7 1         1     -2    5     1 1 1 1 0       0             
+
+FrameI_l2:  P    0     3    0      0  0.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l2:  B    8     4    0      0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l2:  B    4     5    0      0  0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       1            0         1          -1    
+Frame3_l2:  B    2     6    0      0  0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         1            0         1          -1    
+Frame4_l2:  B    1     7    0      0  0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       1            0         1          -1    
+Frame5_l2:  B    3     7    0      0  0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       1            0         2          -1    
+Frame6_l2:  B    6     6    0      0  0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       1            0         2          -1    
+Frame7_l2:  B    5     7    0      0  0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       1            0         2          -1    
+Frame8_l2:  B    7     7    0      0  0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       1            0         2          -1    
+
+FrameI_l3:  P    0     3    0      0  0.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l3:  B    8     4    0      0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l3:  B    4     5    0      0  0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       1            0         1          -1    
+Frame3_l3:  B    2     6    0      0  0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         1            0         1          -1    
+Frame4_l3:  B    1     7    0      0  0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       1            0         1          -1    
+Frame5_l3:  B    3     7    0      0  0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       1            0         2          -1    
+Frame6_l3:  B    6     6    0      0  0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       1            0         2          -1    
+Frame7_l3:  B    5     7    0      0  0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       1            0         2          -1    
+Frame8_l3:  B    7     7    0      0  0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       1            0         2          -1    
+
+FrameI_l4:  P    0     3    0      0  0.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l4:  B    8     4    0      0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l4:  B    4     5    0      0  0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       1            0         1          -1    
+Frame3_l4:  B    2     6    0      0  0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         1            0         1          -1    
+Frame4_l4:  B    1     7    0      0  0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       1            0         1          -1    
+Frame5_l4:  B    3     7    0      0  0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       1            0         2          -1    
+Frame6_l4:  B    6     6    0      0  0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       1            0         2          -1    
+Frame7_l4:  B    5     7    0      0  0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       1            0         2          -1    
+Frame8_l4:  B    7     7    0      0  0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       1            0         2          -1    
+
+FrameI_l5:  P    0     3    0      0  0.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l5:  B    8     4    0      0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l5:  B    4     5    0      0  0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       1            0         1          -1    
+Frame3_l5:  B    2     6    0      0  0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         1            0         1          -1    
+Frame4_l5:  B    1     7    0      0  0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       1            0         1          -1    
+Frame5_l5:  B    3     7    0      0  0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       1            0         2          -1    
+Frame6_l5:  B    6     6    0      0  0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       1            0         2          -1    
+Frame7_l5:  B    5     7    0      0  0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       1            0         2          -1    
+Frame8_l5:  B    7     7    0      0  0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       1            0         2          -1    
+
+LoopFilterDisable             : 0 1         # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
+SAO                           : 1 0         # Sample adaptive offset  (0: OFF, 1: ON) (mc)
+
+#========== view synthesis optimization (VSO) ==========
+VSO                       : 1                          # use of view synthesis optimization for depth coding
+VSOConfig                 : [cx0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) B(oo2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][cx2 B(cc1) I(s1.25 s1.5 s1.75)] # VSO configuration string
+#VSOConfig                 : [ox0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) B(oo2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][ox2 B(cc1) I(s1.25 s1.5 s1.75)] # VSO configuration string for FCO = 1
+WVSO                      : 1                                    # use of WVSO (Depth distortion metric with a weighted depth fidelity term) 
+VSOWeight                 : 10                                   # weight of VSO ( in SAD case, cf. squared in SSE case )
+VSDWeight                 : 1                                    # weight of VSD ( in SAD case, cf. squared in SSE case )
+DWeight                   : 1                                    # weight of depth distortion itself ( in SAD case, cf. squared in SSE case )
+UseEstimatedVSD           : 1                                    # Model based VSD estimation instead of rendering based for some encoder decisions      
Index: /trunk/cfg/MV-HEVC/NonConforming/delta_aux_3view_simu.cfg
===================================================================
--- /trunk/cfg/MV-HEVC/NonConforming/delta_aux_3view_simu.cfg	(revision 1413)
+++ /trunk/cfg/MV-HEVC/NonConforming/delta_aux_3view_simu.cfg	(revision 1413)
@@ -0,0 +1,154 @@
+#======== Legend for comments ===================== 
+# (m) specification per layer/dimension/layerset possible
+# (c) cyclic repetition of values, if not given for all layers/dimensions/layersets. (e.g. 5 layers and 1 2 3 -> 1 2 3 1 2  )
+
+
+NumberOfLayers         : 6       
+
+#======== VPS ============================
+ScalabilityMask        : 10        # Scalability Mask             ( Scalability Mask: 2: Multiview, 8: Auxiliary, 10: Multiview + Auxiliary )
+DimensionIdLen         : 4 4       #  Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex         : 0 0 1 1 2 2    #  # ViewOrderIndex, per layer (m)
+AuxId                  : 0 2 0 2 0 2 # Auxiliary Id, per layer (m), ( 0: none, 1: Alpha, 2: Depth )
+LayerIdInNuh           : 0 1 2 3 4 5   #  Layer Id in NAL unit header, (0: no explicit signalling, otherwise per layer ) (m)
+
+#======== VPS/ Layer sets ================
+VpsNumLayerSets        : 1           #  Number of layer sets    
+LayerIdsInSet_0        : 0           #  Indices in VPS of layers in layer set 0  (here: LS 0)
+LayerIdsInSet_1        :             #  Indices in VPS of layers in layer set 1  (here: LS 1)
+LayerIdsInSet_2        :             #  Indices in VPS of layers in layer set 1  (here: LS 1)
+LayerIdsInSet_3        :             #  Indices in VPS of layers in layer set 1  (here: LS 1)
+
+NumAddLayerSets        : 5                             #  Additional layer sets for independent decodable non-base layer
+HighestLayerIdxPlus1_0 : -1 1 0 0 0 0                  # Highest layer idx plus 1 for the 0-th additional layer set, per independent layer (m) (first value will be ignored) (here: LS 1)
+HighestLayerIdxPlus1_1 : -1 0 1 0 0 0                  # Highest layer idx plus 1 for the 1-th additional layer set, per independent layer (m) (first value will be ignored) (here: LS 2)
+HighestLayerIdxPlus1_2 : -1 0 0 1 0 0                  # Highest layer idx plus 1 for the 1-th additional layer set, per independent layer (m) (first value will be ignored) (here: LS 3)
+HighestLayerIdxPlus1_3 : -1 0 0 0 1 0                  # Highest layer idx plus 1 for the 1-th additional layer set, per independent layer (m) (first value will be ignored) (here: LS 4)
+HighestLayerIdxPlus1_4 : -1 0 0 0 0 1                  # Highest layer idx plus 1 for the 1-th additional layer set, per independent layer (m) (first value will be ignored) (here: LS 5)
+
+#======== VPS / Output layer sets ================
+OutputLayerSetIdx           :               #  Indices of layer sets used to derive additional output layer sets
+
+# TREE 0 (LS Idx (1))
+LayerIdsInAddOutputLayerSet_0 :         #  Indices in VPS of output layers in additional output layer set 0   (here: OLS 7)
+# TREE 1 (LS Idx (2))            
+LayerIdsInAddOutputLayerSet_1 :         #  Indices in VPS of output layers in additional output layer set 1   (here: OLS 8)
+# TREE 2 (LS Idx (4))            
+LayerIdsInAddOutputLayerSet_2 :         #  Indices in VPS of output layers in additional output layer set 2   (here: OLS 9)
+# TREE 3 (LS Idx (5))            
+LayerIdsInAddOutputLayerSet_3 :         #  Indices in VPS of output layers in additional output layer set 3   (here: OLS 10)
+# TREE 4 (LS Idx (6))            
+LayerIdsInAddOutputLayerSet_4 :         #  Indices in VPS of output layers in additional output layer set 4   (here: OLS 11)
+
+LayerIdsInAddOutputLayerSet_5 :         #  Indices in VPS of output layers in additional output layer set 4   (here: OLS 12)
+LayerIdsInAddOutputLayerSet_6 :         #  Indices in VPS of output layers in additional output layer set 4   (here: OLS 13)
+LayerIdsInAddOutputLayerSet_7 :         #  Indices in VPS of output layers in additional output layer set 4   (here: OLS 14)
+
+
+#======== VPS / PTLI ================
+
+Profile                       : main main main  # Profile indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+Level                         : none none none  # Level   indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+Tier                          : main main main  # Tier    indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+InblFlag                      : 0    0    1     # Inbl    indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+
+# For OLS corresponding to layer set
+ProfileTierLevelIdx_0         : 1                          # VpsProfileTierLevel indices of layers in output layer set 0 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_1         : 2                          # VpsProfileTierLevel indices of layers in output layer set 0 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 2                          # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 2                          # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_4         : 2                          # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 2                          # VpsProfileTierLevel indices of layers in output layer set 5 (m) (should be -1, when layer is not necessary)
+
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1      :         #  Indices in VPS of direct reference layers 
+DirectRefLayers_2      :         #  Indices in VPS of direct reference layers 
+DirectRefLayers_3      :         #  Indices in VPS of direct reference layers 
+DirectRefLayers_4      :         #  Indices in VPS of direct reference layers 
+DirectRefLayers_5      :         #  Indices in VPS of direct reference layers 
+
+DependencyTypes_1      :         #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_2      :         #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_3      :         #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_4      :         #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_5      :         #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+
+
+#======== Coding Structure =============
+
+#                      CbQPoffset    QPfactor     betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset  CrQPoffset  tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+Frame1:     B    8     1   0       0  0.442    0        0        0        4      4     -8 -10 -12 -16     0      0
+Frame2:     B    4     2   0       0  0.3536   0        0        0        2      3     -4 -6  4           1      4    5     1 1 0 0 1       0
+Frame3:     B    2     3   0       0  0.3536   0        0        0        2      4     -2 -4  2 6         1      2    4     1 1 1 1         0
+Frame4:     B    1     4   0       0  0.68     0        0        0        2      4     -1  1  3 7         1      1    5     1 0 1 1 1       0
+Frame5:     B    3     4   0       0  0.68     0        0        0        2      4     -1 -3  1 5         1     -2    5     1 1 1 1 0       0
+Frame6:     B    6     3   0       0  0.3536   0        0        0        2      4     -2 -4 -6 2         1     -3    5     1 1 1 1 0       0
+Frame7:     B    5     4   0       0  0.68     0        0        0        2      4     -1 -5  1 3         1      1    5     1 0 1 1 1       0
+Frame8:     B    7     4   0       0  0.68     0        0        0        2      4     -1 -3 -7 1         1     -2    5     1 1 1 1 0       0
+
+FrameI_l1:  I    0     0   0       0  0.442    0        0        0        0      0                        0                                 0             
+Frame1_l1:  B    8     1   0       0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0             
+Frame2_l1:  B    4     2   0       0  0.3536   0        0        0        2      3     -4 -6  4           1      4    5     1 1 0 0 1       0             
+Frame3_l1:  B    2     3   0       0  0.3536   0        0        0        2      4     -2 -4  2 6         1      2    4     1 1 1 1         0             
+Frame4_l1:  B    1     4   0       0  0.68     0        0        0        2      4     -1  1  3 7         1      1    5     1 0 1 1 1       0             
+Frame5_l1:  B    3     4   0       0  0.68     0        0        0        2      4     -1 -3  1 5         1     -2    5     1 1 1 1 0       0             
+Frame6_l1:  B    6     3   0       0  0.3536   0        0        0        2      4     -2 -4 -6 2         1     -3    5     1 1 1 1 0       0             
+Frame7_l1:  B    5     4   0       0  0.68     0        0        0        2      4     -1 -5  1 3         1      1    5     1 0 1 1 1       0             
+Frame8_l1:  B    7     4   0       0  0.68     0        0        0        2      4     -1 -3 -7 1         1     -2    5     1 1 1 1 0       0             
+
+FrameI_l2:  I    0     3   0       0  0.442    0        0        0        1      0                        0                                 0            
+Frame1_l2:  B    8     4   0       0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0            
+Frame2_l2:  B    4     5   0       0  0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       0            
+Frame3_l2:  B    2     6   0       0  0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0            
+Frame4_l2:  B    1     7   0       0  0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       0            
+Frame5_l2:  B    3     7   0       0  0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0            
+Frame6_l2:  B    6     6   0       0  0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       0            
+Frame7_l2:  B    5     7   0       0  0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0            
+Frame8_l2:  B    7     7   0       0  0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0            
+
+FrameI_l3:  I    0     3   0       0  0.442    0        0        0        1      0                        0                                 0            
+Frame1_l3:  B    8     4   0       0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0            
+Frame2_l3:  B    4     5   0       0  0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       0            
+Frame3_l3:  B    2     6   0       0  0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0            
+Frame4_l3:  B    1     7   0       0  0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       0            
+Frame5_l3:  B    3     7   0       0  0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0            
+Frame6_l3:  B    6     6   0       0  0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       0            
+Frame7_l3:  B    5     7   0       0  0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0            
+Frame8_l3:  B    7     7   0       0  0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0            
+
+FrameI_l4:  I    0     3   0       0  0.442    0        0        0        1      0                        0                                 0            
+Frame1_l4:  B    8     4   0       0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0            
+Frame2_l4:  B    4     5   0       0  0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       0            
+Frame3_l4:  B    2     6   0       0  0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0            
+Frame4_l4:  B    1     7   0       0  0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       0            
+Frame5_l4:  B    3     7   0       0  0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0            
+Frame6_l4:  B    6     6   0       0  0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       0            
+Frame7_l4:  B    5     7   0       0  0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0            
+Frame8_l4:  B    7     7   0       0  0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0            
+
+FrameI_l5:  I    0     3   0       0  0.442    0        0        0        1      0                        0                                 0            
+Frame1_l5:  B    8     4   0       0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0            
+Frame2_l5:  B    4     5   0       0  0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       0            
+Frame3_l5:  B    2     6   0       0  0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0            
+Frame4_l5:  B    1     7   0       0  0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       0            
+Frame5_l5:  B    3     7   0       0  0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0            
+Frame6_l5:  B    6     6   0       0  0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       0            
+Frame7_l5:  B    5     7   0       0  0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0            
+Frame8_l5:  B    7     7   0       0  0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0            
+
+
+LoopFilterDisable             : 0 1         # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
+SAO                           : 1 0         # Sample adaptive offset  (0: OFF, 1: ON) (mc)
+
+
+#========== view synthesis optimization (VSO) ==========
+VSO                       : 1                          # use of view synthesis optimization for depth coding
+VSOConfig                 : [cx0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) B(oo2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][cx2 B(cc1) I(s1.25 s1.5 s1.75)] # VSO configuration string
+#VSOConfig                 : [ox0 B(cc1) I(s0.25 s0.5 s0.75)][cx1 B(oo0) B(oo2) I(s0.25 s0.5 s0.75 s1.25 s1.5 s1.75)][ox2 B(cc1) I(s1.25 s1.5 s1.75)] # VSO configuration string for FCO = 1
+WVSO                      : 1                                    # use of WVSO (Depth distortion metric with a weighted depth fidelity term) 
+VSOWeight                 : 10                                   # weight of VSO ( in SAD case, cf. squared in SSE case )
+VSDWeight                 : 1                                    # weight of VSD ( in SAD case, cf. squared in SSE case )
+DWeight                   : 1                                    # weight of depth distortion itself ( in SAD case, cf. squared in SSE case )
+UseEstimatedVSD           : 1                                    # Model based VSD estimation instead of rendering based for some encoder decisions      
Index: /trunk/cfg/MV-HEVC/NonConforming/fullCfg_aux_3view_aux_10bit.cfg
===================================================================
--- /trunk/cfg/MV-HEVC/NonConforming/fullCfg_aux_3view_aux_10bit.cfg	(revision 1413)
+++ /trunk/cfg/MV-HEVC/NonConforming/fullCfg_aux_3view_aux_10bit.cfg	(revision 1413)
@@ -0,0 +1,243 @@
+#======== Legend for comments ===================== 
+# (m) specification per layer/dimension/layerset possible
+# (c) cyclic repetition of values, if not given for all layers/dimensions/layersets/representation formats. (e.g. 5 layers and 1 2 3 -> 1 2 3 1 2  )
+
+#======== File I/O =====================
+
+InputFile_0                   : 
+InputFile_1                   : 
+InputFile_2                   : 
+InputFile_3                   : 
+InputFile_4                   : 
+InputFile_5                   : 
+InputFile_6                   : 
+InputFile_7                   : 
+InputFile_8                   : 
+InputFile_9                   : 
+InputFile_10                  : 
+InputFile_11                  : 
+
+
+BitstreamFile                 : 
+
+ReconFile_0                   : 
+ReconFile_1                   : 
+ReconFile_2                   : 
+ReconFile_3                   : 
+ReconFile_4                   : 
+ReconFile_5                   : 
+ReconFile_6                   : 
+ReconFile_7                   : 
+ReconFile_8                   : 
+ReconFile_9                   : 
+ReconFile_10                  : 
+ReconFile_11                  : 
+
+NumberOfLayers                : 6           # Number of layers
+TargetEncLayerIdList          :             # Layer Id in Nuh to be encoded, (empty:-> all layers will be encode) 
+
+FramesToBeEncoded             :             # Number of frames to be coded
+FrameRate                     :             # Frame Rate per second
+SourceWidth                   :             # Input  frame width
+SourceHeight                  :             # Input  frame height
+
+LayerIdxInVpsToRepFormatIdx   : 0 1         # Mapping of Layers to RepFormats (c), per layer
+InternalBitDepth              : 8 10        # Internal bit depth (c), per representation format
+OutputBitDepth                : 8 10        # Output bit depth (c)  , per representation format
+
+#======== VPS ============================
+ScalabilityMask        : 10        # Scalability Mask             ( Scalability Mask: 2: Multiview, 8: Auxiliary, 10: Multiview + Auxiliary )
+DimensionIdLen         : 4 4       #  Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex         : 0 0 1 1 2 2    #  # ViewOrderIndex, per layer (m)
+AuxId                  : 0 2 0 2 0 2 # Auxiliary Id, per layer (m), ( 0: none, 1: Alpha, 2: Depth )
+LayerIdInNuh           : 0 1 2 3 4 5   #  Layer Id in NAL unit header, (0: no explicit signalling, otherwise per layer ) (m)
+SplittingFlag          : 0           # Splitting Flag 
+ViewId                 : 1 0 2       # ViewId, per ViewOrderIndex (m)
+OutputVpsInfo          : 0           # Output VPS information
+
+
+#======== VPS/ Layer sets ================
+VpsNumLayerSets        : 2           #  Number of layer sets    
+LayerIdsInSet_0        : 0           #  Indices in VPS of layers in layer set 0  (here: LS 0)
+LayerIdsInSet_1        : 0 2 4       #  Indices in VPS of layers in layer set 1  (here: LS 1)
+
+NumAddLayerSets        : 2           #  Additional layer sets for independent decodable non-base layer
+HighestLayerIdxPlus1_0 : -1 1        # Highest layer idx plus 1 for the 0-th additional layer set, per independent layer (m) (first value will be ignored) (here: LS 2)
+HighestLayerIdxPlus1_1 : -1 3        # Highest layer idx plus 1 for the 1-th additional layer set, per independent layer (m) (first value will be ignored) (here: LS 3)
+
+#======== VPS / Output layer sets ================
+OutputLayerSetIdx           : 1 1 1 1 1 3 3 3 3 3 3 #  Indices of layer sets used to derive additional output layer sets
+
+# TREE 0 (LS Idx (1))
+LayerIdsInAddOutputLayerSet_0 : 0 2     #  Indices in VPS of output layers in additional output layer set 0   (here: OLS 4)
+LayerIdsInAddOutputLayerSet_1 : 0 4     #  Indices in VPS of output layers in additional output layer set 1   (here: OLS 5)
+LayerIdsInAddOutputLayerSet_2 : 2 4     #  Indices in VPS of output layers in additional output layer set 2   (here: OLS 6)
+LayerIdsInAddOutputLayerSet_3 : 2       #  Indices in VPS of output layers in additional output layer set 3   (here: OLS 7)
+LayerIdsInAddOutputLayerSet_4 : 4       #  Indices in VPS of output layers in additional output layer set 4   (here: OLS 8)
+                                                                                                              
+# TREE 1 (additional LS  (3))                                                                                          
+LayerIdsInAddOutputLayerSet_5 : 1        #  Indices in VPS of output layers in additional output layer set 5  (here: OLS 9)
+LayerIdsInAddOutputLayerSet_6 : 1 3      #  Indices in VPS of output layers in additional output layer set 6  (here: OLS 10)
+LayerIdsInAddOutputLayerSet_7 : 1 5      #  Indices in VPS of output layers in additional output layer set 7  (here: OLS 11)
+LayerIdsInAddOutputLayerSet_8 : 3 5      #  Indices in VPS of output layers in additional output layer set 8  (here: OLS 12)
+LayerIdsInAddOutputLayerSet_9 : 3        #  Indices in VPS of output layers in additional output layer set 9  (here: OLS 13)
+LayerIdsInAddOutputLayerSet_10: 5        #  Indices in VPS of output layers in additional output layer set 10 (here: OLS 14)
+
+#======== VPS / PTLI ================
+
+Profile                       : main main multiview-main_NONCONFORMING main10  # Profile indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+Level                         : none none none           none  # Level   indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+Tier                          : main main main           main  # Tier    indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+InblFlag                      : 0    0    0              1     # Inbl    indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+
+# For OLS corresponding to layer set
+ProfileTierLevelIdx_0         : 1                          # VpsProfileTierLevel indices of layers in output layer set 0 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_1         : 1  2  2                    # VpsProfileTierLevel indices of layers in output layer set 1 (m) (should be -1, when layer is not necessary)
+# For OLS corresponding to additional layer sets 
+ProfileTierLevelIdx_2         : 3                          # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 1  2  2                    # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+# For additional OLS
+ProfileTierLevelIdx_4         : 1  2 -1                    # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 1 -1  2                    # VpsProfileTierLevel indices of layers in output layer set 5 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_6         : 1  2  2                    # VpsProfileTierLevel indices of layers in output layer set 6 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_7         : 1  2 -1                    # VpsProfileTierLevel indices of layers in output layer set 7 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_8         : 1 -1  2                    # VpsProfileTierLevel indices of layers in output layer set 8 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_9         : 1 -1 -1                    # VpsProfileTierLevel indices of layers in output layer set 9 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_10        : 1  2 -1                    # VpsProfileTierLevel indices of layers in output layer set 10 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_11        : 1 -1  2                    # VpsProfileTierLevel indices of layers in output layer set 11 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_12        : 1  2  2                    # VpsProfileTierLevel indices of layers in output layer set 12 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_13        : 1  2 -1                    # VpsProfileTierLevel indices of layers in output layer set 13 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_14        : 1 -1  2                    # VpsProfileTierLevel indices of layers in output layer set 14 (m) (should be -1, when layer is not necessary)
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1      :          #  Indices in VPS of direct reference layers 
+DirectRefLayers_2      : 0        #  Indices in VPS of direct reference layers 
+DirectRefLayers_3      : 1        #  Indices in VPS of direct reference layers 
+DirectRefLayers_4      : 0        #  Indices in VPS of direct reference layers 
+DirectRefLayers_5      : 1        #  Indices in VPS of direct reference layers 
+
+DependencyTypes_1      :          #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_2      : 2        #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_3      : 2        #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_4      : 2        #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_5      : 2        #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+
+
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 24          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+
+#                      CbQPoffset    QPfactor     betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset  CrQPoffset  tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+
+Frame1:     B    8     1  0  0     0.442    0        0        0        4      4     -8 -10 -12 -16     0      0
+Frame2:     B    4     2  0  0     0.3536   0        0        0        2      3     -4 -6  4           1      4    5     1 1 0 0 1         0
+Frame3:     B    2     3  0  0     0.3536   0        0        0        2      4     -2 -4  2 6         1      2    4     1 1 1 1           0
+Frame4:     B    1     4  0  0     0.68     0        0        0        2      4     -1  1  3 7         1      1    5     1 0 1 1 1         0
+Frame5:     B    3     4  0  0     0.68     0        0        0        2      4     -1 -3  1 5         1     -2    5     1 1 1 1 0         0
+Frame6:     B    6     3  0  0     0.3536   0        0        0        2      4     -2 -4 -6 2         1     -3    5     1 1 1 1 0         0
+Frame7:     B    5     4  0  0     0.68     0        0        0        2      4     -1 -5  1 3         1      1    5     1 0 1 1 1         0
+Frame8:     B    7     4  0  0     0.68     0        0        0        2      4     -1 -3 -7 1         1     -2    5     1 1 1 1 0         0
+                                   
+FrameI_l1:  I    0     0    0      0  0.442    0        0        0        0      0                        0                                 0             
+Frame1_l1:  B    8     1    0      0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0             
+Frame2_l1:  B    4     2    0      0  0.3536   0        0        0        2      3     -4 -6  4           1      4    5     1 1 0 0 1       0             
+Frame3_l1:  B    2     3    0      0  0.3536   0        0        0        2      4     -2 -4  2 6         1      2    4     1 1 1 1         0             
+Frame4_l1:  B    1     4    0      0  0.68     0        0        0        2      4     -1  1  3 7         1      1    5     1 0 1 1 1       0             
+Frame5_l1:  B    3     4    0      0  0.68     0        0        0        2      4     -1 -3  1 5         1     -2    5     1 1 1 1 0       0             
+Frame6_l1:  B    6     3    0      0  0.3536   0        0        0        2      4     -2 -4 -6 2         1     -3    5     1 1 1 1 0       0             
+Frame7_l1:  B    5     4    0      0  0.68     0        0        0        2      4     -1 -5  1 3         1      1    5     1 0 1 1 1       0             
+Frame8_l1:  B    7     4    0      0  0.68     0        0        0        2      4     -1 -3 -7 1         1     -2    5     1 1 1 1 0       0             
+
+FrameI_l2:  P    0     3  0  0     0.442    0        0        0        1      0                        0                                   1          0         0          -1        
+Frame1_l2:  B    8     4  0  0     0.442    0        0        0        4      4     -8 -10 -12 -16     0                                   1          0         1          -1        
+Frame2_l2:  B    4     5  0  0     0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1         1          0         1          -1        
+Frame3_l2:  B    2     6  0  0     0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1           1          0         1          -1        
+Frame4_l2:  B    1     7  0  0     0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1         1          0         1          -1        
+Frame5_l2:  B    3     7  0  0     0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0         1          0         2          -1        
+Frame6_l2:  B    6     6  0  0     0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0         1          0         2          -1        
+Frame7_l2:  B    5     7  0  0     0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1         1          0         2          -1        
+Frame8_l2:  B    7     7  0  0     0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0         1          0         2          -1        
+
+FrameI_l3:  P    0     3    0      0  0.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l3:  B    8     4    0      0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l3:  B    4     5    0      0  0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       1            0         1          -1    
+Frame3_l3:  B    2     6    0      0  0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         1            0         1          -1    
+Frame4_l3:  B    1     7    0      0  0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       1            0         1          -1    
+Frame5_l3:  B    3     7    0      0  0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       1            0         2          -1    
+Frame6_l3:  B    6     6    0      0  0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       1            0         2          -1    
+Frame7_l3:  B    5     7    0      0  0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       1            0         2          -1    
+Frame8_l3:  B    7     7    0      0  0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       1            0         2          -1    
+FrameI_l4:  P    0     3    0      0  0.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l4:  B    8     4    0      0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l4:  B    4     5    0      0  0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       1            0         1          -1    
+Frame3_l4:  B    2     6    0      0  0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         1            0         1          -1    
+Frame4_l4:  B    1     7    0      0  0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       1            0         1          -1    
+Frame5_l4:  B    3     7    0      0  0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       1            0         2          -1    
+Frame6_l4:  B    6     6    0      0  0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       1            0         2          -1    
+Frame7_l4:  B    5     7    0      0  0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       1            0         2          -1    
+Frame8_l4:  B    7     7    0      0  0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       1            0         2          -1    
+
+FrameI_l5:  P    0     3    0      0  0.442    0        0        0        1      0                        0                                 1            0         0          -1    
+Frame1_l5:  B    8     4    0      0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 1            0         1          -1    
+Frame2_l5:  B    4     5    0      0  0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       1            0         1          -1    
+Frame3_l5:  B    2     6    0      0  0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         1            0         1          -1    
+Frame4_l5:  B    1     7    0      0  0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       1            0         1          -1    
+Frame5_l5:  B    3     7    0      0  0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       1            0         2          -1    
+Frame6_l5:  B    6     6    0      0  0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       1            0         2          -1    
+Frame7_l5:  B    5     7    0      0  0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       1            0         2          -1    
+Frame8_l5:  B    7     7    0      0  0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       1            0         2          -1    
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+DispSearchRangeRestriction    : 1           # Limit Search range for vertical component of disparity vector
+VerticalDispSearchRange       : 56          # Vertical Search range in pixel
+
+#======== Quantization =============
+QP                            : 25          # quantization parameter (mc)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+SliceChromaQPOffsetPeriodicity: 0           # Used in conjunction with Slice Cb/Cr QpOffsetIntraOrPeriodic. Use 0 (default) to disable periodic nature.
+SliceCbQpOffsetIntraOrPeriodic: 0           # Chroma Cb QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
+SliceCrQpOffsetIntraOrPeriodic: 0           # Chroma Cr QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
+
+#=========== Deblock Filter ============
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON) (mc)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+LFCrossSliceBoundaryFlag : 1                # In-loop filtering, including ALF and DB, is across or not across slice boundary.
+                                            # 0:not across, 1: across
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /trunk/cfg/MV-HEVC/NonConforming/fullCfg_aux_3view_simu_different_rep_formats.cfg
===================================================================
--- /trunk/cfg/MV-HEVC/NonConforming/fullCfg_aux_3view_simu_different_rep_formats.cfg	(revision 1413)
+++ /trunk/cfg/MV-HEVC/NonConforming/fullCfg_aux_3view_simu_different_rep_formats.cfg	(revision 1413)
@@ -0,0 +1,240 @@
+#======== Legend for comments ===================== 
+# (m) specification per layer/dimension/layerset possible
+# (c) cyclic repetition of values, if not given for all layers/dimensions/layersets. (e.g. 5 layers and 1 2 3 -> 1 2 3 1 2  )
+
+#======== File I/O =====================
+
+InputFile_0                   :
+InputFile_1                   :
+InputFile_2                   :
+InputFile_3                   :                               
+InputFile_4                   :                                
+InputFile_5                   :       
+InputFile_6                   :       
+InputFile_7                   :       
+InputFile_8                   :       
+InputFile_9                   :       
+InputFile_10                   :       
+InputFile_11                   :       
+
+BitstreamFile                 : stream.bit                         
+
+ReconFile_0                   :
+ReconFile_1                   :
+ReconFile_2                   :
+ReconFile_3                   :                           
+ReconFile_4                   :                          
+ReconFile_5                   :                            
+ReconFile_6                   :       
+ReconFile_7                   :       
+ReconFile_8                   :       
+ReconFile_9                   :       
+ReconFile_10                  :       
+ReconFile_11                  :       
+
+
+NumberOfLayers         : 6       
+
+FramesToBeEncoded             : 3           # Number of frames to be coded
+FrameRate                     : 30          # Frame Rate per second
+
+
+#=========== Repersentation format ============
+InternalBitDepth              : 8      10   12    8   10   12   # codec operating bit-depth
+ChromaFormatIDC               : 420   400  422  420  422  400
+SourceWidth                   : 1024 1024 1024  512  512  512   
+SourceHeight                  : 768  768  1024  512  512  512   
+
+LayerIdxInVpsToRepFormatIdx   : 0      1     2    3    4    5
+
+
+#======== VPS ============================
+ScalabilityMask        : 10        # Scalability Mask             ( Scalability Mask: 2: Multiview, 8: Auxiliary, 10: Multiview + Auxiliary )
+DimensionIdLen         : 4 4       #  Number of bits to store Ids,  per scalability dimension, (m)
+ViewOrderIndex         : 0 0 1 1 2 2    #  # ViewOrderIndex, per layer (m)
+AuxId                  : 0 2 0 2 0 2 # Auxiliary Id, per layer (m), ( 0: none, 1: Alpha, 2: Depth )
+LayerIdInNuh           : 0 1 2 3 4 5   #  Layer Id in NAL unit header, (0: no explicit signalling, otherwise per layer ) (m)
+ViewId                 : 0 1 2 3 4 5
+
+#======== VPS/ Layer sets ================
+VpsNumLayerSets        : 1           #  Number of layer sets    
+LayerIdsInSet_0        : 0           #  Indices in VPS of layers in layer set 0  (here: LS 0)
+LayerIdsInSet_1        :             #  Indices in VPS of layers in layer set 1  (here: LS 1)
+LayerIdsInSet_2        :             #  Indices in VPS of layers in layer set 1  (here: LS 1)
+LayerIdsInSet_3        :             #  Indices in VPS of layers in layer set 1  (here: LS 1)
+
+NumAddLayerSets        : 5                             #  Additional layer sets for independent decodable non-base layer
+HighestLayerIdxPlus1_0 : -1 1 0 0 0 0                  # Highest layer idx plus 1 for the 0-th additional layer set, per independent layer (m) (first value will be ignored) (here: LS 1)
+HighestLayerIdxPlus1_1 : -1 0 1 0 0 0                  # Highest layer idx plus 1 for the 1-th additional layer set, per independent layer (m) (first value will be ignored) (here: LS 2)
+HighestLayerIdxPlus1_2 : -1 0 0 1 0 0                  # Highest layer idx plus 1 for the 1-th additional layer set, per independent layer (m) (first value will be ignored) (here: LS 3)
+HighestLayerIdxPlus1_3 : -1 0 0 0 1 0                  # Highest layer idx plus 1 for the 1-th additional layer set, per independent layer (m) (first value will be ignored) (here: LS 4)
+HighestLayerIdxPlus1_4 : -1 0 0 0 0 1                  # Highest layer idx plus 1 for the 1-th additional layer set, per independent layer (m) (first value will be ignored) (here: LS 5)
+
+
+#======== VPS / Output layer sets ================
+OutputLayerSetIdx           :               #  Indices of layer sets used to derive additional output layer sets
+
+# TREE 0 (LS Idx (1))
+LayerIdsInAddOutputLayerSet_0 :         #  Indices in VPS of output layers in additional output layer set 0   (here: OLS 7)
+# TREE 1 (LS Idx (2))            
+LayerIdsInAddOutputLayerSet_1 :         #  Indices in VPS of output layers in additional output layer set 1   (here: OLS 8)
+# TREE 2 (LS Idx (4))            
+LayerIdsInAddOutputLayerSet_2 :         #  Indices in VPS of output layers in additional output layer set 2   (here: OLS 9)
+# TREE 3 (LS Idx (5))            
+LayerIdsInAddOutputLayerSet_3 :         #  Indices in VPS of output layers in additional output layer set 3   (here: OLS 10)
+# TREE 4 (LS Idx (6))            
+LayerIdsInAddOutputLayerSet_4 :         #  Indices in VPS of output layers in additional output layer set 4   (here: OLS 11)
+
+LayerIdsInAddOutputLayerSet_5 :         #  Indices in VPS of output layers in additional output layer set 4   (here: OLS 12)
+LayerIdsInAddOutputLayerSet_6 :         #  Indices in VPS of output layers in additional output layer set 4   (here: OLS 13)
+LayerIdsInAddOutputLayerSet_7 :         #  Indices in VPS of output layers in additional output layer set 4   (here: OLS 14)
+
+#======== VPS / PTLI ================
+
+Profile                       : none none none  # Profile indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+Level                         : none none none  # Level   indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+Tier                          : main main main  # Tier    indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+InblFlag                      : 0    0    1     # Inbl    indication in VpsProfileTierLevel, per VpsProfileTierLevel syntax structure  (m) 
+
+# For OLS corresponding to layer set
+ProfileTierLevelIdx_0         : 1                          # VpsProfileTierLevel indices of layers in output layer set 0 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_1         : 2                          # VpsProfileTierLevel indices of layers in output layer set 0 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_2         : 2                          # VpsProfileTierLevel indices of layers in output layer set 2 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_3         : 2                          # VpsProfileTierLevel indices of layers in output layer set 3 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_4         : 2                          # VpsProfileTierLevel indices of layers in output layer set 4 (m) (should be -1, when layer is not necessary)
+ProfileTierLevelIdx_5         : 2                          # VpsProfileTierLevel indices of layers in output layer set 5 (m) (should be -1, when layer is not necessary)
+
+
+#======== VPS / Dependencies ================
+DirectRefLayers_1      :         #  Indices in VPS of direct reference layers 
+DirectRefLayers_2      :         #  Indices in VPS of direct reference layers 
+DirectRefLayers_3      :         #  Indices in VPS of direct reference layers 
+DirectRefLayers_4      :         #  Indices in VPS of direct reference layers 
+DirectRefLayers_5      :         #  Indices in VPS of direct reference layers 
+
+DependencyTypes_1      :         #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_2      :         #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_3      :         #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_4      :         #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+DependencyTypes_5      :         #  Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion
+
+
+
+
+
+#======== Unit definition ================
+MaxCUWidth                    : 64          # Maximum coding unit width in pixel
+MaxCUHeight                   : 64          # Maximum coding unit height in pixel
+MaxPartitionDepth             : 4           # Maximum coding unit depth
+QuadtreeTULog2MaxSize         : 5           # Log2 of maximum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTULog2MinSize         : 2           # Log2 of minimum transform size for
+                                            # quadtree-based TU coding (2...6)
+QuadtreeTUMaxDepthInter       : 3
+QuadtreeTUMaxDepthIntra       : 3
+
+#======== Coding Structure =============
+IntraPeriod                   : 24          # Period of I-Frame ( -1 = only first)
+DecodingRefreshType           : 1           # Random Accesss 0:none, 1:CRA, 2:IDR, 3:Recovery Point SEI
+GOPSize                       : 8           # GOP Size (number of B slice = GOPSize-1)
+
+#                      CbQPoffset    QPfactor     betaOffsetDiv2   #ref_pics_active  reference pictures     deltaRPS     reference idcs          ilPredLayerIdc       refLayerPicPosIl_L1
+#         Type  POC QPoffset  CrQPoffset  tcOffsetDiv2      temporal_id      #ref_pics                 predict     #ref_idcs        #ActiveRefLayerPics     refLayerPicPosIl_L0     
+Frame1:     B    8     1   0       0  0.442    0        0        0        4      4     -8 -10 -12 -16     0      0
+Frame2:     B    4     2   0       0  0.3536   0        0        0        2      3     -4 -6  4           1      4    5     1 1 0 0 1       0
+Frame3:     B    2     3   0       0  0.3536   0        0        0        2      4     -2 -4  2 6         1      2    4     1 1 1 1         0
+Frame4:     B    1     4   0       0  0.68     0        0        0        2      4     -1  1  3 7         1      1    5     1 0 1 1 1       0
+Frame5:     B    3     4   0       0  0.68     0        0        0        2      4     -1 -3  1 5         1     -2    5     1 1 1 1 0       0
+Frame6:     B    6     3   0       0  0.3536   0        0        0        2      4     -2 -4 -6 2         1     -3    5     1 1 1 1 0       0
+Frame7:     B    5     4   0       0  0.68     0        0        0        2      4     -1 -5  1 3         1      1    5     1 0 1 1 1       0
+Frame8:     B    7     4   0       0  0.68     0        0        0        2      4     -1 -3 -7 1         1     -2    5     1 1 1 1 0       0
+
+FrameI_l1:  I    0     0   0       0  0.442    0        0        0        0      0                        0                                 0             
+Frame1_l1:  B    8     1   0       0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0             
+Frame2_l1:  B    4     2   0       0  0.3536   0        0        0        2      3     -4 -6  4           1      4    5     1 1 0 0 1       0             
+Frame3_l1:  B    2     3   0       0  0.3536   0        0        0        2      4     -2 -4  2 6         1      2    4     1 1 1 1         0             
+Frame4_l1:  B    1     4   0       0  0.68     0        0        0        2      4     -1  1  3 7         1      1    5     1 0 1 1 1       0             
+Frame5_l1:  B    3     4   0       0  0.68     0        0        0        2      4     -1 -3  1 5         1     -2    5     1 1 1 1 0       0             
+Frame6_l1:  B    6     3   0       0  0.3536   0        0        0        2      4     -2 -4 -6 2         1     -3    5     1 1 1 1 0       0             
+Frame7_l1:  B    5     4   0       0  0.68     0        0        0        2      4     -1 -5  1 3         1      1    5     1 0 1 1 1       0             
+Frame8_l1:  B    7     4   0       0  0.68     0        0        0        2      4     -1 -3 -7 1         1     -2    5     1 1 1 1 0       0             
+
+FrameI_l2:  I    0     3   0       0  0.442    0        0        0        1      0                        0                                 0            
+Frame1_l2:  B    8     4   0       0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0            
+Frame2_l2:  B    4     5   0       0  0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       0            
+Frame3_l2:  B    2     6   0       0  0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0            
+Frame4_l2:  B    1     7   0       0  0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       0            
+Frame5_l2:  B    3     7   0       0  0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0            
+Frame6_l2:  B    6     6   0       0  0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       0            
+Frame7_l2:  B    5     7   0       0  0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0            
+Frame8_l2:  B    7     7   0       0  0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0            
+
+FrameI_l3:  I    0     3   0       0  0.442    0        0        0        1      0                        0                                 0            
+Frame1_l3:  B    8     4   0       0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0            
+Frame2_l3:  B    4     5   0       0  0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       0            
+Frame3_l3:  B    2     6   0       0  0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0            
+Frame4_l3:  B    1     7   0       0  0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       0            
+Frame5_l3:  B    3     7   0       0  0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0            
+Frame6_l3:  B    6     6   0       0  0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       0            
+Frame7_l3:  B    5     7   0       0  0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0            
+Frame8_l3:  B    7     7   0       0  0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0            
+
+FrameI_l4:  I    0     3   0       0  0.442    0        0        0        1      0                        0                                 0            
+Frame1_l4:  B    8     4   0       0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0            
+Frame2_l4:  B    4     5   0       0  0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       0            
+Frame3_l4:  B    2     6   0       0  0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0            
+Frame4_l4:  B    1     7   0       0  0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       0            
+Frame5_l4:  B    3     7   0       0  0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0            
+Frame6_l4:  B    6     6   0       0  0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       0            
+Frame7_l4:  B    5     7   0       0  0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0            
+Frame8_l4:  B    7     7   0       0  0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0            
+
+FrameI_l5:  I    0     3   0       0  0.442    0        0        0        1      0                        0                                 0            
+Frame1_l5:  B    8     4   0       0  0.442    0        0        0        4      4     -8 -10 -12 -16     0                                 0            
+Frame2_l5:  B    4     5   0       0  0.3536   0        0        0        3      3     -4 -6  4           1     4     5     1 1 0 0 1       0            
+Frame3_l5:  B    2     6   0       0  0.3536   0        0        0        3      4     -2 -4  2 6         1     2     4     1 1 1 1         0            
+Frame4_l5:  B    1     7   0       0  0.68     0        0        0        3      4     -1  1  3 7         1     1     5     1 0 1 1 1       0            
+Frame5_l5:  B    3     7   0       0  0.68     0        0        0        3      4     -1 -3  1 5         1    -2     5     1 1 1 1 0       0            
+Frame6_l5:  B    6     6   0       0  0.3536   0        0        0        3      4     -2 -4 -6 2         1    -3     5     1 1 1 1 0       0            
+Frame7_l5:  B    5     7   0       0  0.68     0        0        0        3      4     -1 -5  1 3         1     1     5     1 0 1 1 1       0            
+Frame8_l5:  B    7     7   0       0  0.68     0        0        0        3      4     -1 -3 -7 1         1    -2     5     1 1 1 1 0       0            
+
+#=========== Motion Search =============
+FastSearch                    : 1           # 0:Full search  1:TZ search
+SearchRange                   : 64          # (0: Search range is a Full frame)
+BipredSearchRange             : 4           # Search range for bi-prediction refinement
+HadamardME                    : 1           # Use of hadamard measure for fractional ME
+FEN                           : 1           # Fast encoder decision
+FDM                           : 1           # Fast Decision for Merge RD cost
+DispSearchRangeRestriction    : 1           # Limit Search range for vertical component of disparity vector
+VerticalDispSearchRange       : 56          # Vertical Search range in pixel
+
+#======== Quantization =============
+QP                            : 25          # quantization parameter (mc)
+MaxDeltaQP                    : 0           # CU-based multi-QP optimization
+MaxCuDQPDepth                 : 0           # Max depth of a minimum CuDQP for sub-LCU-level delta QP
+DeltaQpRD                     : 0           # Slice-based multi-QP optimization
+RDOQ                          : 1           # RDOQ
+RDOQTS                        : 1           # RDOQ for transform skip
+SliceChromaQPOffsetPeriodicity: 0           # Used in conjunction with Slice Cb/Cr QpOffsetIntraOrPeriodic. Use 0 (default) to disable periodic nature.
+SliceCbQpOffsetIntraOrPeriodic: 0           # Chroma Cb QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
+SliceCrQpOffsetIntraOrPeriodic: 0           # Chroma Cr QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
+
+#=========== Deblock Filter ============
+
+LoopFilterOffsetInPPS         : 1           # Dbl params: 0=varying params in SliceHeader, param = base_param + GOP_offset_param; 1 (default) =constant params in PPS, param = base_param)
+LoopFilterDisable             : 0           # Disable deblocking filter (0=Filter, 1=No Filter) (mc)
+LoopFilterBetaOffset_div2     : 0           # base_param: -6 ~ 6 
+LoopFilterTcOffset_div2       : 0           # base_param: -6 ~ 6
+DeblockingFilterMetric        : 0           # blockiness metric (automatically configures deblocking parameters in bitstream). Applies slice-level loop filter offsets (LoopFilterOffsetInPPS and LoopFilterDisable must be 0)
+
+
+#=========== Coding Tools =================
+SAO                           : 1           # Sample adaptive offset  (0: OFF, 1: ON) (mc)
+AMP                           : 1           # Asymmetric motion partitions (0: OFF, 1: ON)
+TransformSkip                 : 1           # Transform skipping (0: OFF, 1: ON)
+TransformSkipFast             : 1           # Fast Transform skipping (0: OFF, 1: ON)
+SAOLcuBoundary                : 0           # SAOLcuBoundary using non-deblocked pixels (0: OFF, 1: ON)
+
+### DO NOT ADD ANYTHING BELOW THIS LINE ###
+### DO NOT DELETE THE EMPTY LINE BELOW ###
Index: /trunk/source/App/TAppDecoder/TAppDecCfg.cpp
===================================================================
--- /trunk/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 1412)
+++ /trunk/source/App/TAppDecoder/TAppDecCfg.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -115,4 +115,7 @@
 #endif
   ("ClipOutputVideoToRec709Range",      m_bClipOutputVideoToRec709Range,  false, "If true then clip output video to the Rec. 709 Range on saving")
+#if MCTS_ENC_CHECK
+  ("TMCTSCheck",                  m_tmctsCheck,                          false,    "If enabled, the decoder checks for violations of mc_exact_sample_value_match_flag in Temporal MCTS ")
+#endif
   ;
 
Index: /trunk/source/App/TAppDecoder/TAppDecCfg.h
===================================================================
--- /trunk/source/App/TAppDecoder/TAppDecCfg.h	(revision 1412)
+++ /trunk/source/App/TAppDecoder/TAppDecCfg.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -78,4 +78,8 @@
   std::string   m_outputDecodedSEIMessagesFilename;   ///< filename to output decoded SEI messages to. If '-', then use stdout. If empty, do not output details.
   Bool          m_bClipOutputVideoToRec709Range;      ///< If true, clip the output video to the Rec 709 range on saving.
+#if MCTS_ENC_CHECK
+  Bool          m_tmctsCheck;
+#endif
+
 #if NH_MV
   std::vector<TChar*> m_pchReconFiles;                ///< array of output reconstruction file name create from output reconstruction file name
@@ -122,9 +126,11 @@
   , m_outputDecodedSEIMessagesFilename()
   , m_bClipOutputVideoToRec709Range(false)
+#if MCTS_ENC_CHECK
+  , m_tmctsCheck(false)
+#endif
 #if NH_MV
   , m_highestTid(-1)
   , m_targetDecLayerIdSetFileEmpty(true)
 #endif
-
   {
     for (UInt channelTypeIndex = 0; channelTypeIndex < MAX_NUM_CHANNEL_TYPE; channelTypeIndex++)
Index: /trunk/source/App/TAppDecoder/TAppDecTop.cpp
===================================================================
--- /trunk/source/App/TAppDecoder/TAppDecTop.cpp	(revision 1412)
+++ /trunk/source/App/TAppDecoder/TAppDecTop.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -405,5 +405,5 @@
   // initialize global variables
   initROM();
-#if NH_3D_DMM
+#if NH_3D
   initWedgeLists();
 #endif
@@ -474,4 +474,7 @@
   m_cTDecTop.init();
   m_cTDecTop.setDecodedPictureHashSEIEnabled(m_decodedPictureHashSEIEnabled);
+#if MCTS_ENC_CHECK
+  m_cTDecTop.setTMctsCheckEnabled(m_tmctsCheck);
+#endif
 #if O0043_BEST_EFFORT_DECODING
   m_cTDecTop.setForceDecodeBitDepth(m_forceDecodeBitDepth);
@@ -1262,4 +1265,5 @@
     m_vps->printLayerSets();
     m_vps->printPTL();
+    m_vps->printRepFormat();
   }
 }
@@ -2223,21 +2227,34 @@
   ////////////////////////////////////////////////////////////////////////////////
 
-  const TComDpbSize* dpbSize = m_vps->getDpbSize();
-  m_maxNumReorderPics       = dpbSize->getMaxVpsNumReorderPics      ( m_targetOptLayerSetIdx, m_highestTid );
-  m_maxLatencyIncreasePlus1 = dpbSize->getMaxVpsLatencyIncreasePlus1( m_targetOptLayerSetIdx, m_highestTid );
-  m_maxLatencyValue         = dpbSize->getVpsMaxLatencyPictures     ( m_targetOptLayerSetIdx, m_highestTid );
-
-  for(Int i = 0; i < MAX_NUM_LAYER_IDS; i++)
-  {
-    m_maxDecPicBufferingMinus1[ i ] = MIN_INT;
-  }
-  for( Int i = 0; i <= m_vps->getMaxLayersMinus1(); i++ )
-  {
-    Int currLayerId = m_vps->getLayerIdInNuh( i );
-    for(Int layerIdx = 0 ; layerIdx < m_vps->getNumLayersInIdList( m_targetDecLayerSetIdx); layerIdx++ )
-    {
-      if( m_vps->getLayerSetLayerIdList( m_targetDecLayerSetIdx, layerIdx ) == currLayerId )
-      {
-        m_maxDecPicBufferingMinus1[currLayerId] = dpbSize->getMaxVpsDecPicBufferingMinus1( m_targetDecLayerSetIdx, layerIdx, m_highestTid );
+  // According to spec, no dbpSize values are given for OLS 0, however they are used in F.13.5.2.1. 
+  // This might be an issue of the spec. As workaround use sps for OLS 0 here.
+
+  if ( m_targetOptLayerSetIdx == 0 )
+  { 
+    m_maxNumReorderPics            = m_sps->getSpsMaxNumReorderPics      ( m_highestTid );
+    m_maxLatencyIncreasePlus1      = m_sps->getSpsMaxLatencyIncreasePlus1( m_highestTid );
+    m_maxLatencyValue              = m_sps->getSpsMaxLatencyPictures     ( m_highestTid );
+    m_maxDecPicBufferingMinus1[0]  = m_sps->getMaxDecPicBuffering        ( m_highestTid );
+  }
+  else
+  {
+    const TComDpbSize* dpbSize = m_vps->getDpbSize();
+    m_maxNumReorderPics       = dpbSize->getMaxVpsNumReorderPics      ( m_targetOptLayerSetIdx, m_highestTid );
+    m_maxLatencyIncreasePlus1 = dpbSize->getMaxVpsLatencyIncreasePlus1( m_targetOptLayerSetIdx, m_highestTid );
+    m_maxLatencyValue         = dpbSize->getVpsMaxLatencyPictures     ( m_targetOptLayerSetIdx, m_highestTid );
+
+    for(Int i = 0; i < MAX_NUM_LAYER_IDS; i++)
+    {
+      m_maxDecPicBufferingMinus1[ i ] = MIN_INT;
+    }
+    for( Int i = 0; i <= m_vps->getMaxLayersMinus1(); i++ )
+    {
+      Int currLayerId = m_vps->getLayerIdInNuh( i );
+      for(Int layerIdx = 0 ; layerIdx < m_vps->getNumLayersInIdList( m_targetDecLayerSetIdx); layerIdx++ )
+      {
+        if( m_vps->getLayerSetLayerIdList( m_targetDecLayerSetIdx, layerIdx ) == currLayerId )
+        {
+          m_maxDecPicBufferingMinus1[currLayerId] = dpbSize->getMaxVpsDecPicBufferingMinus1( m_targetDecLayerSetIdx, layerIdx, m_highestTid );
+        }
       }
     }
@@ -2673,4 +2690,7 @@
     m_tDecTop[ decIdx ]->setLayerId( layerId );
     m_tDecTop[ decIdx ]->setDecodedPictureHashSEIEnabled(m_decodedPictureHashSEIEnabled);
+#if MCTS_ENC_CHECK
+    m_tDecTop[ decIdx ]->setTMctsCheckEnabled( m_tmctsCheck );
+#endif
     m_tDecTop[ decIdx ]->setDpb( &m_dpb );
     m_tDecTop[ decIdx ]->setTargetOlsIdx( m_targetOptLayerSetIdx );
@@ -2678,6 +2698,4 @@
     m_tDecTop[ decIdx ]->setPocDecrementedInDPBFlag   ( m_pocDecrementedInDpbFlag    );
     m_tDecTop[ decIdx ]->setLastPresentPocResetIdc    ( m_lastPresentPocResetIdc );
-
-
 #if O0043_BEST_EFFORT_DECODING
     m_cTDecTop[ decIdx ]->setForceDecodeBitDepth(m_forceDecodeBitDepth);
Index: /trunk/source/App/TAppDecoder/TAppDecTop.h
===================================================================
--- /trunk/source/App/TAppDecoder/TAppDecTop.h	(revision 1412)
+++ /trunk/source/App/TAppDecoder/TAppDecTop.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/App/TAppDecoder/decmain.cpp
===================================================================
--- /trunk/source/App/TAppDecoder/decmain.cpp	(revision 1412)
+++ /trunk/source/App/TAppDecoder/decmain.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -70,5 +70,6 @@
   Int curDecoding  = 0; 
   Double dResult = 0; 
-  do {
+  do 
+  {
     TAppDecTop  cTAppDecTop;
 #endif
Index: /trunk/source/App/TAppEncoder/TAppEncCfg.cpp
===================================================================
--- /trunk/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 1412)
+++ /trunk/source/App/TAppEncoder/TAppEncCfg.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -46,4 +46,8 @@
 #include "TAppCommon/program_options_lite.h"
 #include "TLibEncoder/TEncRateCtrl.h"
+#if NH_MV
+#include <set>
+#endif
+
 #ifdef WIN32
 #define strdup _strdup
@@ -57,47 +61,58 @@
 
 
-
-enum ExtendedProfileName // this is used for determining profile strings, where multiple profiles map to a single profile idc with various constraint flag combinations
+#if !NH_MV
+enum UIProfileName // this is used for determining profile strings, where multiple profiles map to a single profile idc with various constraint flag combinations
 {
-  NONE = 0,
-  MAIN = 1,
-  MAIN10 = 2,
-  MAINSTILLPICTURE = 3,
-  MAINREXT = 4,
-  HIGHTHROUGHPUTREXT = 5, // Placeholder profile for development
+  UI_NONE = 0,
+  UI_MAIN = 1,
+  UI_MAIN10 = 2,
+  UI_MAIN10_STILL_PICTURE=10002,
+  UI_MAINSTILLPICTURE = 3,
+  UI_MAINREXT = 4,
+  UI_HIGHTHROUGHPUTREXT = 5,
   // The following are RExt profiles, which would map to the MAINREXT profile idc.
   // The enumeration indicates the bit-depth constraint in the bottom 2 digits
   //                           the chroma format in the next digit
-    //                           the intra constraint in the next digit
+  //                           the intra constraint in the next digit (1 for no intra constraint, 2 for intra constraint)
 //                           If it is a RExt still picture, there is a '1' for the top digit.
 #if NH_MV
-  MULTIVIEWMAIN = 6,
+  UI_MULTIVIEWMAIN     = 6,
 #if NH_3D
-  MAIN3D = 8, 
-#endif
-#endif
-  MONOCHROME_8      = 1008,
-  MONOCHROME_12     = 1012,
-  MONOCHROME_16     = 1016,
-  MAIN_12           = 1112,
-  MAIN_422_10       = 1210,
-  MAIN_422_12       = 1212,
-  MAIN_444          = 1308,
-  MAIN_444_10       = 1310,
-  MAIN_444_12       = 1312,
-  MAIN_444_16       = 1316, // non-standard profile definition, used for development purposes
-  MAIN_INTRA        = 2108,
-  MAIN_10_INTRA     = 2110,
-  MAIN_12_INTRA     = 2112,
-  MAIN_422_10_INTRA = 2210,
-  MAIN_422_12_INTRA = 2212,
-  MAIN_444_INTRA    = 2308,
-  MAIN_444_10_INTRA = 2310,
-  MAIN_444_12_INTRA = 2312,
-  MAIN_444_16_INTRA = 2316,
-  MAIN_444_STILL_PICTURE = 11308,
-  MAIN_444_16_STILL_PICTURE = 12316
+  UI_MAIN3D            = 8, 
+#endif
+#endif
+  UI_MONOCHROME_8      = 1008,
+  UI_MONOCHROME_12     = 1012,
+  UI_MONOCHROME_16     = 1016,
+  UI_MAIN_12           = 1112,
+  UI_MAIN_422_10       = 1210,
+  UI_MAIN_422_12       = 1212,
+  UI_MAIN_444          = 1308,
+  UI_MAIN_444_10       = 1310,
+  UI_MAIN_444_12       = 1312,
+  UI_MAIN_444_16       = 1316, // non-standard profile definition, used for development purposes
+  UI_MAIN_INTRA        = 2108,
+  UI_MAIN_10_INTRA     = 2110,
+  UI_MAIN_12_INTRA     = 2112,
+  UI_MAIN_422_10_INTRA = 2210,
+  UI_MAIN_422_12_INTRA = 2212,
+  UI_MAIN_444_INTRA    = 2308,
+  UI_MAIN_444_10_INTRA = 2310,
+  UI_MAIN_444_12_INTRA = 2312,
+  UI_MAIN_444_16_INTRA = 2316,
+  UI_MAIN_444_STILL_PICTURE = 11308,
+  UI_MAIN_444_16_STILL_PICTURE = 12316,
+  // The following are high throughput profiles, which would map to the HIGHTHROUGHPUTREXT profile idc.
+  // The enumeration indicates the bit-depth constraint in the bottom 2 digits
+  //                           the chroma format in the next digit
+  //                           the intra constraint in the next digit
+  //                           There is a '2' for the top digit to indicate it is high throughput profile
+  
+  UI_HIGHTHROUGHPUT_444     = 21308,
+  UI_HIGHTHROUGHPUT_444_10  = 21310,
+  UI_HIGHTHROUGHPUT_444_14  = 21314,
+  UI_HIGHTHROUGHPUT_444_16_INTRA  = 22316
 };
-
+#endif
 
 //! \ingroup TAppEncoder
@@ -112,4 +127,7 @@
 , m_snrInternalColourSpace(false)
 , m_outputInternalColourSpace(false)
+#if EXTENSION_360_VIDEO
+, m_ext360(*this)
+#endif
 {
 #if !NH_MV
@@ -208,4 +226,25 @@
 
 #if NH_MV
+
+GOPEntry* TAppEncCfg::xGetGopEntries(Int layerIdInVps)
+{
+  return m_GOPListMvc[ m_layerIdxInVpsToGopDefIdx[ layerIdInVps ] ];
+}
+
+GOPEntry* TAppEncCfg::xGetGopEntry(Int layerIdInVps, Int poc)
+{
+  GOPEntry* geFound = NULL; 
+  for( Int i = 0; i < ( getGOPSize() + 1) && geFound == NULL ; i++ ) 
+  {
+    GOPEntry* ge = &(xGetGopEntries( layerIdInVps)[ ( i < getGOPSize()  ? i : MAX_GOP ) ]);
+    if ( ge->m_POC == poc )
+    {
+      geFound = ge;       
+    }
+  }
+  assert( geFound != NULL ); 
+  return geFound;
+}
+
 Void TAppEncCfg::xParseSeiCfg()
 {
@@ -239,8 +278,10 @@
   in>>entry.m_POC;
   in>>entry.m_QPOffset;
-#if W0038_CQP_ADJ
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+  in>>entry.m_QPOffsetModelOffset;
+  in>>entry.m_QPOffsetModelScale;
+#endif
   in>>entry.m_CbQPoffset;
   in>>entry.m_CrQPoffset;
-#endif
   in>>entry.m_QPFactor;
   in>>entry.m_tcOffsetDiv2;
@@ -302,4 +343,17 @@
   }
 }
+
+#if NH_MV
+static inline std::vector<ChromaFormat> numberToChromaFormat(const IntAry1d val)
+{
+  std::vector<ChromaFormat> chromaFormats;
+  for( Int i = 0; i < val.size(); i++)
+  {
+    chromaFormats.push_back( numberToChromaFormat( val[i] ) );
+  }
+  return chromaFormats;
+}
+#endif
+
 
 static const struct MapStrToProfile
@@ -314,10 +368,17 @@
   {"main10",               Profile::MAIN10             },
   {"main-still-picture",   Profile::MAINSTILLPICTURE   },
+  {"main10-still-picture", Profile::MAIN10             },
   {"main-RExt",            Profile::MAINREXT           },
   {"high-throughput-RExt", Profile::HIGHTHROUGHPUTREXT }
 #if NH_MV
-  ,{"multiview-main"     , Profile::MULTIVIEWMAIN      },
+  ,{"multiview-main"     , Profile::MULTIVIEWMAIN      }
+#if NH_MV_ALLOW_NON_CONFORMING
+  ,{"multiview-main_NONCONFORMING", Profile::MULTIVIEWMAIN_NONCONFORMING }
 #if NH_3D
-   {"3d-main"            , Profile::MAIN3D             }
+  ,{"3d-main_NONCONFORMING"       , Profile::MAIN3D_NONCONFORMING }
+#endif
+#endif
+#if NH_3D
+   ,{"3d-main"                    , Profile::MAIN3D             }   
 #endif
 #endif
@@ -325,66 +386,84 @@
 };
 
-static const struct MapStrToExtendedProfile
+static const struct MapStrToUIProfileName
 {
   const TChar* str;
-  ExtendedProfileName value;
+  UIProfileName value;
 }
-strToExtendedProfile[] =
+strToUIProfileName[] =
 {
-    {"none",               NONE             },
-    {"main",               MAIN             },
-    {"main10",             MAIN10           },
-    {"main_still_picture",        MAINSTILLPICTURE },
-    {"main-still-picture",        MAINSTILLPICTURE },
-    {"main_RExt",                 MAINREXT         },
-    {"main-RExt",                 MAINREXT         },
-    {"main_rext",                 MAINREXT         },
-    {"main-rext",                 MAINREXT         },
-    {"high_throughput_RExt",      HIGHTHROUGHPUTREXT },
-    {"high-throughput-RExt",      HIGHTHROUGHPUTREXT },
-    {"high_throughput_rext",      HIGHTHROUGHPUTREXT },
-    {"high-throughput-rext",      HIGHTHROUGHPUTREXT },
-#if NH_MV
-    {"multiview-main"     , MULTIVIEWMAIN   },
+    {"none",                      UI_NONE             },
+    {"main",                      UI_MAIN             },
+    {"main10",                    UI_MAIN10           },
+    {"main10_still_picture",      UI_MAIN10_STILL_PICTURE },
+    {"main10-still-picture",      UI_MAIN10_STILL_PICTURE },
+    {"main_still_picture",        UI_MAINSTILLPICTURE },
+    {"main-still-picture",        UI_MAINSTILLPICTURE },
+    {"main_RExt",                 UI_MAINREXT         },
+    {"main-RExt",                 UI_MAINREXT         },
+    {"main_rext",                 UI_MAINREXT         },
+    {"main-rext",                 UI_MAINREXT         },
+    {"high_throughput_RExt",      UI_HIGHTHROUGHPUTREXT },
+    {"high-throughput-RExt",      UI_HIGHTHROUGHPUTREXT },
+    {"high_throughput_rext",      UI_HIGHTHROUGHPUTREXT },
+    {"high-throughput-rext",      UI_HIGHTHROUGHPUTREXT },
+#if NH_MV
+    {"multiview-main"     , UI_MULTIVIEWMAIN   },
 #if NH_3D
-    {"3d-main"            , MAIN3D          },
-#endif
-#endif
-    {"monochrome",         MONOCHROME_8     },
-    {"monochrome12",       MONOCHROME_12    },
-    {"monochrome16",       MONOCHROME_16    },
-    {"main12",             MAIN_12          },
-    {"main_422_10",        MAIN_422_10      },
-    {"main_422_12",        MAIN_422_12      },
-    {"main_444",           MAIN_444         },
-    {"main_444_10",        MAIN_444_10      },
-    {"main_444_12",        MAIN_444_12      },
-    {"main_444_16",        MAIN_444_16      },
-    {"main_intra",         MAIN_INTRA       },
-    {"main_10_intra",      MAIN_10_INTRA    },
-    {"main_12_intra",      MAIN_12_INTRA    },
-    {"main_422_10_intra",  MAIN_422_10_INTRA},
-    {"main_422_12_intra",  MAIN_422_12_INTRA},
-    {"main_444_intra",     MAIN_444_INTRA   },
-    {"main_444_still_picture",    MAIN_444_STILL_PICTURE },
-    {"main_444_10_intra",  MAIN_444_10_INTRA},
-    {"main_444_12_intra",  MAIN_444_12_INTRA},
-    {"main_444_16_intra",         MAIN_444_16_INTRA},
-    {"main_444_16_still_picture", MAIN_444_16_STILL_PICTURE }
+    {"3d-main"            , UI_MAIN3D          },
+#endif
+#if NH_MV_ALLOW_NON_CONFORMING
+    {"multiview-main_NONCONFORMING"     , UI_MULTIVIEWMAIN_NONCONF   },
+#if NH_3D
+    {"3d-main_NONCONFORMING"            , UI_MAIN3D_NONCONF          },
+#endif
+#endif
+#endif
+    {"monochrome",                UI_MONOCHROME_8     },
+    {"monochrome12",              UI_MONOCHROME_12    },
+    {"monochrome16",              UI_MONOCHROME_16    },
+    {"main12",                    UI_MAIN_12          },
+    {"main_422_10",               UI_MAIN_422_10      },
+    {"main_422_12",               UI_MAIN_422_12      },
+    {"main_444",                  UI_MAIN_444         },
+    {"main_444_10",               UI_MAIN_444_10      },
+    {"main_444_12",               UI_MAIN_444_12      },
+    {"main_444_16",               UI_MAIN_444_16      },
+    {"main_intra",                UI_MAIN_INTRA       },
+    {"main_10_intra",             UI_MAIN_10_INTRA    },
+    {"main_12_intra",             UI_MAIN_12_INTRA    },
+    {"main_422_10_intra",         UI_MAIN_422_10_INTRA},
+    {"main_422_12_intra",         UI_MAIN_422_12_INTRA},
+    {"main_444_intra",            UI_MAIN_444_INTRA   },
+    {"main_444_still_picture",    UI_MAIN_444_STILL_PICTURE },
+    {"main_444_10_intra",         UI_MAIN_444_10_INTRA},
+    {"main_444_12_intra",         UI_MAIN_444_12_INTRA},
+    {"main_444_16_intra",         UI_MAIN_444_16_INTRA},
+    {"main_444_16_still_picture", UI_MAIN_444_16_STILL_PICTURE },
+    {"high_throughput_444",       UI_HIGHTHROUGHPUT_444    },
+    {"high_throughput_444_10",    UI_HIGHTHROUGHPUT_444_10 },
+    {"high_throughput_444_14",    UI_HIGHTHROUGHPUT_444_14 },
+    {"high_throughput_444_16_intra", UI_HIGHTHROUGHPUT_444_16_INTRA }
 };
 
-static const ExtendedProfileName validRExtProfileNames[2/* intraConstraintFlag*/][4/* bit depth constraint 8=0, 10=1, 12=2, 16=3*/][4/*chroma format*/]=
+static const UIProfileName validRExtHighThroughPutProfileNames[2/* intraConstraintFlag*/][4/* bit depth constraint 8=0, 10=1, 12=2, 16=3*/]=
 {
-    {
-        { MONOCHROME_8,  NONE,          NONE,              MAIN_444          }, // 8-bit  inter for 400, 420, 422 and 444
-        { NONE,          NONE,          MAIN_422_10,       MAIN_444_10       }, // 10-bit inter for 400, 420, 422 and 444
-        { MONOCHROME_12, MAIN_12,       MAIN_422_12,       MAIN_444_12       }, // 12-bit inter for 400, 420, 422 and 444
-        { MONOCHROME_16, NONE,          NONE,              MAIN_444_16       }  // 16-bit inter for 400, 420, 422 and 444 (the latter is non standard used for development)
+    { UI_HIGHTHROUGHPUT_444,          UI_HIGHTHROUGHPUT_444_10,          UI_HIGHTHROUGHPUT_444_14,         UI_NONE                         }, // intraConstraintFlag 0 - 8-bit,10-bit,14-bit and 16-bit
+    { UI_NONE,                        UI_NONE,                           UI_NONE,                          UI_HIGHTHROUGHPUT_444_16_INTRA  }  // intraConstraintFlag 1 - 8-bit,10-bit,14-bit and 16-bit
+};
+
+static const UIProfileName validRExtProfileNames[2/* intraConstraintFlag*/][4/* bit depth constraint 8=0, 10=1, 12=2, 16=3*/][4/*chroma format*/]=
+{
+    {
+        { UI_MONOCHROME_8,  UI_NONE,          UI_NONE,              UI_MAIN_444          }, // 8-bit  inter for 400, 420, 422 and 444
+        { UI_NONE,          UI_NONE,          UI_MAIN_422_10,       UI_MAIN_444_10       }, // 10-bit inter for 400, 420, 422 and 444
+        { UI_MONOCHROME_12, UI_MAIN_12,       UI_MAIN_422_12,       UI_MAIN_444_12       }, // 12-bit inter for 400, 420, 422 and 444
+        { UI_MONOCHROME_16, UI_NONE,          UI_NONE,              UI_MAIN_444_16       }  // 16-bit inter for 400, 420, 422 and 444 (the latter is non standard used for development)
     },
     {
-        { NONE,          MAIN_INTRA,    NONE,              MAIN_444_INTRA    }, // 8-bit  intra for 400, 420, 422 and 444
-        { NONE,          MAIN_10_INTRA, MAIN_422_10_INTRA, MAIN_444_10_INTRA }, // 10-bit intra for 400, 420, 422 and 444
-        { NONE,          MAIN_12_INTRA, MAIN_422_12_INTRA, MAIN_444_12_INTRA }, // 12-bit intra for 400, 420, 422 and 444
-        { NONE,          NONE,          NONE,              MAIN_444_16_INTRA }  // 16-bit intra for 400, 420, 422 and 444
+        { UI_NONE,          UI_MAIN_INTRA,    UI_NONE,              UI_MAIN_444_INTRA    }, // 8-bit  intra for 400, 420, 422 and 444
+        { UI_NONE,          UI_MAIN_10_INTRA, UI_MAIN_422_10_INTRA, UI_MAIN_444_10_INTRA }, // 10-bit intra for 400, 420, 422 and 444
+        { UI_NONE,          UI_MAIN_12_INTRA, UI_MAIN_422_12_INTRA, UI_MAIN_444_12_INTRA }, // 12-bit intra for 400, 420, 422 and 444
+        { UI_NONE,          UI_NONE,          UI_NONE,              UI_MAIN_444_16_INTRA }  // 16-bit intra for 400, 420, 422 and 444
     }
 };
@@ -425,5 +504,4 @@
 };
 
-#if U0132_TARGET_BITS_SATURATION
 UInt g_uiMaxCpbSize[2][21] =
 {
@@ -432,5 +510,4 @@
   { 0, 0, 0,      0, 0, 0,       0,       0, 0,       0,        0, 0, 30000000, 50000000, 0, 100000000, 160000000, 240000000, 240000000, 480000000, 800000000 }
 };
-#endif
 
 static const struct MapStrToCostMode
@@ -481,15 +558,15 @@
   in >> str;
 
-  for (UInt i = 0; i < mapLen; i++)
-  {
-    if (str == map[i].str)
+  UInt i=0;
+  for (; i < mapLen && str!=map[i].str; i++);
+
+  if (i < mapLen)
     {
       val = map[i].value;
-      goto found;
-    }
-  }
-  /* not found */
+    }
+  else
+  {
   in.setstate(ios::failbit);
-found:
+  }
   return in;
 }
@@ -497,7 +574,7 @@
 //inline to prevent compiler warnings for "unused static function"
 
-static inline istream& operator >> (istream &in, ExtendedProfileName &profile)
+static inline istream& operator >> (istream &in, UIProfileName &profile)
 {
-  return readStrToEnum(strToExtendedProfile, sizeof(strToExtendedProfile)/sizeof(*strToExtendedProfile), in, profile);
+  return readStrToEnum(strToUIProfileName, sizeof(strToUIProfileName)/sizeof(*strToUIProfileName), in, profile);
 }
 
@@ -640,4 +717,22 @@
 }
 
+#if JVET_E0059_FLOATING_POINT_QP_FIX
+template <class T>
+static inline istream& operator >> (std::istream &in, TAppEncCfg::OptionalValue<T> &value)
+{
+  in >> std::ws;
+  if (in.eof())
+  {
+    value.bPresent=false;
+  }
+  else
+  {
+    in >> value.value;
+    value.bPresent=true;
+  }
+  return in;
+}
+#endif
+
 static Void
 automaticallySelectRExtProfile(const Bool bUsingGeneralRExtTools,
@@ -740,7 +835,24 @@
 #endif
 
+#if NH_MV
+  IntAry1d tmpInputChromaFormat;
+  IntAry1d tmpChromaFormat;
+#if NH_3D
+  IntAry1d tmpChromaFormatInit;
+  tmpChromaFormatInit.push_back(420);
+  tmpChromaFormatInit.push_back(400);
+#endif
+  IntAry2d tmpPad(2);
+
+  IntAry2d tmpInputBitDepth      (2);
+  IntAry2d tmpOutputBitDepth     (2);
+  IntAry2d tmpMSBExtendedBitDepth(2);
+  IntAry2d tmpInternalBitDepth   (2);
+
+#else
+  Int tmpInputChromaFormat;
   Int tmpChromaFormat;
-  Int tmpInputChromaFormat;
   Int tmpConstraintChromaFormat;
+#endif
   Int tmpWeightedPredictionMethod;
   Int tmpFastInterSearchMode;
@@ -751,7 +863,7 @@
   string inputColourSpaceConvert;
 #if NH_MV
-  std::vector<ExtendedProfileName> extendedProfiles;
-#else
-  ExtendedProfileName extendedProfile;
+  std::vector<UIProfileName> UIProfiles;
+#else
+  UIProfileName UIProfile;
 #endif
   Int saoOffsetBitShift[MAX_NUM_CHANNEL_TYPE];
@@ -766,4 +878,9 @@
   SMultiValueInput<Double> cfg_adIntraLambdaModifier         (0, std::numeric_limits<Double>::max(), 0, MAX_TLAYER); ///< Lambda modifier for Intra pictures, one for each temporal layer. If size>temporalLayer, then use [temporalLayer], else if size>0, use [size()-1], else use m_adLambdaModifier.
 
+  const Int defaultLumaLevelTodQp_QpChangePoints[]   =  {-3,  -2,  -1,   0,   1,   2,   3,   4,   5,   6};
+  const Int defaultLumaLevelTodQp_LumaChangePoints[] =  { 0, 301, 367, 434, 501, 567, 634, 701, 767, 834};
+  SMultiValueInput<Int>  cfg_lumaLeveltoDQPMappingQP         (-MAX_QP, MAX_QP,                    0, LUMA_LEVEL_TO_DQP_LUT_MAXSIZE, defaultLumaLevelTodQp_QpChangePoints,   sizeof(defaultLumaLevelTodQp_QpChangePoints  )/sizeof(Int));
+  SMultiValueInput<Int>  cfg_lumaLeveltoDQPMappingLuma       (0, std::numeric_limits<Int>::max(), 0, LUMA_LEVEL_TO_DQP_LUT_MAXSIZE, defaultLumaLevelTodQp_LumaChangePoints, sizeof(defaultLumaLevelTodQp_LumaChangePoints)/sizeof(Int));
+  UInt lumaLevelToDeltaQPMode;
 
   const UInt defaultInputKneeCodes[3]  = { 600, 800, 900 };
@@ -842,7 +959,22 @@
   ("ProfileTierLevelIdx_%d"        , m_profileTierLevelIdx         , IntAry1d(0)  , MAX_NUM_LAYERS,                  "Indices to profile level tier for ols")
   // Layer dependencies
-  ("DirectRefLayers_%d"            , m_directRefLayers             , IntAry1d(0,0), MAX_NUM_LAYERS,                  "LayerIdx in VPS of direct reference layers")
-  ("DependencyTypes_%d"            , m_dependencyTypes             , IntAry1d(0,0), MAX_NUM_LAYERS,                  "Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion")
-#endif
+  ("DirectRefLayers_%d"            , m_directRefLayers               , IntAry1d(0,0), MAX_NUM_LAYERS,                  "LayerIdx in VPS of direct reference layers")
+  ("DependencyTypes_%d"            , m_dependencyTypes               , IntAry1d(0,0), MAX_NUM_LAYERS,                  "Dependency types of direct reference layers, 0: Sample 1: Motion 2: Sample+Motion")
+  ("ShareParameterSets"            , m_shareParameterSets            , false        ,                                  "Signal parameter sets only in the base layer.")  
+  ("LayerIdxInVpsToGopDefIdx"      , m_layerIdxInVpsToGopDefIdx      , IntAry1d(0,0),                                  "Maps the layers to the GOP definitions in the cfg-file.")
+  ("LayerIdxInVpsToRepFormatIdx"   , m_layerIdxInVpsToRepFormatIdx   , IntAry1d(0,0),                                  "Maps the layers to the vps representation formats, i.e. values of SourceWidth, SourceHeight, InternalBitDepth, ChromaFormatIDC, InputBitDepth, OutputBitDepth, MSBExtendedBitDepth, InputChromaFormat, ConfWinBottom, ConfWinTop, ConfWinRight, ConfWinLeft, VerticalPadding, HorizontalPadding." )  
+#endif
+#if NH_MV
+  ("SourceWidth,-wdt",                                m_iSourceWidths,                            IntAry1d(1,0), "Source picture width")
+  ("SourceHeight,-hgt",                               m_iSourceHeights,                           IntAry1d(1,0), "Source picture height")
+  ("InputBitDepth",                                   tmpInputBitDepth      [CHANNEL_TYPE_LUMA  ], IntAry1d(1,8), "Bit-depth of input file")
+  ("OutputBitDepth",                                  tmpOutputBitDepth     [CHANNEL_TYPE_LUMA  ], IntAry1d(1,0), "Bit-depth of output file (default:InternalBitDepth)")
+  ("MSBExtendedBitDepth",                             tmpMSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ], IntAry1d(1,0), "bit depth of luma component after addition of MSBs of value 0 (used for synthesising High Dynamic Range source material). (default:InputBitDepth)")
+  ("InternalBitDepth",                                tmpInternalBitDepth   [CHANNEL_TYPE_LUMA  ], IntAry1d(1,0), "Bit-depth the codec operates at. (default:MSBExtendedBitDepth). If different to MSBExtendedBitDepth, source data will be converted")
+  ("InputBitDepthC",                                  tmpInputBitDepth      [CHANNEL_TYPE_CHROMA], IntAry1d(1,0), "As per InputBitDepth but for chroma component. (default:InputBitDepth)")
+  ("OutputBitDepthC",                                 tmpOutputBitDepth     [CHANNEL_TYPE_CHROMA], IntAry1d(1,0), "As per OutputBitDepth but for chroma component. (default:InternalBitDepthC)")
+  ("MSBExtendedBitDepthC",                            tmpMSBExtendedBitDepth[CHANNEL_TYPE_CHROMA], IntAry1d(1,0), "As per MSBExtendedBitDepth but for chroma component. (default:MSBExtendedBitDepth)")
+  ("InternalBitDepthC",                               tmpInternalBitDepth   [CHANNEL_TYPE_CHROMA], IntAry1d(1,0), "As per InternalBitDepth but for chroma component. (default:InternalBitDepth)")
+#else
   ("SourceWidth,-wdt",                                m_iSourceWidth,                                       0, "Source picture width")
   ("SourceHeight,-hgt",                               m_iSourceHeight,                                      0, "Source picture height")
@@ -855,4 +987,5 @@
   ("MSBExtendedBitDepthC",                            m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA],           0, "As per MSBExtendedBitDepth but for chroma component. (default:MSBExtendedBitDepth)")
   ("InternalBitDepthC",                               m_internalBitDepth[CHANNEL_TYPE_CHROMA],              0, "As per InternalBitDepth but for chroma component. (default:InternalBitDepth)")
+#endif
   ("ExtendedPrecision",                               m_extendedPrecisionProcessingFlag,                false, "Increased internal accuracies to support high bit depths (not valid in V1 profiles)")
   ("HighPrecisionPredictionWeighting",                m_highPrecisionOffsetsEnabledFlag,                false, "Use high precision option for weighted prediction (not valid in V1 profiles)")
@@ -860,22 +993,52 @@
   ("SNRInternalColourSpace",                          m_snrInternalColourSpace,                         false, "If true, then no colour space conversion is applied prior to SNR, otherwise inverse of input is applied.")
   ("OutputInternalColourSpace",                       m_outputInternalColourSpace,                      false, "If true, then no colour space conversion is applied for reconstructed video, otherwise inverse of input is applied.")
+#if NH_MV
+  ("InputChromaFormat",                               tmpInputChromaFormat,                   IntAry1d(1,420), "InputChromaFormatIDC")
+#else
   ("InputChromaFormat",                               tmpInputChromaFormat,                               420, "InputChromaFormatIDC")
+#endif
   ("MSEBasedSequencePSNR",                            m_printMSEBasedSequencePSNR,                      false, "0 (default) emit sequence PSNR only as a linear average of the frame PSNRs, 1 = also emit a sequence PSNR based on an average of the frame MSEs")
   ("PrintFrameMSE",                                   m_printFrameMSE,                                  false, "0 (default) emit only bit count and PSNRs for each frame, 1 = also emit MSE values")
   ("PrintSequenceMSE",                                m_printSequenceMSE,                               false, "0 (default) emit only bit rate and PSNRs for the whole sequence, 1 = also emit MSE values")
+#if JVET_F0064_MSSSIM  
+  ("PrintMSSSIM",                                     m_printMSSSIM,                                    false, "0 (default) do not print MS-SSIM scores, 1 = print MS-SSIM scores for each frame and for the whole sequence")
+#endif
   ("CabacZeroWordPaddingEnabled",                     m_cabacZeroWordPaddingEnabled,                     true, "0 do not add conforming cabac-zero-words to bit streams, 1 (default) = add cabac-zero-words as required")
+#if NH_MV
+#if NH_3D
+  ("ChromaFormatIDC,-cf",                             tmpChromaFormat,                    tmpChromaFormatInit, "ChromaFormatIDC (400|420|422|444 or set 0 (default) for same as InputChromaFormat)")
+#else
+  ("ChromaFormatIDC,-cf",                             tmpChromaFormat,                          IntAry1d(1,0), "ChromaFormatIDC (400|420|422|444 or set 0 (default) for same as InputChromaFormat)")
+#endif
+#else
   ("ChromaFormatIDC,-cf",                             tmpChromaFormat,                                      0, "ChromaFormatIDC (400|420|422|444 or set 0 (default) for same as InputChromaFormat)")
+#endif
   ("ConformanceMode",                                 m_conformanceWindowMode,                              0, "Deprecated alias of ConformanceWindowMode")
   ("ConformanceWindowMode",                           m_conformanceWindowMode,                              0, "Window conformance mode (0: no window, 1:automatic padding, 2:padding, 3:conformance")
+#if NH_MV
+  ("HorizontalPadding,-pdx",                          tmpPad[0] ,                               IntAry1d(1,0), "Horizontal source padding for conformance window mode 2")
+  ("VerticalPadding,-pdy",                            tmpPad[1] ,                               IntAry1d(1,0), "Vertical source padding for conformance window mode 2")
+#else
   ("HorizontalPadding,-pdx",                          m_aiPad[0],                                           0, "Horizontal source padding for conformance window mode 2")
   ("VerticalPadding,-pdy",                            m_aiPad[1],                                           0, "Vertical source padding for conformance window mode 2")
+#endif
+
+#if NH_MV
+  ("ConfWinLeft",                                     m_confWinLefts,                         IntAry1d(1, 0) , "Left offset for window conformance mode 3")
+  ("ConfWinRight",                                    m_confWinRights,                        IntAry1d(1, 0) , "Right offset for window conformance mode 3")
+  ("ConfWinTop",                                      m_confWinTops,                          IntAry1d(1, 0) , "Top offset for window conformance mode 3")
+  ("ConfWinBottom",                                   m_confWinBottoms,                       IntAry1d(1, 0) , "Bottom offset for window conformance mode 3")
+#else
   ("ConfLeft",                                        m_confWinLeft,                                        0, "Deprecated alias of ConfWinLeft")
   ("ConfRight",                                       m_confWinRight,                                       0, "Deprecated alias of ConfWinRight")
   ("ConfTop",                                         m_confWinTop,                                         0, "Deprecated alias of ConfWinTop")
   ("ConfBottom",                                      m_confWinBottom,                                      0, "Deprecated alias of ConfWinBottom")
+
   ("ConfWinLeft",                                     m_confWinLeft,                                        0, "Left offset for window conformance mode 3")
   ("ConfWinRight",                                    m_confWinRight,                                       0, "Right offset for window conformance mode 3")
   ("ConfWinTop",                                      m_confWinTop,                                         0, "Top offset for window conformance mode 3")
   ("ConfWinBottom",                                   m_confWinBottom,                                      0, "Bottom offset for window conformance mode 3")
+#endif
+  
   ("AccessUnitDelimiter",                             m_AccessUnitDelimiter,                            false, "Enable Access Unit Delimiter NALUs")
   ("FrameRate,-fr",                                   m_iFrameRate,                                         0, "Frame rate")
@@ -901,9 +1064,19 @@
   ("Tier"    ,                                        cfg_tiers  ,                                 string(""), "Tier indication in VpsProfileTierLevel (Indication only)")
   ("InblFlag",                                        m_inblFlag ,                       std::vector<Bool>(0), "InblFlags in VpsProfileTierLevel (Indication only)" )
-#else
-  ("Profile",                                         extendedProfile,                                   NONE, "Profile name to use for encoding. Use main (for main), main10 (for main10), main-still-picture, main-RExt (for Range Extensions profile), any of the RExt specific profile names, or none")
+
+  ("MaxBitDepthConstraint",                           m_bitDepthConstraints,           std::vector<Int>( 1,0u) , "Bit depth to use for profile-constraint for RExt profiles. 0=automatically choose based upon other parameters")
+  ("MaxChromaFormatConstraint",                       m_tmpConstraintChromaFormats,    IntAry1d(1,     0)       , "Chroma-format to use for the profile-constraint for RExt profiles. 0=automatically choose based upon other parameters")
+  ("IntraConstraintFlag",                             m_intraConstraintFlags,          BoolAry1d(1,false)       , "Value of general_intra_constraint_flag to use for RExt profiles (not used if an explicit RExt sub-profile is specified)")
+  ("OnePictureOnlyConstraintFlag",                    m_onePictureOnlyConstraintFlags, BoolAry1d(1,false)       , "Value of general_one_picture_only_constraint_flag to use for RExt profiles (not used if an explicit RExt sub-profile is specified)")
+  ("LowerBitRateConstraintFlag",                      m_lowerBitRateConstraintFlags,   BoolAry1d(1,true)        , "Value of general_lower_bit_rate_constraint_flag to use for RExt profiles")
+  ("ProgressiveSource",                               m_progressiveSourceFlags,        BoolAry1d(1,false)       , "Indicate that source is progressive")
+  ("InterlacedSource",                                m_interlacedSourceFlags,         BoolAry1d(1,false)       , "Indicate that source is interlaced")
+  ("NonPackedSource",                                 m_nonPackedConstraintFlags,      BoolAry1d(1,false)       , "Indicate that source does not contain frame packing")
+  ("FrameOnly",                                       m_frameOnlyConstraintFlags,      BoolAry1d(1,false)       , "Indicate that the bitstream contains only frames")
+
+#else
+  ("Profile",                                         UIProfile,                                      UI_NONE, "Profile name to use for encoding. Use main (for main), main10 (for main10), main-still-picture, main-RExt (for Range Extensions profile), any of the RExt specific profile names, or none")
   ("Level",                                           m_level,                                    Level::NONE, "Level limit to be used, eg 5.1, or none")
   ("Tier",                                            m_levelTier,                                Level::MAIN, "Tier to use for interpretation of --Level (main or high only)")
-#endif
   ("MaxBitDepthConstraint",                           m_bitDepthConstraint,                                0u, "Bit depth to use for profile-constraint for RExt profiles. 0=automatically choose based upon other parameters")
   ("MaxChromaFormatConstraint",                       tmpConstraintChromaFormat,                            0, "Chroma-format to use for the profile-constraint for RExt profiles. 0=automatically choose based upon other parameters")
@@ -911,9 +1084,11 @@
   ("OnePictureOnlyConstraintFlag",                    m_onePictureOnlyConstraintFlag,                   false, "Value of general_one_picture_only_constraint_flag to use for RExt profiles (not used if an explicit RExt sub-profile is specified)")
   ("LowerBitRateConstraintFlag",                      m_lowerBitRateConstraintFlag,                      true, "Value of general_lower_bit_rate_constraint_flag to use for RExt profiles")
-
   ("ProgressiveSource",                               m_progressiveSourceFlag,                          false, "Indicate that source is progressive")
   ("InterlacedSource",                                m_interlacedSourceFlag,                           false, "Indicate that source is interlaced")
   ("NonPackedSource",                                 m_nonPackedConstraintFlag,                        false, "Indicate that source does not contain frame packing")
   ("FrameOnly",                                       m_frameOnlyConstraintFlag,                        false, "Indicate that the bitstream contains only frames")
+
+#endif
+
 
   // Unit definition parameters
@@ -939,4 +1114,12 @@
   ("DecodingRefreshType,-dr",                         m_iDecodingRefreshType,                               0, "Intra refresh type (0:none 1:CRA 2:IDR 3:RecPointSEI)")
   ("GOPSize,g",                                       m_iGOPSize,                                           1, "GOP size of temporal structure")
+#if JCTVC_Y0038_PARAMS
+#if NH_MV
+  // To keep compatibility to legacy bit streams.
+  ("ReWriteParamSetsFlag",                            m_bReWriteParamSetsFlag,                           false, "Enable rewriting of Parameter sets before every (intra) random access point")
+#else
+  ("ReWriteParamSetsFlag",                            m_bReWriteParamSetsFlag,                           true, "Enable rewriting of Parameter sets before every (intra) random access point")
+#endif
+#endif 
 
   // motion search options
@@ -967,11 +1150,25 @@
   ("LambdaModifier6,-LM6",                            m_adLambdaModifier[ 6 ],                  ( Double )1.0, "Lambda modifier for temporal layer 6. If LambdaModifierI is used, this will not affect intra pictures")
   ("LambdaModifierI,-LMI",                            cfg_adIntraLambdaModifier,    cfg_adIntraLambdaModifier, "Lambda modifiers for Intra pictures, comma separated, up to one the number of temporal layer. If entry for temporalLayer exists, then use it, else if some are specified, use the last, else use the standard LambdaModifiers.")
-  ("IQPFactor,-IQF",                                  m_dIntraQpFactor,                                  -1.0, "Intra QP Factor for Lambda Computation. If negative, use the default equation: 0.57*(1.0 - Clip3( 0.0, 0.5, 0.05*(Double)(isField ? (GopSize-1)/2 : GopSize-1) ))")
+  ("IQPFactor,-IQF",                                  m_dIntraQpFactor,                                  -1.0, "Intra QP Factor for Lambda Computation. If negative, the default will scale lambda based on GOP size (unless LambdaFromQpEnable then IntraQPOffset is used instead)")
 
   /* Quantization parameters */
 #if NH_MV
+#if JVET_E0059_FLOATING_POINT_QP_FIX
+  ("QP,q",                                            m_iQP,                                               std::vector<Int>(1,30)  , "Qp value")
+  ("QPIncrementFrame,-qpif",                          m_qpIncrementAtSourceFrame,                          std::vector<Int>( 0 ), "If a source file frame number is specified, the internal QP will be incremented for all POCs associated with source frames >= frame number. If empty, do not increment.")
+#else
   ("QP,q",          m_fQP, std::vector<double>(1,30.0), "Qp values for each layer, if value is float, QP is switched once during encoding")
+#endif
+#else
+#if JVET_E0059_FLOATING_POINT_QP_FIX
+  ("QP,q",                                            m_iQP,                                               30, "Qp value")
+  ("QPIncrementFrame,-qpif",                          m_qpIncrementAtSourceFrame,       OptionalValue<UInt>(), "If a source file frame number is specified, the internal QP will be incremented for all POCs associated with source frames >= frame number. If empty, do not increment.")
 #else
   ("QP,q",                                            m_fQP,                                             30.0, "Qp value, if value is float, QP is switched once during encoding")
+#endif
+#endif
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+  ("IntraQPOffset",                                   m_intraQPOffset,                                      0, "Qp offset value for intra slice, typically determined based on GOP size")
+  ("LambdaFromQpEnable",                              m_lambdaFromQPEnable,                             false, "Enable flag for derivation of lambda from QP")
 #endif
   ("DeltaQpRD,-dqr",                                  m_uiDeltaQpRD,                                       0u, "max dQp offset for slice")
@@ -981,12 +1178,18 @@
   ("FastDeltaQP",                                     m_bFastDeltaQP,                                   false, "Fast Delta QP Algorithm")
 
+  ("LumaLevelToDeltaQPMode",                          lumaLevelToDeltaQPMode,                              0u, "Luma based Delta QP 0(default): not used. 1: Based on CTU average, 2: Based on Max luma in CTU")
+  ("LumaLevelToDeltaQPMaxValWeight",                  m_lumaLevelToDeltaQPMapping.maxMethodWeight,        1.0, "Weight of block max luma val when LumaLevelToDeltaQPMode = 2")
+  ("LumaLevelToDeltaQPMappingLuma",                   cfg_lumaLeveltoDQPMappingLuma,  cfg_lumaLeveltoDQPMappingLuma, "Luma to Delta QP Mapping - luma thresholds")
+  ("LumaLevelToDeltaQPMappingDQP",                    cfg_lumaLeveltoDQPMappingQP,  cfg_lumaLeveltoDQPMappingQP, "Luma to Delta QP Mapping - DQP values")
   ("CbQpOffset,-cbqpofs",                             m_cbQpOffset,                                         0, "Chroma Cb QP Offset")
   ("CrQpOffset,-crqpofs",                             m_crQpOffset,                                         0, "Chroma Cr QP Offset")
-
-#if W0038_CQP_ADJ
-  ("SliceChromaQPOffsetPeriodicity",                  m_sliceChromaQpOffsetPeriodicity,                    0u, "Used in conjunction with Slice Cb/Cr QpOffsetIntraOrPeriodic. Use 0 (default) to disable periodic nature.")
+  ("WCGPPSEnable",                                    m_wcgChromaQpControl.enabled,                     false, "1: Enable the WCG PPS chroma modulation scheme. 0 (default) disabled")
+  ("WCGPPSCbQpScale",                                 m_wcgChromaQpControl.chromaCbQpScale,               1.0, "WCG PPS Chroma Cb QP Scale")
+  ("WCGPPSCrQpScale",                                 m_wcgChromaQpControl.chromaCrQpScale,               1.0, "WCG PPS Chroma Cr QP Scale")
+  ("WCGPPSChromaQpScale",                             m_wcgChromaQpControl.chromaQpScale,                 0.0, "WCG PPS Chroma QP Scale")
+  ("WCGPPSChromaQpOffset",                            m_wcgChromaQpControl.chromaQpOffset,                0.0, "WCG PPS Chroma QP Offset")
+("SliceChromaQPOffsetPeriodicity",                  m_sliceChromaQpOffsetPeriodicity,                    0u, "Used in conjunction with Slice Cb/Cr QpOffsetIntraOrPeriodic. Use 0 (default) to disable periodic nature.")
   ("SliceCbQpOffsetIntraOrPeriodic",                  m_sliceChromaQpOffsetIntraOrPeriodic[0],              0, "Chroma Cb QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.")
   ("SliceCrQpOffsetIntraOrPeriodic",                  m_sliceChromaQpOffsetIntraOrPeriodic[1],              0, "Chroma Cr QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.")
-#endif
 #if ADAPTIVE_QP_SELECTION
   ("AdaptiveQpSelection,-aqps",                       m_bUseAdaptQpSelect,                              false, "AdaptiveQpSelection")
@@ -998,7 +1201,5 @@
   ("RDOQ",                                            m_useRDOQ,                                         true)
   ("RDOQTS",                                          m_useRDOQTS,                                       true)
-#if T0196_SELECTIVE_RDOQ
   ("SelectiveRDOQ",                                   m_useSelectiveRDOQ,                               false, "Enable selective RDOQ")
-#endif
   ("RDpenalty",                                       m_rdPenalty,                                          0,  "RD-penalty for 32x32 TU for intra in non-intra slices. 0:disabled  1:RD-penalty  2:maximum RD-penalty")
 
@@ -1012,9 +1213,5 @@
   ("LoopFilterBetaOffset_div2",                       m_loopFilterBetaOffsetDiv2,                           0)
   ("LoopFilterTcOffset_div2",                         m_loopFilterTcOffsetDiv2,                             0)
-#if W0038_DB_OPT
   ("DeblockingFilterMetric",                          m_deblockingFilterMetric,                             0)
-#else
-  ("DeblockingFilterMetric",                          m_DeblockingFilterMetric,                         false)
-#endif
   // Coding tools
   ("AMP",                                             m_enableAMP,                                       true, "Enable asymmetric motion partitions")
@@ -1042,7 +1239,5 @@
   ("MaxNumOffsetsPerPic",                             m_maxNumOffsetsPerPic,                             2048, "Max number of SAO offset per picture (Default: 2048)")
   ("SAOLcuBoundary",                                  m_saoCtuBoundary,                                 false, "0: right/bottom CTU boundary areas skipped from SAO parameter estimation, 1: non-deblocked pixels are used for those areas")
-#if OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP
   ("SAOResetEncoderStateAfterIRAP",                   m_saoResetEncoderStateAfterIRAP,                  false, "When true, resets the encoder's SAO state after an IRAP (POC order). Disabled by default.")
-#endif
   ("SliceMode",                                       tmpSliceMode,                            Int(NO_SLICES), "0: Disable all Recon slice limits, 1: Enforce max # of CTUs, 2: Enforce max # of bytes, 3:specify tiles per dependent slice")
   ("SliceArgument",                                   m_sliceArgument,                                      0, "Depending on SliceMode being:"
@@ -1086,5 +1281,5 @@
   ("ScalingList",                                     m_useScalingListId,                    SCALING_LIST_OFF, "0/off: no scaling list, 1/default: default scaling lists, 2/file: scaling lists specified in ScalingListFile")
   ("ScalingListFile",                                 m_scalingListFileName,                       string(""), "Scaling list file name. Use an empty string to produce help.")
-  ("SignHideFlag,-SBH",                               m_signHideFlag,                                    true)
+  ("SignHideFlag,-SBH",                               m_signDataHidingEnabledFlag,                                    true)
   ("MaxNumMergeCand",                                 m_maxNumMergeCand,                                   5u, "Maximum number of merge candidates")
   /* Misc. */
@@ -1107,11 +1302,7 @@
   ( "InitialQP",                                      m_RCInitialQP,                                        0, "Rate control: initial QP" )
   ( "RCForceIntraQP",                                 m_RCForceIntraQP,                                 false, "Rate control: force intra QP to be equal to initial QP" )
-
-#if U0132_TARGET_BITS_SATURATION
   ( "RCCpbSaturation",                                m_RCCpbSaturationEnabled,                         false, "Rate control: enable target bits saturation to avoid CPB overflow and underflow" )
   ( "RCCpbSize",                                      m_RCCpbSize,                                         0u, "Rate control: CPB size" )
   ( "RCInitialCpbFullness",                           m_RCInitialCpbFullness,                             0.9, "Rate control: initial CPB fullness" )
-#endif
-
 #if KWU_RC_VIEWRC_E0227
   ("ViewWiseTargetBits, -vtbr" ,  m_viewTargetBits,  std::vector<Int>(1, 32), "View-wise target bit-rate setting")
@@ -1150,6 +1341,7 @@
 #endif
 
-  ("TransquantBypassEnableFlag",                      m_TransquantBypassEnableFlag,                     false, "transquant_bypass_enable_flag indicator in PPS")
-  ("CUTransquantBypassFlagForce",                     m_CUTransquantBypassFlagForce,                    false, "Force transquant bypass mode, when transquant_bypass_enable_flag is enabled")
+  ("TransquantBypassEnable",                          m_TransquantBypassEnabledFlag,                    false, "transquant_bypass_enabled_flag indicator in PPS")
+  ("TransquantBypassEnableFlag",                      m_TransquantBypassEnabledFlag,                    false, "deprecated alias for TransquantBypassEnable")
+  ("CUTransquantBypassFlagForce",                     m_CUTransquantBypassFlagForce,                    false, "Force transquant bypass mode, when transquant_bypass_enabled_flag is enabled")
   ("CostMode",                                        m_costMode,                         COST_STANDARD_LOSSY, "Use alternative cost functions: choose between 'lossy', 'sequence_level_lossless', 'lossless' (which forces QP to " MACRO_TO_STRING(LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP) ") and 'mixed_lossless_lossy' (which used QP'=" MACRO_TO_STRING(LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP_PRIME) " for pre-estimates of transquant-bypass blocks).")
   ("RecalculateQPAccordingToLambda",                  m_recalculateQPAccordingToLambda,                 false, "Recalculate QP values according to lambda values. Do not suggest to be enabled in all intra case")
@@ -1263,4 +1455,7 @@
   ("SEIScalableNesting",                              m_scalableNestingSEIEnabled,                      false, "Control generation of scalable nesting SEI messages")
   ("SEITempMotionConstrainedTileSets",                m_tmctsSEIEnabled,                                false, "Control generation of temporal motion constrained tile sets SEI message")
+#if MCTS_ENC_CHECK
+  ("SEITMCTSTileConstraint",                          m_tmctsSEITileConstraint,                         false, "Constrain motion vectors at tile boundaries")
+#endif
   ("SEITimeCodeEnabled",                              m_timeCodeSEIEnabled,                             false, "Control generation of time code information SEI message")
   ("SEITimeCodeNumClockTs",                           m_timeCodeSEINumTs,                                   0, "Number of clock time sets [0..3]")
@@ -1296,7 +1491,8 @@
   ("SEIMasteringDisplayPrimaries",                    cfg_DisplayPrimariesCode,       cfg_DisplayPrimariesCode, "Mastering display primaries for all three colour planes in CIE xy coordinates in increments of 1/50000 (results in the ranges 0 to 50000 inclusive)")
   ("SEIMasteringDisplayWhitePoint",                   cfg_DisplayWhitePointCode,     cfg_DisplayWhitePointCode, "Mastering display white point CIE xy coordinates in normalised increments of 1/50000 (e.g. 0.333 = 16667)")
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
   ("SEIPreferredTransferCharacterisics",              m_preferredTransferCharacteristics,                   -1, "Value for the preferred_transfer_characteristics field of the Alternative transfer characteristics SEI which will override the corresponding entry in the VUI. If negative, do not produce the respective SEI message")
-#endif
+  ("SEIGreenMetadataType",                            m_greenMetadataType,                   0u, "Value for the green_metadata_type specifies the type of metadata that is present in the SEI message. If green_metadata_type is 1, then metadata enabling quality recovery after low-power encoding is present")
+  ("SEIXSDMetricType",                                m_xsdMetricType,                      0u, "Value for the xsd_metric_type indicates the type of the objective quality metric. PSNR is the only type currently supported")
+
 #if NH_MV
   ("SeiCfgFileName_%d",                               m_seiCfgFileNames,             (TChar *) 0 ,MAX_NUM_SEIS , "SEI cfg file name %d")
@@ -1331,9 +1527,8 @@
   ("DWeight",                                         m_iDWeight                , 1                             ,"Depth Distortion weight" )
 #endif //HHI_VSO
+
+#if NH_3D
 /* 3D- HEVC Tools */                                                            
-#if NH_3D_QTL
   ("QTL"                   ,                          m_bUseQTL                 , true                          , "Use depth quad tree limitation (encoder only)" )
-#endif
-#if NH_3D
 
   ("IvMvPredFlag"          ,                          m_ivMvPredFlag            , BoolAry1d(2,true)             , "Inter-view motion prediction"              )
@@ -1355,10 +1550,14 @@
   ("IlluCompEnable"        ,                          m_abUseIC                 , true                          , "Enable illumination compensation"          )
   ("IlluCompLowLatencyEnc" ,                          m_bUseLowLatencyICEnc     , false                         , "Enable low-latency illumination compensation encoding")
-#endif //NH_3D
-    
+#endif //NH_3D    
   ;
 
-#if NH_MV
-  // parse coding structure
+#if EXTENSION_360_VIDEO
+  TExt360AppEncCfg::TExt360AppEncCfgContext ext360CfgContext;
+  m_ext360.addOptions(opts, ext360CfgContext);
+#endif
+
+
+#if NH_MV
   for( Int k = 0; k < MAX_NUM_LAYERS; k++ )
   {
@@ -1414,4 +1613,5 @@
   const list<const TChar*>& argv_unhandled = po::scanArgv(opts, argc, (const TChar**) argv, err);
 
+
   for (list<const TChar*>::const_iterator it = argv_unhandled.begin(); it != argv_unhandled.end(); it++)
   {
@@ -1435,16 +1635,67 @@
   }
 
+#if NH_MV
+  if ( m_layerIdxInVpsToRepFormatIdx.size() == 0 )
+  {
+    m_layerIdxInVpsToRepFormatIdx.push_back( 0 ); 
+#if NH_3D
+    m_layerIdxInVpsToRepFormatIdx.push_back( 1 ); 
+#endif
+  }
+
+  xResizeVector( m_layerIdxInVpsToRepFormatIdx );
+
+  // parse coding structure
+  if ( m_layerIdxInVpsToGopDefIdx.size() == 0 )
+  {
+    for( Int k = 0; k < m_numberOfLayers; k++ )
+    {
+      m_layerIdxInVpsToGopDefIdx.push_back( k );
+    }
+  }
+
+  xConvertRepFormatParameters(
+    tmpPad                       ,             
+    tmpInputBitDepth             ,
+    tmpOutputBitDepth            ,
+    tmpMSBExtendedBitDepth       ,
+    tmpInternalBitDepth          ,
+    tmpInputChromaFormat         ,
+    tmpChromaFormat
+    );
+#endif
   /*
    * Set any derived parameters
    */
+#if NH_MV
+  m_inputFileWidths  = m_iSourceWidths;
+  m_inputFileHeights = m_iSourceHeights;
+#else
+  m_inputFileWidth  = m_iSourceWidth;
+  m_inputFileHeight = m_iSourceHeight;
+#endif
 
   m_framesToBeEncoded = ( m_framesToBeEncoded + m_temporalSubsampleRatio - 1 ) / m_temporalSubsampleRatio;
   m_adIntraLambdaModifier = cfg_adIntraLambdaModifier.values;
+
+#if NH_MV
+  m_iSourceHeightOrgs = m_iSourceHeights;
+#endif
   if(m_isField)
   {
+#if NH_MV
+    //Frame height
+    m_iSourceHeightOrgs = m_iSourceHeights;
+    //Field height
+    for (Int i = 0; i < m_iSourceHeights.size(); i++ )
+    {
+      m_iSourceHeights[i] = m_iSourceHeights[i] >> 1;
+    }
+#else
     //Frame height
     m_iSourceHeightOrg = m_iSourceHeight;
     //Field height
     m_iSourceHeight = m_iSourceHeight >> 1;
+#endif
     //number of fields to encode
     m_framesToBeEncoded *= 2;
@@ -1503,4 +1754,12 @@
   }
 
+#if NH_MV
+  for (Int i = 0; i < m_numRepFormats; i++ )
+  {
+    Int* m_MSBExtendedBitDepth   = &m_MSBExtendedBitDepths[i][0];
+    Int* m_internalBitDepth      = &m_internalBitDepths   [i][0];
+    Int* m_outputBitDepth        = &m_outputBitDepths     [i][0];
+    Int* m_inputBitDepth         = &m_inputBitDepths      [i][0];
+#endif
   /* rules for input, output and internal bitdepths as per help text */
   if (m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ] == 0)
@@ -1533,7 +1792,24 @@
   }
 
+  
+#if NH_MV
+  }
   m_InputChromaFormatIDC = numberToChromaFormat(tmpInputChromaFormat);
+#endif
+
+
+#if NH_MV
+  std::vector<ChromaFormat> tempChromaFormatIdc = numberToChromaFormat(tmpChromaFormat);
+  for(Int i = 0 ; i < m_InputChromaFormatIDC.size(); i++)
+  {
+    m_chromaFormatIDCs.push_back( ((tmpChromaFormat[i] == 0) ? (m_InputChromaFormatIDC[i]) : tempChromaFormatIdc[i] ) );
+  }
+#else
   m_chromaFormatIDC      = ((tmpChromaFormat == 0) ? (m_InputChromaFormatIDC) : (numberToChromaFormat(tmpChromaFormat)));
-
+#endif
+
+#if EXTENSION_360_VIDEO
+  m_ext360.processOptions(ext360CfgContext);
+#endif
 
   assert(tmpWeightedPredictionMethod>=0 && tmpWeightedPredictionMethod<=WP_PER_PICTURE_WITH_HISTOGRAM_AND_PER_COMPONENT_AND_CLIPPING_AND_EXTENSION);
@@ -1558,6 +1834,6 @@
   m_motionEstimationSearchMethod=MESearchMethod(tmpMotionEstimationSearchMethod);
 
-#if NH_MV
-  // parse PTL
+#if NH_MV 
+
   Bool anyEmpty = false; 
   if( cfg_profiles.empty() )
@@ -1602,117 +1878,185 @@
   }
 
-  xReadStrToEnum( cfg_profiles, extendedProfiles  ); 
+  xReadStrToEnum( cfg_profiles, m_uiProfiles  ); 
   xReadStrToEnum( cfg_levels,   m_level     ); 
   xReadStrToEnum( cfg_tiers ,   m_levelTier ); 
-
-
-#if NH_MV
-  m_profiles.resize( extendedProfiles.size()); 
-
-  for (Int i = 0; i < m_profiles.size(); i++)
-  {
-    Profile::Name& m_profile             = m_profiles      [i];  
-    ExtendedProfileName& extendedProfile = extendedProfiles[i];  
-#endif
-#endif
-
-  if (extendedProfile >= 1000 && extendedProfile <= 12316)
-    {
+   
+#else
+    switch (UIProfile)
+    {
+    case UI_NONE:
+      m_profile = Profile::NONE;
+      m_onePictureOnlyConstraintFlag = false;
+      break;
+    case UI_MAIN:
+      m_profile = Profile::MAIN;
+      m_onePictureOnlyConstraintFlag = false;
+      break;
+    case UI_MAIN10:
+      m_profile = Profile::MAIN10;
+      m_onePictureOnlyConstraintFlag = false;
+      break;
+    case UI_MAINSTILLPICTURE:
+      m_profile = Profile::MAINSTILLPICTURE;
+      m_onePictureOnlyConstraintFlag = false;
+      break;
+    case UI_MAIN10_STILL_PICTURE:
+      m_profile = Profile::MAIN10;
+      m_onePictureOnlyConstraintFlag = true;
+      break;
+    case UI_MAINREXT:
       m_profile = Profile::MAINREXT;
-      if (m_bitDepthConstraint != 0 || tmpConstraintChromaFormat != 0)
-      {
-        fprintf(stderr, "Error: The bit depth and chroma format constraints are not used when an explicit RExt profile is specified\n");
-        exit(EXIT_FAILURE);
-      }
-      m_bitDepthConstraint     = (extendedProfile%100);
-    m_intraConstraintFlag          = ((extendedProfile%10000)>=2000);
-    m_onePictureOnlyConstraintFlag = (extendedProfile >= 10000);
-      switch ((extendedProfile/100)%10)
-      {
-      case 0:  tmpConstraintChromaFormat=400; break;
-      case 1:  tmpConstraintChromaFormat=420; break;
-      case 2:  tmpConstraintChromaFormat=422; break;
-      default: tmpConstraintChromaFormat=444; break;
-      }
-    }
-    else
-    {
-      m_profile = Profile::Name(extendedProfile);
-    }
-
-    if (m_profile == Profile::HIGHTHROUGHPUTREXT )
-    {
-      if (m_bitDepthConstraint == 0)
-      {
-        m_bitDepthConstraint = 16;
-      }
-      m_chromaFormatConstraint = (tmpConstraintChromaFormat == 0) ? CHROMA_444 : numberToChromaFormat(tmpConstraintChromaFormat);
-    }
-    else if (m_profile == Profile::MAINREXT)
-    {
-      if (m_bitDepthConstraint == 0 && tmpConstraintChromaFormat == 0)
-      {
-        // produce a valid combination, if possible.
-      const Bool bUsingGeneralRExtTools  = m_transformSkipRotationEnabledFlag        ||
-                                           m_transformSkipContextEnabledFlag         ||
-                                           m_rdpcmEnabledFlag[RDPCM_SIGNAL_IMPLICIT] ||
-                                           m_rdpcmEnabledFlag[RDPCM_SIGNAL_EXPLICIT] ||
-          !m_enableIntraReferenceSmoothing         ||
-                                           m_persistentRiceAdaptationEnabledFlag     ||
-                                           m_log2MaxTransformSkipBlockSize!=2;
-      const Bool bUsingChromaQPAdjustment= m_diffCuChromaQpOffsetDepth >= 0;
-      const Bool bUsingExtendedPrecision = m_extendedPrecisionProcessingFlag;
-      if (m_onePictureOnlyConstraintFlag)
-      {
-        m_chromaFormatConstraint = CHROMA_444;
-        if (m_intraConstraintFlag != true)
+      m_onePictureOnlyConstraintFlag = false;
+      break;
+    case UI_HIGHTHROUGHPUTREXT:
+      m_profile = Profile::HIGHTHROUGHPUTREXT;
+      m_onePictureOnlyConstraintFlag = false;
+      break;
+    default:
+      if (UIProfile >= 1000 && UIProfile <= 12316)
+      {
+        m_profile = Profile::MAINREXT;
+        if (m_bitDepthConstraint != 0 || tmpConstraintChromaFormat != 0)
         {
-          fprintf(stderr, "Error: Intra constraint flag must be true when one_picture_only_constraint_flag is true\n");
+          fprintf(stderr, "Error: The bit depth and chroma format constraints are not used when an explicit RExt profile is specified\n");
           exit(EXIT_FAILURE);
         }
-        const Int maxBitDepth = m_chromaFormatIDC==CHROMA_400 ? m_internalBitDepth[CHANNEL_TYPE_LUMA] : std::max(m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA]);
-        m_bitDepthConstraint = maxBitDepth>8 ? 16:8;
+        m_bitDepthConstraint           = (UIProfile%100);
+        m_intraConstraintFlag          = ((UIProfile%10000)>=2000);
+        m_onePictureOnlyConstraintFlag = (UIProfile >= 10000);
+        switch ((UIProfile/100)%10)
+        {
+        case 0:  tmpConstraintChromaFormat=400; break;
+        case 1:  tmpConstraintChromaFormat=420; break;
+        case 2:  tmpConstraintChromaFormat=422; break;
+        default: tmpConstraintChromaFormat=444; break;
+        }
+      }
+      else if (UIProfile >= 21308 && UIProfile <= 22316)
+      {
+        m_profile = Profile::HIGHTHROUGHPUTREXT;
+        if (m_bitDepthConstraint != 0 || tmpConstraintChromaFormat != 0)
+        {
+          fprintf(stderr, "Error: The bit depth and chroma format constraints are not used when an explicit RExt profile is specified\n");
+          exit(EXIT_FAILURE);
+        }
+        m_bitDepthConstraint           = (UIProfile%100);
+        m_intraConstraintFlag          = ((UIProfile%10000)>=2000);
+        m_onePictureOnlyConstraintFlag = 0;
+        if((UIProfile == UI_HIGHTHROUGHPUT_444) || (UIProfile == UI_HIGHTHROUGHPUT_444_10) )
+        {
+          assert(m_cabacBypassAlignmentEnabledFlag==0);
+        }
+        switch ((UIProfile/100)%10)
+        {
+        case 0:  tmpConstraintChromaFormat=400; break;
+        case 1:  tmpConstraintChromaFormat=420; break;
+        case 2:  tmpConstraintChromaFormat=422; break;
+        default: tmpConstraintChromaFormat=444; break;
+        }
       }
       else
       {
-        m_chromaFormatConstraint = NUM_CHROMA_FORMAT;
-        automaticallySelectRExtProfile(bUsingGeneralRExtTools,
-          bUsingChromaQPAdjustment,
-          bUsingExtendedPrecision,
-          m_intraConstraintFlag,
-          m_bitDepthConstraint,
-          m_chromaFormatConstraint,
-          m_chromaFormatIDC==CHROMA_400 ? m_internalBitDepth[CHANNEL_TYPE_LUMA] : std::max(m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA]),
-          m_chromaFormatIDC);
-      }
-    }
-      else if (m_bitDepthConstraint == 0 || tmpConstraintChromaFormat == 0)
-      {
-        fprintf(stderr, "Error: The bit depth and chroma format constraints must either both be specified or both be configured automatically\n");
+        fprintf(stderr, "Error: Unprocessed UI profile\n");
+        assert(0);
         exit(EXIT_FAILURE);
       }
-      else
-      {
-        m_chromaFormatConstraint = numberToChromaFormat(tmpConstraintChromaFormat);
-      }
-    }
-    else
-    {
+      break;
+    }
+
+    switch (m_profile)
+    {
+    case Profile::HIGHTHROUGHPUTREXT:
+      {
+        if (m_bitDepthConstraint == 0)
+        {
+          m_bitDepthConstraint = 16;
+        }
+        m_chromaFormatConstraint = (tmpConstraintChromaFormat == 0) ? CHROMA_444 : numberToChromaFormat(tmpConstraintChromaFormat);
+      }
+      break;
+    case Profile::MAINREXT:
+
+      {
+        if (m_bitDepthConstraint == 0 && tmpConstraintChromaFormat == 0)
+        {
+          // produce a valid combination, if possible.
+          const Bool bUsingGeneralRExtTools  = m_transformSkipRotationEnabledFlag        ||
+            m_transformSkipContextEnabledFlag         ||
+            m_rdpcmEnabledFlag[RDPCM_SIGNAL_IMPLICIT] ||
+            m_rdpcmEnabledFlag[RDPCM_SIGNAL_EXPLICIT] ||
+            !m_enableIntraReferenceSmoothing         ||
+            m_persistentRiceAdaptationEnabledFlag     ||
+            m_log2MaxTransformSkipBlockSize!=2;
+          const Bool bUsingChromaQPAdjustment= m_diffCuChromaQpOffsetDepth >= 0;
+          const Bool bUsingExtendedPrecision = m_extendedPrecisionProcessingFlag;
+          if (m_onePictureOnlyConstraintFlag)
+          {
+            m_chromaFormatConstraint = CHROMA_444;
+            if (m_intraConstraintFlag != true)
+            {
+              fprintf(stderr, "Error: Intra constraint flag must be true when one_picture_only_constraint_flag is true\n");
+              exit(EXIT_FAILURE);
+            }
+            const Int maxBitDepth = m_chromaFormatIDC==CHROMA_400 ? m_internalBitDepth[CHANNEL_TYPE_LUMA] : std::max(m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA]);
+            m_bitDepthConstraint = maxBitDepth>8 ? 16:8;
+          }
+          else
+          {
+            m_chromaFormatConstraint = NUM_CHROMA_FORMAT;
+            automaticallySelectRExtProfile(bUsingGeneralRExtTools,
+              bUsingChromaQPAdjustment,
+              bUsingExtendedPrecision,
+              m_intraConstraintFlag,
+              m_bitDepthConstraint,
+              m_chromaFormatConstraint,
+              m_chromaFormatIDC==CHROMA_400 ? m_internalBitDepth[CHANNEL_TYPE_LUMA] : std::max(m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA]),
+              m_chromaFormatIDC);
+          }
+        }
+        else if (m_bitDepthConstraint == 0 || tmpConstraintChromaFormat == 0)
+        {
+          fprintf(stderr, "Error: The bit depth and chroma format constraints must either both be specified or both be configured automatically\n");
+          exit(EXIT_FAILURE);
+        }
+        else
+        {
+          m_chromaFormatConstraint = numberToChromaFormat(tmpConstraintChromaFormat);
+        }
+      }
+      break;
+    case Profile::MAIN:
+    case Profile::MAIN10:
+    case Profile::MAINSTILLPICTURE:
       m_chromaFormatConstraint = (tmpConstraintChromaFormat == 0) ? m_chromaFormatIDC : numberToChromaFormat(tmpConstraintChromaFormat);
       m_bitDepthConstraint = (m_profile == Profile::MAIN10?10:8);
-    }
-#if NH_MV
-  }
-
-  if ( m_numberOfLayers != 0 && ( m_profiles[0] != Profile::MAIN || m_profiles[1] != Profile::MAIN )  )
-  {
-    fprintf(stderr, "Error: The base layer must conform to the Main profile for Multilayer coding.\n");
-    exit(EXIT_FAILURE);
-  }
-#endif
-
+      break;
+    case Profile::NONE:
+      m_chromaFormatConstraint = m_chromaFormatIDC;
+      m_bitDepthConstraint = m_chromaFormatIDC==CHROMA_400 ? m_internalBitDepth[CHANNEL_TYPE_LUMA] : std::max(m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA]);
+      break;
+    default:
+      fprintf(stderr, "Unknown profile selected\n");
+      exit(EXIT_FAILURE);
+      break;
+    }
+#endif
 
   m_inputColourSpaceConvert = stringToInputColourSpaceConvert(inputColourSpaceConvert, true);
 
+
+#if NH_MV
+  for (Int i = 0; i < m_numRepFormats; i++ )
+  {
+    Int*          m_aiPad            = &m_aiPads[i][0];
+    ChromaFormat &m_chromaFormatIDC  = m_chromaFormatIDCs [i];
+    Int          &m_confWinRight     = m_confWinRights    [i];
+    Int          &m_confWinBottom    = m_confWinBottoms   [i];
+    Int          &m_confWinLeft      = m_confWinLefts     [i];
+    Int          &m_confWinTop       = m_confWinTops      [i];
+    Int          &m_iSourceHeight    = m_iSourceHeights   [i];
+    Int          &m_iSourceWidth     = m_iSourceWidths    [i];
+    Int          &m_iSourceHeightOrg = m_iSourceHeightOrgs[i];
+#endif
   switch (m_conformanceWindowMode)
   {
@@ -1779,4 +2123,7 @@
     }
   }
+#if NH_MV
+  }
+#endif
 
   if (tmpSliceMode<0 || tmpSliceMode>=Int(NUMBER_OF_SLICE_CONSTRAINT_MODES))
@@ -1837,5 +2184,14 @@
   xResizeVector( m_depthFlag ); 
 #endif
+
+#if JVET_E0059_FLOATING_POINT_QP_FIX  
+  if ( !m_qpIncrementAtSourceFrame.empty() )
+  {
+    xResizeVector( m_qpIncrementAtSourceFrame );
+  }
+  xResizeVector( m_iQP ); 
+#else
   xResizeVector( m_fQP ); 
+#endif
 
   for( Int layer = 0; layer < m_numberOfLayers; layer++ )
@@ -1844,4 +2200,21 @@
     ::memset( m_aidQP[layer], 0, sizeof(Int)*( m_framesToBeEncoded + m_iGOPSize + 1 ) );
 
+#if JVET_E0059_FLOATING_POINT_QP_FIX
+    if ( !m_qpIncrementAtSourceFrame.empty() )
+    {
+      UInt switchingPOC=0;
+      if (m_qpIncrementAtSourceFrame[layer] > m_FrameSkip)
+      {
+        // if switch source frame (ssf) = 10, and frame skip (fs)=2 and temporal subsample ratio (tsr) =1, then
+        //    for this simulation switch at POC 8 (=10-2).
+        // if ssf=10, fs=2, tsr=2, then for this simulation, switch at POC 4 (=(10-2)/2): POC0=Src2, POC1=Src4, POC2=Src6, POC3=Src8, POC4=Src10
+        switchingPOC = (m_qpIncrementAtSourceFrame[layer] - m_FrameSkip) / m_temporalSubsampleRatio;
+      }
+      for(UInt i=switchingPOC; i<( m_framesToBeEncoded + m_iGOPSize + 1 ); i++)
+      {
+        m_aidQP[layer][i]=1;
+      }
+    }
+#else
     // handling of floating-point QP values
     // if QP is not integer, sequence is split into two sections having QP and QP+1
@@ -1857,4 +2230,5 @@
       }
     }
+#endif
 
     for(UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
@@ -1862,7 +2236,12 @@
       if (saoOffsetBitShift[ch]<0)
       {
+#if NH_MV
+        Int repFormatIdx = m_layerIdxInVpsToRepFormatIdx[ layer ];
+        if (m_internalBitDepths[repFormatIdx][ch]>10)
+#else
         if (m_internalBitDepth[ch]>10)
+#endif
         {
-          m_log2SaoOffsetScale[layer][ch]=UInt(Clip3<Int>(0, m_internalBitDepth[ch]-10, Int(m_internalBitDepth[ch]-10 + 0.165*m_iQP[layer] - 3.22 + 0.5) ) );
+          m_log2SaoOffsetScale[layer][ch]=UInt(Clip3<Int>(0, m_internalBitDepths[repFormatIdx][ch]-10, Int(m_internalBitDepths[repFormatIdx][ch]-10 + 0.165*m_iQP[layer] - 3.22 + 0.5) ) );
         }
         else
@@ -1893,4 +2272,21 @@
   ::memset( m_aidQP, 0, sizeof(Int)*( m_framesToBeEncoded + m_iGOPSize + 1 ) );
 
+#if JVET_E0059_FLOATING_POINT_QP_FIX
+  if (m_qpIncrementAtSourceFrame.bPresent)
+  {
+    UInt switchingPOC=0;
+    if (m_qpIncrementAtSourceFrame.value > m_FrameSkip)
+    {
+      // if switch source frame (ssf) = 10, and frame skip (fs)=2 and temporal subsample ratio (tsr) =1, then
+      //    for this simulation switch at POC 8 (=10-2).
+      // if ssf=10, fs=2, tsr=2, then for this simulation, switch at POC 4 (=(10-2)/2): POC0=Src2, POC1=Src4, POC2=Src6, POC3=Src8, POC4=Src10
+      switchingPOC = (m_qpIncrementAtSourceFrame.value - m_FrameSkip) / m_temporalSubsampleRatio;
+    }
+    for(UInt i=switchingPOC; i<( m_framesToBeEncoded + m_iGOPSize + 1 ); i++)
+    {
+      m_aidQP[i]=1;
+    }
+  }
+#else
   // handling of floating-point QP values
   // if QP is not integer, sequence is split into two sections having QP and QP+1
@@ -1906,4 +2302,5 @@
     }
   }
+#endif
 
   for(UInt ch=0; ch<MAX_NUM_CHANNEL_TYPE; ch++)
@@ -1927,4 +2324,21 @@
 
 #endif
+
+  assert(lumaLevelToDeltaQPMode<LUMALVL_TO_DQP_NUM_MODES);
+  if (lumaLevelToDeltaQPMode>=LUMALVL_TO_DQP_NUM_MODES)
+  {
+    exit(EXIT_FAILURE);
+  }
+  m_lumaLevelToDeltaQPMapping.mode=LumaLevelToDQPMode(lumaLevelToDeltaQPMode);
+
+  if (m_lumaLevelToDeltaQPMapping.mode)
+  {
+    assert(  cfg_lumaLeveltoDQPMappingLuma.values.size() == cfg_lumaLeveltoDQPMappingQP.values.size() );
+    m_lumaLevelToDeltaQPMapping.mapping.resize(cfg_lumaLeveltoDQPMappingLuma.values.size());
+    for(UInt i=0; i<cfg_lumaLeveltoDQPMappingLuma.values.size(); i++)
+    {
+      m_lumaLevelToDeltaQPMapping.mapping[i]=std::pair<Int,Int>(cfg_lumaLeveltoDQPMappingLuma.values[i], cfg_lumaLeveltoDQPMappingQP.values[i]);
+    }
+  }
 
   // reading external dQP description from file
@@ -2070,9 +2484,10 @@
     m_dLambdaScaleVSO *= adLambdaScaleTable[m_iQP[firstDepthLayer]]; 
   }
+
   if ( m_bUseVSO && m_uiVSOMode == 4)
   {
     m_cRenModStrParser.setString( m_iNumberOfViews, m_pchVSOConfig );
     m_cCameraData     .init     ( ((UInt) m_iNumberOfViews ), 
-      m_internalBitDepth[ CHANNEL_TYPE_LUMA],
+      m_internalBitDepths[0][ CHANNEL_TYPE_LUMA],
       (UInt)m_iCodedCamParPrecision,
       m_FrameSkip,
@@ -2087,5 +2502,5 @@
   {
     m_cCameraData     .init     ( ((UInt) m_iNumberOfViews ), 
-      m_internalBitDepth[ CHANNEL_TYPE_LUMA],
+      m_internalBitDepths[0][ CHANNEL_TYPE_LUMA],
       (UInt)m_iCodedCamParPrecision,
       m_FrameSkip,
@@ -2102,5 +2517,5 @@
   {
     m_cCameraData     .init     ( ((UInt) m_iNumberOfViews ), 
-      m_internalBitDepth[ CHANNEL_TYPE_LUMA],
+      m_internalBitDepths[0][ CHANNEL_TYPE_LUMA],
       (UInt) m_iCodedCamParPrecision,
       m_FrameSkip,
@@ -2125,5 +2540,14 @@
   }
 
-  m_uiMaxTotalCUDepth = m_uiMaxCUDepth + uiAddCUDepth + getMaxCUDepthOffset(m_chromaFormatIDC, m_uiQuadtreeTULog2MinSize); // if minimum TU larger than 4x4, allow for additional part indices for 4:2:2 SubTUs.
+
+#if NH_MV
+  for (Int i = 0; i < m_numRepFormats; i++ )
+  {
+    m_uiMaxTotalCUDepth               .push_back( m_uiMaxCUDepth + uiAddCUDepth + getMaxCUDepthOffset(m_chromaFormatIDCs[i], m_uiQuadtreeTULog2MinSize) ); // if minimum TU larger than 4x4, allow for additional part indices for 4:2:2 SubTUs.    
+  }
+#else
+  m_uiMaxTotalCUDepth = m_uiMaxCUDepth + uiAddCUDepth + getMaxCUDepthOffset(m_chromaFormatIDC, m_uiQuadtreeTULog2MinSize); // if minimum TU larger than 4x4, allow for additional part indices for 4:2:2 SubTUs.  
+#endif
+
   m_uiLog2DiffMaxMinCodingBlockSize = m_uiMaxCUDepth - 1;
 
@@ -2134,8 +2558,439 @@
 }
 
+#if NH_MV
+Void TAppEncCfg::xDeriveProfAndConstrFlags( const TComVPS& vps )
+{
+
+  UInt numPtl = (Int) m_uiProfiles.size();
+  m_profiles.resize( numPtl );
+  m_chromaFormatConstraints.resize( m_uiProfiles.size() );
+  
+  xResizeVector( m_onePictureOnlyConstraintFlags , numPtl );
+  xResizeVector( m_bitDepthConstraints           , numPtl );
+  xResizeVector( m_frameOnlyConstraintFlags      , numPtl );
+  xResizeVector( m_nonPackedConstraintFlags      , numPtl );
+  xResizeVector( m_intraConstraintFlags          , numPtl );  
+  xResizeVector( m_interlacedSourceFlags         , numPtl );
+  xResizeVector( m_progressiveSourceFlags        , numPtl );
+  xResizeVector( m_lowerBitRateConstraintFlags   , numPtl );
+  xResizeVector( m_tmpConstraintChromaFormats    , numPtl );
+
+  for (Int i = 0; i < m_profiles.size(); i++)
+  { 
+    UIProfileName UIProfile = m_uiProfiles[i];
+
+    ChromaFormat maxChromaFormatIdc       ;
+    Int          maxInternalBitDepthLuma  ;
+    Int          maxInternalBitDepthChroma;
+    Int          maxNumRefLayers          ;
+
+    xGetMaxValuesOfApplicableLayers(vps, i, maxInternalBitDepthLuma,maxInternalBitDepthChroma, maxChromaFormatIdc, maxNumRefLayers );
+
+    switch ( UIProfile )
+    {
+    case UI_MULTIVIEWMAIN:
+      m_profiles[i] = Profile::MULTIVIEWMAIN;
+      m_onePictureOnlyConstraintFlags[i] = false;
+      break;
+#if NH_3D
+    case UI_MAIN3D:
+      m_profiles[i] = Profile::MAIN3D;
+      m_onePictureOnlyConstraintFlags[i] = false;
+      break;
+#endif
+    case UI_NONE:
+      m_profiles[i] = Profile::NONE;
+      m_onePictureOnlyConstraintFlags[i] = false;
+      break;
+    case UI_MAIN:
+      m_profiles[i] = Profile::MAIN;
+      m_onePictureOnlyConstraintFlags[i] = false;
+      break;
+    case UI_MAIN10:
+      m_profiles[i] = Profile::MAIN10;
+      m_onePictureOnlyConstraintFlags[i] = false;
+      break;
+    case UI_MAINSTILLPICTURE:
+      m_profiles[i] = Profile::MAINSTILLPICTURE;
+      m_onePictureOnlyConstraintFlags[i] = false;
+      break;
+    case UI_MAIN10_STILL_PICTURE:
+      m_profiles[i] = Profile::MAIN10;
+      m_onePictureOnlyConstraintFlags[i] = true;
+      break;
+    case UI_MAINREXT:
+      m_profiles[i] = Profile::MAINREXT;
+      m_onePictureOnlyConstraintFlags[i] = false;
+      break;
+    case UI_HIGHTHROUGHPUTREXT:
+      m_profiles[i] = Profile::HIGHTHROUGHPUTREXT;
+      m_onePictureOnlyConstraintFlags[i] = false;
+      break;
+#if NH_MV_ALLOW_NON_CONFORMING
+    case UI_MULTIVIEWMAIN_NONCONF:
+      m_profiles[i] = Profile::MULTIVIEWMAIN_NONCONFORMING;
+      m_onePictureOnlyConstraintFlags[i] = false;
+      break;
+#if NH_3D
+    case UI_MAIN3D_NONCONF:
+      m_profiles[i] = Profile::MAIN3D_NONCONFORMING;
+      m_onePictureOnlyConstraintFlags[i] = false;
+      break;
+#endif
+#endif
+
+    default:
+      if (UIProfile >= 1000 && UIProfile <= 12316)
+      {
+        m_profiles[i] = Profile::MAINREXT;
+        if (m_bitDepthConstraints[i] != 0 || m_tmpConstraintChromaFormats[i] != 0)
+        {
+          fprintf(stderr, "Error: The bit depth and chroma format constraints are not used when an explicit RExt profile is specified\n");
+          exit(EXIT_FAILURE);
+        }
+        m_bitDepthConstraints[i]           = (UIProfile%100);
+        m_intraConstraintFlags[i]          = ((UIProfile%10000)>=2000);
+        m_onePictureOnlyConstraintFlags[i] = (UIProfile >= 10000);
+        switch ((UIProfile/100)%10)
+        {
+        case 0:  m_tmpConstraintChromaFormats[i]=400; break;
+        case 1:  m_tmpConstraintChromaFormats[i]=420; break;
+        case 2:  m_tmpConstraintChromaFormats[i]=422; break;
+        default: m_tmpConstraintChromaFormats[i]=444; break;
+        }
+      }
+      else if (UIProfile >= 21308 && UIProfile <= 22316)
+      {
+        m_profiles[i] = Profile::HIGHTHROUGHPUTREXT;
+        if (m_bitDepthConstraints[i] != 0 || m_tmpConstraintChromaFormats[i] != 0)
+        {
+          fprintf(stderr, "Error: The bit depth and chroma format constraints are not used when an explicit RExt profile is specified\n");
+          exit(EXIT_FAILURE);
+        }
+        m_bitDepthConstraints[i]           = (UIProfile%100);
+        m_intraConstraintFlags[i]          = ((UIProfile%10000)>=2000);
+        m_onePictureOnlyConstraintFlags[i] = 0;
+        if((UIProfile == UI_HIGHTHROUGHPUT_444) || (UIProfile == UI_HIGHTHROUGHPUT_444_10) )
+        {
+          assert(m_cabacBypassAlignmentEnabledFlag==0);
+        }
+        switch ((UIProfile/100)%10)
+        {
+        case 0:  m_tmpConstraintChromaFormats[i]=400; break;
+        case 1:  m_tmpConstraintChromaFormats[i]=420; break;
+        case 2:  m_tmpConstraintChromaFormats[i]=422; break;
+        default: m_tmpConstraintChromaFormats[i]=444; break;
+        }
+      }
+      else
+      {
+        fprintf(stderr, "Error: Unprocessed UI profile\n");
+        assert(0);
+        exit(EXIT_FAILURE);
+      }
+      break;
+    }
+
+    switch (m_profiles[i])
+    {
+    case Profile::HIGHTHROUGHPUTREXT:
+      {
+        if (m_bitDepthConstraints[i] == 0)
+        {
+          m_bitDepthConstraints[i] = 16;
+        }
+        m_chromaFormatConstraints[i] = (m_tmpConstraintChromaFormats[i] == 0) ? CHROMA_444 : numberToChromaFormat(m_tmpConstraintChromaFormats[i]);
+      }
+      break;
+    case Profile::MAINREXT:
+
+      {
+        if (m_bitDepthConstraints[i] == 0 && m_tmpConstraintChromaFormats[i] == 0)
+        {
+          // produce a valid combination, if possible.
+          const Bool bUsingGeneralRExtTools  = m_transformSkipRotationEnabledFlag        ||
+            m_transformSkipContextEnabledFlag         ||
+            m_rdpcmEnabledFlag[RDPCM_SIGNAL_IMPLICIT] ||
+            m_rdpcmEnabledFlag[RDPCM_SIGNAL_EXPLICIT] ||
+            !m_enableIntraReferenceSmoothing         ||
+            m_persistentRiceAdaptationEnabledFlag     ||
+            m_log2MaxTransformSkipBlockSize!=2;
+          const Bool bUsingChromaQPAdjustment= m_diffCuChromaQpOffsetDepth >= 0;
+          const Bool bUsingExtendedPrecision = m_extendedPrecisionProcessingFlag;
+          if (m_onePictureOnlyConstraintFlags[i])
+          {
+            m_chromaFormatConstraints[i] = CHROMA_444;
+            if (m_intraConstraintFlags[i] != true)
+            {
+              fprintf(stderr, "Error: Intra constraint flag must be true when one_picture_only_constraint_flag is true\n");
+              exit(EXIT_FAILURE);
+            }
+            const Int maxBitDepth = maxChromaFormatIdc==CHROMA_400 ? maxInternalBitDepthLuma : std::max( maxInternalBitDepthLuma, maxInternalBitDepthChroma);
+            m_bitDepthConstraints[i] = maxBitDepth>8 ? 16:8;
+          }
+          else
+          {
+            m_chromaFormatConstraints[i] = NUM_CHROMA_FORMAT;
+
+            UInt tempBitDepthConstraint = (UInt) m_bitDepthConstraints[i];
+
+            automaticallySelectRExtProfile(bUsingGeneralRExtTools,
+              bUsingChromaQPAdjustment,
+              bUsingExtendedPrecision,
+              m_intraConstraintFlags[i],
+              tempBitDepthConstraint,
+              m_chromaFormatConstraints[i],
+              maxChromaFormatIdc==CHROMA_400 ? maxInternalBitDepthLuma : std::max(maxInternalBitDepthLuma, maxInternalBitDepthChroma),
+              maxChromaFormatIdc);
+
+            m_bitDepthConstraints[i] = (Int) tempBitDepthConstraint;
+          }
+        }
+        else if (m_bitDepthConstraints[i] == 0 || m_tmpConstraintChromaFormats[i] == 0)
+        {
+          fprintf(stderr, "Error: The bit depth and chroma format constraints must either both be specified or both be configured automatically\n");
+          exit(EXIT_FAILURE);
+        }
+        else
+        {
+          m_chromaFormatConstraints[i] = numberToChromaFormat(m_tmpConstraintChromaFormats[i]);
+        }
+      }
+      break;
+    case Profile::MAIN:
+    case Profile::MAIN10:
+    case Profile::MAINSTILLPICTURE:
+      m_chromaFormatConstraints[i] = (m_tmpConstraintChromaFormats[i] == 0) ? maxChromaFormatIdc : numberToChromaFormat(m_tmpConstraintChromaFormats[i]);
+      m_bitDepthConstraints[i] = (m_profiles[i] == Profile::MAIN10?10:8);
+      break;
+#if NH_MV_ALLOW_NON_CONFORMING
+    case Profile::MULTIVIEWMAIN_NONCONFORMING:
+#if NH_3D
+    case Profile::MAIN3D_NONCONFORMING:
+#endif
+#endif
+    case Profile::NONE:
+
+      m_chromaFormatConstraints[i] = maxChromaFormatIdc;
+      m_bitDepthConstraints[i]     = maxChromaFormatIdc==CHROMA_400 ? maxInternalBitDepthLuma : std::max(maxInternalBitDepthLuma, maxInternalBitDepthChroma);
+      break;
+    case Profile::MULTIVIEWMAIN:
+      m_chromaFormatConstraints[i] = CHROMA_420;
+      m_bitDepthConstraints[i]     = 8;
+      break;
+
+#if NH_3D
+    case Profile::MAIN3D:
+      // Here depth layers could use a different ptl struct. 
+      // For simplicity, depth and texture share currently the same.
+      m_chromaFormatConstraints[i] = CHROMA_420;
+      m_bitDepthConstraints[i]     = 8;
+      break;
+#endif
+    default:
+      fprintf(stderr, "Unknown profile selected\n");
+      exit(EXIT_FAILURE);
+      break;
+    }
+  }
+}
+#endif
 
 // ====================================================================================================================
 // Private member functions
 // ====================================================================================================================
+
+#if NH_MV
+Void TAppEncCfg::xCheckProfiles( const TComVPS& vps )
+{
+  Bool check_failed = false; 
+
+
+#define xConfirmPara(a,b) check_failed |= confirmPara(a,b)
+
+  // TBD: disallow 3D tools when 3D Main profile is not used.
+
+  for (Int i = 0; i < m_profiles.size(); i++ )
+  {
+    ChromaFormat maxChromaFormatIdc; 
+    Int          maxBitDepthLuma   ;
+    Int          maxBitDepthChroma ;
+    Int          maxNumRefLayers   ;
+
+    xGetMaxValuesOfApplicableLayers(vps, i, maxBitDepthLuma, maxBitDepthChroma , maxChromaFormatIdc, maxNumRefLayers );
+
+    const UInt maxBitDepth=(maxChromaFormatIdc==CHROMA_400) ? maxBitDepthLuma : std::max(maxBitDepthLuma, maxBitDepthChroma);
+
+    xConfirmPara(m_bitDepthConstraints    [i] < maxBitDepth       , "The internalBitDepth must not be greater than the bitDepthConstraint value"      );
+    xConfirmPara(m_chromaFormatConstraints[i] < maxChromaFormatIdc, "The chroma format used must not be greater than the chromaFormatConstraint value");
+
+    switch (m_profiles[i] )
+    {
+    case Profile::MAINREXT:
+    case Profile::HIGHTHROUGHPUTREXT:
+
+      {
+        xConfirmPara(m_lowerBitRateConstraintFlags[i] == false  &&  m_intraConstraintFlags[i] == false                        , "The lowerBitRateConstraint flag cannot be false when intraConstraintFlag is false");
+        xConfirmPara(m_cabacBypassAlignmentEnabledFlag          &&              m_profiles[i] != Profile::HIGHTHROUGHPUTREXT  , "AlignCABACBeforeBypass must not be enabled unless the high throughput profile is being used.");
+
+        if (m_profiles[i] == Profile::MAINREXT)
+        {
+          const UInt intraIdx        = m_intraConstraintFlags[i] ? 1:0;
+          const UInt bitDepthIdx     = (m_bitDepthConstraints[i] == 8 ? 0 : (m_bitDepthConstraints[i] ==10 ? 1 : (m_bitDepthConstraints[i] == 12 ? 2 : (m_bitDepthConstraints[i] == 16 ? 3 : 4 ))));
+          const UInt chromaFormatIdx = UInt(m_chromaFormatConstraints[i]);
+          const Bool bValidProfile   = (bitDepthIdx > 3 || chromaFormatIdx>3) ? false : (validRExtProfileNames[intraIdx][bitDepthIdx][chromaFormatIdx] != UI_NONE);
+
+          xConfirmPara(!bValidProfile, "Invalid intra constraint flag, bit depth constraint flag and chroma format constraint flag combination for a RExt profile");
+          const Bool bUsingGeneralRExtTools  = m_transformSkipRotationEnabledFlag   ||
+            m_transformSkipContextEnabledFlag                                       ||
+            m_rdpcmEnabledFlag[RDPCM_SIGNAL_IMPLICIT]                               ||
+            m_rdpcmEnabledFlag[RDPCM_SIGNAL_EXPLICIT]                               ||
+            !m_enableIntraReferenceSmoothing                                        ||
+            m_persistentRiceAdaptationEnabledFlag                                   ||
+            m_log2MaxTransformSkipBlockSize!=2;
+          const Bool bUsingChromaQPTool      = m_diffCuChromaQpOffsetDepth >= 0;
+          const Bool bUsingExtendedPrecision = m_extendedPrecisionProcessingFlag;
+
+          xConfirmPara((m_chromaFormatConstraints[i]==CHROMA_420 || m_chromaFormatConstraints[i]==CHROMA_400) && bUsingChromaQPTool, "CU Chroma QP adjustment cannot be used for 4:0:0 or 4:2:0 RExt profiles");
+          xConfirmPara(m_bitDepthConstraints[i] != 16 && bUsingExtendedPrecision, "Extended precision can only be used in 16-bit RExt profiles");
+          if (!(m_chromaFormatConstraints[i] == CHROMA_400 && m_bitDepthConstraints[i] == 16) && m_chromaFormatConstraints[i]!=CHROMA_444)
+          {
+            xConfirmPara(bUsingGeneralRExtTools, "Combination of tools and profiles are not possible in the specified RExt profile.");
+          }
+          xConfirmPara( m_onePictureOnlyConstraintFlags[i] && m_chromaFormatConstraints[i]!=CHROMA_444, "chroma format constraint must be 4:4:4 when one-picture-only constraint flag is 1");
+          xConfirmPara( m_onePictureOnlyConstraintFlags[i] && m_bitDepthConstraints[i] != 8 && m_bitDepthConstraints[i] != 16, "bit depth constraint must be 8 or 16 when one-picture-only constraint flag is 1");
+          xConfirmPara( m_onePictureOnlyConstraintFlags[i] && m_framesToBeEncoded > 1, "Number of frames to be encoded must be 1 when one-picture-only constraint flag is 1.");
+
+          if (!m_intraConstraintFlags[i] && m_bitDepthConstraints[i]==16 && m_chromaFormatConstraints[i]==CHROMA_444)
+          {
+            fprintf(stderr, "********************************************************************************************************\n");
+            fprintf(stderr, "** WARNING: The RExt constraint flags describe a non standard combination (used for development only) **\n");
+            fprintf(stderr, "********************************************************************************************************\n");
+          }
+        }
+        else
+        {
+          xConfirmPara( m_chromaFormatConstraints[i] != CHROMA_444, "chroma format constraint must be 4:4:4 in the High Throughput 4:4:4 16-bit Intra profile.");
+          const UInt intraIdx      =   m_intraConstraintFlags[i]     ? 1     : 0;
+          const UInt bitDepthIdx   = ( m_bitDepthConstraints[i] == 8 ? 0     : (m_bitDepthConstraints[i] == 10 ? 1 : (m_bitDepthConstraints[i] == 14 ? 2 : (m_bitDepthConstraints[i] == 16 ? 3 : 4 ))));
+          const Bool bValidProfile = ( bitDepthIdx > 3)              ? false : (validRExtHighThroughPutProfileNames[intraIdx][bitDepthIdx] != UI_NONE);
+          xConfirmPara(!bValidProfile, "Invalid intra constraint flag and bit depth constraint flag combination for a RExt high profile throughput profile");
+          if(bitDepthIdx < 2)
+          {
+            xConfirmPara((m_extendedPrecisionProcessingFlag || m_cabacBypassAlignmentEnabledFlag), "Invalid configuration for a RExt high throughput 8 and 10 bit profile");
+          }
+          if(bitDepthIdx == 3)
+          {
+            xConfirmPara(!m_cabacBypassAlignmentEnabledFlag, "Cabac Bypass Alignment flag must be 1 in the High Throughput 4:4:4 16-bit Intra profile");
+          }
+          else if(bitDepthIdx < 3)
+          {
+            xConfirmPara(!m_entropyCodingSyncEnabledFlag, "WPP flag must be 1 in the High Throughput 4:4:4 non 16-bit Intra profile");
+          }
+        }
+      }
+      break;
+    case Profile::MAIN:
+    case Profile::MAIN10:
+    case Profile::MAINSTILLPICTURE:
+    case Profile::MULTIVIEWMAIN:
+#if NH_3D
+    case Profile::MAIN3D:
+#endif
+      {
+        xConfirmPara(m_bitDepthConstraints        [i] != ((m_profiles[i]==Profile::MAIN10)?10:8), "BitDepthConstraint must be 8 for MAIN profile, Multiview main profile, and 3D Main profile and 10 for MAIN10 profile.");
+#if NH_3D
+        if (m_profiles[i] == Profile::MAIN3D )
+        {
+          xConfirmPara(m_chromaFormatConstraints    [i] != CHROMA_420 && m_chromaFormatConstraints    [i] != CHROMA_400   , "ChromaFormatConstraint must be 420 or 400 for the 3D main profile.");
+        }
+        else
+#endif
+        {
+          xConfirmPara(m_chromaFormatConstraints    [i] != CHROMA_420   , "ChromaFormatConstraint must be 420 for non main-RExt profiles.");
+        }
+       
+        xConfirmPara(m_intraConstraintFlags       [i] == true         , "IntraConstraintFlag must be false for non main_RExt profiles.");
+        xConfirmPara(m_lowerBitRateConstraintFlags[i] == false        , "LowerBitrateConstraintFlag must be true for non main-RExt profiles.");
+        xConfirmPara(m_profiles[i] == Profile::MAINSTILLPICTURE && m_framesToBeEncoded > 1, "Number of frames to be encoded must be 1 when main still picture profile is used.");
+
+        xConfirmPara(m_crossComponentPredictionEnabledFlag    == true , "CrossComponentPrediction must not be used for non main-RExt profiles.");
+        xConfirmPara(m_log2MaxTransformSkipBlockSize          != 2    , "Transform Skip Log2 Max Size must be 2 for V1 profiles.");
+        xConfirmPara(m_transformSkipRotationEnabledFlag       == true , "UseResidualRotation must not be enabled for non main-RExt profiles.");
+        xConfirmPara(m_transformSkipContextEnabledFlag        == true , "UseSingleSignificanceMapContext must not be enabled for non main-RExt profiles.");
+        xConfirmPara(m_rdpcmEnabledFlag[RDPCM_SIGNAL_IMPLICIT]== true , "ImplicitResidualDPCM must not be enabled for non main-RExt profiles.");
+        xConfirmPara(m_rdpcmEnabledFlag[RDPCM_SIGNAL_EXPLICIT]== true , "ExplicitResidualDPCM must not be enabled for non main-RExt profiles.");
+        xConfirmPara(m_persistentRiceAdaptationEnabledFlag    == true , "GolombRiceParameterAdaption must not be enabled for non main-RExt profiles.");
+        xConfirmPara(m_extendedPrecisionProcessingFlag        == true , "UseExtendedPrecision must not be enabled for non main-RExt profiles.");
+        xConfirmPara(m_highPrecisionOffsetsEnabledFlag        == true , "UseHighPrecisionPredictionWeighting must not be enabled for non main-RExt profiles.");
+        xConfirmPara(m_enableIntraReferenceSmoothing          == false, "EnableIntraReferenceSmoothing must be enabled for non main-RExt profiles.");
+        xConfirmPara(m_cabacBypassAlignmentEnabledFlag                , "AlignCABACBeforeBypass cannot be enabled for non main-RExt profiles.");
+
+        if ( m_profiles[i] == Profile::MULTIVIEWMAIN )
+        {
+          xConfirmPara( maxNumRefLayers > 4, "When using the MV-Main profile, NumRefLayers must be less than or equal to 4 for all layers in the subBitstream"  );
+          // -  For a layer with nuh_layer_id iNuhLId equal to any value included in layerIdListTarget that was used to derive subBitstream, 
+          //    the value of NumRefLayers[ iNuhLId ], which specifies the total number of direct and indirect reference layers and is derived as 
+          //    specified in F.7.4.3.1, shall be less than or equal to 4.
+        }
+
+#if NH_3D
+        if ( m_profiles[i] == Profile::MAIN3D )
+        {
+          xConfirmPara( maxNumRefLayers > 9, "When using the 3D-Main profile, NumRefLayers must be less than or equal to 9 for all layers in the subBitstream."  );
+            // -  For a layer with nuh_layer_id iNuhLId equal to any value included in layerIdListTarget that was used to derive subBitstream, 
+            //   the value of NumRefLayers[ iNuhLId ], which specifies the total number of direct and indirect reference layers and is derived as 
+            //   specified in F.7.4.3.1, shall be less than or equal to 9.
+        }
+#endif
+
+
+      }
+      break;
+#if NH_MV_ALLOW_NON_CONFORMING
+    case Profile::MULTIVIEWMAIN_NONCONFORMING:
+#if NH_3D
+    case Profile::MAIN3D_NONCONFORMING:
+#endif
+#endif
+    case Profile::NONE:
+      // Non-conforming configuration, so all settings are valid.
+      break;
+    default:
+      xConfirmPara( 1, "Unknown profile selected.");
+      break;
+    }
+
+    if ( check_failed )
+    {
+      printf("Error: Checking VpsProfileTierLevel[%d]. \n", i );
+      exit(EXIT_FAILURE);
+    }
+
+  }
+  #undef xConfirmPara
+
+  Bool anyMultiLayerProfile = false; 
+
+  for (Int i = 0; i < m_profiles.size(); i++ )
+  {
+    anyMultiLayerProfile = ( anyMultiLayerProfile
+       
+      ||  (m_profiles[i] == Profile::MULTIVIEWMAIN)
+#if NH_3D
+      || ( m_profiles[i] == Profile::MAIN3D       )
+#endif
+      ) ;
+  }
+
+  if ( anyMultiLayerProfile && ( m_profiles[0] != Profile::MAIN || m_profiles[1] != Profile::MAIN  ) )
+  {
+    fprintf(stderr, "Error: The base layer must conform to the Main profile for Multilayer coding.\n");
+    exit(EXIT_FAILURE);
+  }
+
+}
+
+#endif
 
 Void TAppEncCfg::xCheckParameter()
@@ -2168,14 +3023,17 @@
   Bool check_failed = false; /* abort if there is a fatal configuration problem */
 #define xConfirmPara(a,b) check_failed |= confirmPara(a,b)
-
+  
   xConfirmPara(m_bitstreamFileName.empty(), "A bitstream file name must be specified (BitstreamFile)");
+#if !NH_MV
   const UInt maxBitDepth=(m_chromaFormatIDC==CHROMA_400) ? m_internalBitDepth[CHANNEL_TYPE_LUMA] : std::max(m_internalBitDepth[CHANNEL_TYPE_LUMA], m_internalBitDepth[CHANNEL_TYPE_CHROMA]);
+
   xConfirmPara(m_bitDepthConstraint<maxBitDepth, "The internalBitDepth must not be greater than the bitDepthConstraint value");
   xConfirmPara(m_chromaFormatConstraint<m_chromaFormatIDC, "The chroma format used must not be greater than the chromaFormatConstraint value");
-#if NH_MV
-  Profile::Name & m_profile = m_profiles[0];
-#endif
-
-  if (m_profile==Profile::MAINREXT || m_profile==Profile::HIGHTHROUGHPUTREXT)
+
+  switch (m_profile)
+  {
+    case Profile::MAINREXT:
+    case Profile::HIGHTHROUGHPUTREXT:
+
   {
     xConfirmPara(m_lowerBitRateConstraintFlag==false && m_intraConstraintFlag==false, "The lowerBitRateConstraint flag cannot be false when intraConstraintFlag is false");
@@ -2186,5 +3044,5 @@
       const UInt bitDepthIdx = (m_bitDepthConstraint == 8 ? 0 : (m_bitDepthConstraint ==10 ? 1 : (m_bitDepthConstraint == 12 ? 2 : (m_bitDepthConstraint == 16 ? 3 : 4 ))));
       const UInt chromaFormatIdx = UInt(m_chromaFormatConstraint);
-      const Bool bValidProfile = (bitDepthIdx > 3 || chromaFormatIdx>3) ? false : (validRExtProfileNames[intraIdx][bitDepthIdx][chromaFormatIdx] != NONE);
+          const Bool bValidProfile = (bitDepthIdx > 3 || chromaFormatIdx>3) ? false : (validRExtProfileNames[intraIdx][bitDepthIdx][chromaFormatIdx] != UI_NONE);
       xConfirmPara(!bValidProfile, "Invalid intra constraint flag, bit depth constraint flag and chroma format constraint flag combination for a RExt profile");
       const Bool bUsingGeneralRExtTools  = m_transformSkipRotationEnabledFlag        ||
@@ -2218,9 +3076,26 @@
     {
       xConfirmPara( m_chromaFormatConstraint != CHROMA_444, "chroma format constraint must be 4:4:4 in the High Throughput 4:4:4 16-bit Intra profile.");
-      xConfirmPara( m_bitDepthConstraint     != 16,         "bit depth constraint must be 4:4:4 in the High Throughput 4:4:4 16-bit Intra profile.");
-      xConfirmPara( m_intraConstraintFlag    != 1,          "intra constraint flag must be 1 in the High Throughput 4:4:4 16-bit Intra profile.");
-    }
-  }
-  else
+          const UInt intraIdx = m_intraConstraintFlag ? 1:0;
+          const UInt bitDepthIdx = (m_bitDepthConstraint == 8 ? 0 : (m_bitDepthConstraint ==10 ? 1 : (m_bitDepthConstraint == 14 ? 2 : (m_bitDepthConstraint == 16 ? 3 : 4 ))));
+          const Bool bValidProfile = (bitDepthIdx > 3) ? false : (validRExtHighThroughPutProfileNames[intraIdx][bitDepthIdx] != UI_NONE);
+          xConfirmPara(!bValidProfile, "Invalid intra constraint flag and bit depth constraint flag combination for a RExt high profile throughput profile");
+          if(bitDepthIdx < 2)
+          {
+            xConfirmPara((m_extendedPrecisionProcessingFlag || m_cabacBypassAlignmentEnabledFlag), "Invalid configuration for a RExt high throughput 8 and 10 bit profile");
+    }
+          if(bitDepthIdx == 3)
+          {
+            xConfirmPara(!m_cabacBypassAlignmentEnabledFlag, "Cabac Bypass Alignment flag must be 1 in the High Throughput 4:4:4 16-bit Intra profile");
+  }
+          else if(bitDepthIdx < 3)
+          {
+            xConfirmPara(!m_entropyCodingSyncEnabledFlag, "WPP flag must be 1 in the High Throughput 4:4:4 non 16-bit Intra profile");
+          }
+        }
+      }
+      break;
+    case Profile::MAIN:
+    case Profile::MAIN10:
+    case Profile::MAINSTILLPICTURE:
   {
     xConfirmPara(m_bitDepthConstraint!=((m_profile==Profile::MAIN10)?10:8), "BitDepthConstraint must be 8 for MAIN profile and 10 for MAIN10 profile.");
@@ -2242,5 +3117,21 @@
     xConfirmPara(m_cabacBypassAlignmentEnabledFlag, "AlignCABACBeforeBypass cannot be enabled for non main-RExt profiles.");
   }
-
+      break;
+    case Profile::NONE:
+      // Non-conforming configuration, so all settings are valid.
+      break;
+    default:
+      xConfirmPara( 1, "Unknown profile selected.");
+      break;
+  }
+#endif
+
+#if NH_MV
+  for (Int i = 0; i < m_numRepFormats; i++ )
+  {
+    Int* m_internalBitDepth    = &m_internalBitDepths   [i][0];
+    Int* m_inputBitDepth       = &m_inputBitDepths      [i][0];
+    Int* m_MSBExtendedBitDepth = &m_MSBExtendedBitDepths[i][0];  
+#endif
   // check range of parameters
   xConfirmPara( m_inputBitDepth[CHANNEL_TYPE_LUMA  ] < 8,                                   "InputBitDepth must be at least 8" );
@@ -2263,23 +3154,36 @@
   }
 #endif
-
   xConfirmPara( (m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA  ] < m_inputBitDepth[CHANNEL_TYPE_LUMA  ]), "MSB-extended bit depth for luma channel (--MSBExtendedBitDepth) must be greater than or equal to input bit depth for luma channel (--InputBitDepth)" );
   xConfirmPara( (m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] < m_inputBitDepth[CHANNEL_TYPE_CHROMA]), "MSB-extended bit depth for chroma channel (--MSBExtendedBitDepthC) must be greater than or equal to input bit depth for chroma channel (--InputBitDepthC)" );
 
 #if NH_MV
+  }
   for (Int i = 0; i < m_numberOfLayers; i++)
   {
-    xConfirmPara( m_log2SaoOffsetScale[i][CHANNEL_TYPE_LUMA]   > (m_internalBitDepth[CHANNEL_TYPE_LUMA  ]<10?0:(m_internalBitDepth[CHANNEL_TYPE_LUMA  ]-10)), "SaoLumaOffsetBitShift must be in the range of 0 to InternalBitDepth-10, inclusive");
-    xConfirmPara( m_log2SaoOffsetScale[i][CHANNEL_TYPE_CHROMA] > (m_internalBitDepth[CHANNEL_TYPE_CHROMA]<10?0:(m_internalBitDepth[CHANNEL_TYPE_CHROMA]-10)), "SaoChromaOffsetBitShift must be in the range of 0 to InternalBitDepthC-10, inclusive");
+    Int repFormatIdx = m_layerIdxInVpsToRepFormatIdx[i];
+    xConfirmPara( m_log2SaoOffsetScale[i][CHANNEL_TYPE_LUMA]   > (m_internalBitDepths[repFormatIdx][CHANNEL_TYPE_LUMA  ]<10?0:(m_internalBitDepths[repFormatIdx][CHANNEL_TYPE_LUMA  ]-10)), "SaoLumaOffsetBitShift must be in the range of 0 to InternalBitDepth-10, inclusive");
+    xConfirmPara( m_log2SaoOffsetScale[i][CHANNEL_TYPE_CHROMA] > (m_internalBitDepths[repFormatIdx][CHANNEL_TYPE_CHROMA]<10?0:(m_internalBitDepths[repFormatIdx][CHANNEL_TYPE_CHROMA]-10)), "SaoChromaOffsetBitShift must be in the range of 0 to InternalBitDepthC-10, inclusive");
+  }
+
+  for (Int i = 0; i < m_numRepFormats; i++)
+  {
+    xConfirmPara( m_chromaFormatIDCs[i] >= NUM_CHROMA_FORMAT,                                     "ChromaFormatIDC must be either 400, 420, 422 or 444" );
   }
 #else
   xConfirmPara( m_log2SaoOffsetScale[CHANNEL_TYPE_LUMA]   > (m_internalBitDepth[CHANNEL_TYPE_LUMA  ]<10?0:(m_internalBitDepth[CHANNEL_TYPE_LUMA  ]-10)), "SaoLumaOffsetBitShift must be in the range of 0 to InternalBitDepth-10, inclusive");
   xConfirmPara( m_log2SaoOffsetScale[CHANNEL_TYPE_CHROMA] > (m_internalBitDepth[CHANNEL_TYPE_CHROMA]<10?0:(m_internalBitDepth[CHANNEL_TYPE_CHROMA]-10)), "SaoChromaOffsetBitShift must be in the range of 0 to InternalBitDepthC-10, inclusive");
-#endif
-
   xConfirmPara( m_chromaFormatIDC >= NUM_CHROMA_FORMAT,                                     "ChromaFormatIDC must be either 400, 420, 422 or 444" );
+#endif
+
   std::string sTempIPCSC="InputColourSpaceConvert must be empty, "+getListOfColourSpaceConverts(true);
   xConfirmPara( m_inputColourSpaceConvert >= NUMBER_INPUT_COLOUR_SPACE_CONVERSIONS,         sTempIPCSC.c_str() );
+#if NH_MV
+  for (Int i = 0 ; i < m_InputChromaFormatIDC.size(); i++ )
+  {
+    xConfirmPara( m_InputChromaFormatIDC[i] >= NUM_CHROMA_FORMAT,                                "InputChromaFormatIDC must be either 400, 420, 422 or 444" );
+  }
+#else
   xConfirmPara( m_InputChromaFormatIDC >= NUM_CHROMA_FORMAT,                                "InputChromaFormatIDC must be either 400, 420, 422 or 444" );
+#endif
   xConfirmPara( m_iFrameRate <= 0,                                                          "Frame rate must be more than 1" );
   xConfirmPara( m_temporalSubsampleRatio < 1,                                               "Temporal subsample rate must be no less than 1" );
@@ -2291,4 +3195,11 @@
   xConfirmPara( m_layerIdInNuh[0] != 0      , "LayerIdInNuh must be 0 for the first layer. ");
   xConfirmPara( (m_layerIdInNuh.size()!=1) && (m_layerIdInNuh.size() < m_numberOfLayers) , "LayerIdInNuh must be given for all layers. ");
+
+#if NH_MV
+  xConfirmPara( !m_shareParameterSets && (m_numberOfLayers > 16)                            , "When NumberOfLayers is greater than 16, ShareParameterSets must be 1.");  
+  xConfirmPara( ! (m_layerIdxInVpsToGopDefIdx.size() == 0     || m_layerIdxInVpsToGopDefIdx.size() == m_numberOfLayers), "The number of entries in LayerIdxInVpsToGopDefIdx must zero or equal to NumberOfLayers.");  
+  xConfirmPara( ! (m_layerIdxInVpsToRepFormatIdx.size() == 0  || m_layerIdxInVpsToRepFormatIdx.size() == m_numberOfLayers), "The number of entries in LayerIdxInVpsToRepFormatIdx must zero or equal to NumberOfLayers.");  
+  
+#endif
 
 #if NH_3D
@@ -2370,5 +3281,4 @@
       xConfirmPara( allEqual , "Each layer shall have a different position in scalability space." );
 
-#if !H_3D_FCO
       if ( numDiff  == 1 ) 
       {
@@ -2381,5 +3291,4 @@
         xConfirmPara( shallBeButIsNotIncreasing,  "DimensionIds shall be increasing within one dimension. " );
       }
-#endif
     }
   }
@@ -2447,13 +3356,13 @@
 
   // PTL
-  xConfirmPara( ( m_profiles.size() != m_inblFlag.size() || m_profiles.size() != m_level.size()  ||  m_profiles.size() != m_levelTier.size() ), "The number of Profiles, Levels, Tiers and InblFlags must be equal." ); 
+  xConfirmPara( ( m_uiProfiles.size() != m_inblFlag.size() || m_uiProfiles.size() != m_level.size()  ||  m_uiProfiles.size() != m_levelTier.size() ), "The number of Profiles, Levels, Tiers and InblFlags must be equal." ); 
 
   if ( m_numberOfLayers > 1)
   {
-    xConfirmPara( m_profiles.size() <= 1, "The number of profiles, tiers, levels, and inblFlags must be greater than 1.");
+    xConfirmPara( m_uiProfiles.size() <= 1, "The number of profiles, tiers, levels, and inblFlags must be greater than 1.");
     xConfirmPara( m_inblFlag[0], "VpsProfileTierLevel[0] must have inblFlag equal to 0");
-    if (m_profiles.size() > 1 )
-    {
-      xConfirmPara( m_profiles[0]  != m_profiles[1], "The profile in VpsProfileTierLevel[1] must be equal to the profile in VpsProfileTierLevel[0].");
+    if (m_uiProfiles.size() > 1 )
+    {
+      xConfirmPara( m_uiProfiles[0]  != m_uiProfiles[1], "The profile in VpsProfileTierLevel[1] must be equal to the profile in VpsProfileTierLevel[0].");
       xConfirmPara( m_inblFlag[0] != m_inblFlag[1], "inblFlag in VpsProfileTierLevel[1] must be equal to the inblFlag in VpsProfileTierLevel[0].");
     }
@@ -2467,5 +3376,10 @@
     for (Int j = 0; j < m_directRefLayers[i].size(); j++)
     {
-      xConfirmPara( m_directRefLayers[i][j] < 0 || m_directRefLayers[i][j] >= i , "Reference layer id shall be greater than or equal to 0 and less than dependent layer id"); 
+      if ( m_directRefLayers[i][j] < 0 || m_directRefLayers[i][j] >= i )
+      {
+        printf( "Error: Reference layer id (%d) shall be greater than or equal to 0 and less than dependent layer id (%d). ", m_directRefLayers[i][j],  i );
+        check_failed = true; 
+      }       
+
       xConfirmPara( m_dependencyTypes[i][j] < 0 || m_dependencyTypes[i][j] >  6 , "Dependency type shall be greater than or equal to 0 and less than 7");
     }        
@@ -2499,5 +3413,11 @@
   }
 
+#if NH_MV
+  for (Int i = 0; i < m_numRepFormats; i++)
+  {
+    if(m_crossComponentPredictionEnabledFlag && (m_chromaFormatIDCs[i] != CHROMA_444))
+#else
   if(m_crossComponentPredictionEnabledFlag && (m_chromaFormatIDC != CHROMA_444))
+#endif
   {
     fprintf(stderr, "****************************************************************************\n");
@@ -2507,4 +3427,7 @@
     m_crossComponentPredictionEnabledFlag = false;
   }
+#if NH_MV
+  }
+#endif
 
   if ( m_CUTransquantBypassFlagForce && m_bUseHADME )
@@ -2531,14 +3454,11 @@
   for( Int layer = 0; layer < m_numberOfLayers; layer++ )
   {
-    xConfirmPara( m_iQP[layer] <  -6 * (m_internalBitDepth[CHANNEL_TYPE_LUMA] - 8) || m_iQP[layer] > 51,      "QP exceeds supported range (-QpBDOffsety to 51)" );
+    Int repFormatIdx = m_layerIdxInVpsToRepFormatIdx[layer];
+    xConfirmPara( m_iQP[layer] <  -6 * (m_internalBitDepths[repFormatIdx][CHANNEL_TYPE_LUMA] - 8) || m_iQP[layer] > 51,      "QP exceeds supported range (-QpBDOffsety to 51)" );
     xConfirmPara( m_deblockingFilterMetric!=0 && (m_bLoopFilterDisable[layer] || m_loopFilterOffsetInPPS), "If DeblockingFilterMetric is true then both LoopFilterDisable and LoopFilterOffsetInPPS must be 0");
   }
 #else
   xConfirmPara( m_iQP <  -6 * (m_internalBitDepth[CHANNEL_TYPE_LUMA] - 8) || m_iQP > 51,    "QP exceeds supported range (-QpBDOffsety to 51)" );
-#if W0038_DB_OPT
   xConfirmPara( m_deblockingFilterMetric!=0 && (m_bLoopFilterDisable || m_loopFilterOffsetInPPS), "If DeblockingFilterMetric is non-zero then both LoopFilterDisable and LoopFilterOffsetInPPS must be 0");
-#else
-  xConfirmPara( m_DeblockingFilterMetric && (m_bLoopFilterDisable || m_loopFilterOffsetInPPS), "If DeblockingFilterMetric is true then both LoopFilterDisable and LoopFilterOffsetInPPS must be 0");
-#endif
 #endif
   
@@ -2552,4 +3472,5 @@
 #endif
   xConfirmPara( m_iMaxDeltaQP > 7,                                                          "Absolute Delta QP exceeds supported range (0 to 7)" );
+  xConfirmPara(m_lumaLevelToDeltaQPMapping.mode &&  m_uiDeltaQpRD > 0, "Luma-level-based Delta QP cannot be used together with slice level multiple-QP optimization\n" );
   xConfirmPara( m_iMaxCuDQPDepth > m_uiMaxCUDepth - 1,                                          "Absolute depth for a minimum CuDQP exceeds maximum coding unit depth" );
 
@@ -2560,29 +3481,23 @@
 
   xConfirmPara( m_iQPAdaptationRange <= 0,                                                  "QP Adaptation Range must be more than 0" );
+#if NH_MV
+  for (Int i = 0; i < m_numberOfLayers; i++ )
+  {
+    if (m_iDecodingRefreshType == 2 || m_saoResetEncoderStateAfterIRAP)
+    {
+      xConfirmPara( m_iIntraPeriod[i] > 0 && m_iIntraPeriod[i] <= m_iGOPSize ,                      "Intra period must be larger than GOP size for periodic IDR pictures");
+    }
+  }
+#else
   if (m_iDecodingRefreshType == 2)
   {
-#if NH_MV
-    for (Int i = 0; i < m_numberOfLayers; i++ )
-    {
-      xConfirmPara( m_iIntraPeriod[i] > 0 && m_iIntraPeriod[i] <= m_iGOPSize ,                      "Intra period must be larger than GOP size for periodic IDR pictures");
-#if OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP
+   xConfirmPara( m_iIntraPeriod > 0 && m_iIntraPeriod <= m_iGOPSize ,                      "Intra period must be larger than GOP size for periodic IDR pictures");
+  }
   if (m_saoResetEncoderStateAfterIRAP)
   {
-    xConfirmPara( m_iIntraPeriod[i] > 0 && m_iIntraPeriod[i] <= m_iGOPSize ,                      "Intra period must be larger than GOP size when SAOResetEncoderStateAfterIRAP is enabled");
-  }
-#endif
-
-    }
-#else
-#if OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP
-  if (m_saoResetEncoderStateAfterIRAP)
-  {
     xConfirmPara( m_iIntraPeriod > 0 && m_iIntraPeriod <= m_iGOPSize ,                      "Intra period must be larger than GOP size when SAOResetEncoderStateAfterIRAP is enabled");
   }
 #endif
-
-   xConfirmPara( m_iIntraPeriod > 0 && m_iIntraPeriod <= m_iGOPSize ,                      "Intra period must be larger than GOP size for periodic IDR pictures");
-#endif
-  }
+  
   xConfirmPara( m_uiMaxCUDepth < 1,                                                         "MaxPartitionDepth must be greater than zero");
   xConfirmPara( (m_uiMaxCUWidth  >> m_uiMaxCUDepth) < 4,                                    "Minimum partition width size should be larger than or equal to 8");
@@ -2590,6 +3505,14 @@
   xConfirmPara( m_uiMaxCUWidth < 16,                                                        "Maximum partition width size should be larger than or equal to 16");
   xConfirmPara( m_uiMaxCUHeight < 16,                                                       "Maximum partition height size should be larger than or equal to 16");
+#if NH_MV
+  for (Int i = 0; i < m_numRepFormats; i++ )
+  {
+    xConfirmPara( (m_iSourceWidths[i]  % (m_uiMaxCUWidth  >> (m_uiMaxCUDepth-1)))!=0,             "Resulting coded frame width must be a multiple of the minimum CU size");
+    xConfirmPara( (m_iSourceHeights[i] % (m_uiMaxCUHeight >> (m_uiMaxCUDepth-1)))!=0,             "Resulting coded frame height must be a multiple of the minimum CU size");
+  }
+#else
   xConfirmPara( (m_iSourceWidth  % (m_uiMaxCUWidth  >> (m_uiMaxCUDepth-1)))!=0,             "Resulting coded frame width must be a multiple of the minimum CU size");
   xConfirmPara( (m_iSourceHeight % (m_uiMaxCUHeight >> (m_uiMaxCUDepth-1)))!=0,             "Resulting coded frame height must be a multiple of the minimum CU size");
+#endif
 
   xConfirmPara( m_uiQuadtreeTULog2MinSize < 2,                                        "QuadtreeTULog2MinSize must be 2 or greater.");
@@ -2631,5 +3554,12 @@
     for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
     {
+#if NH_MV
+      for (Int i = 0; i < m_numRepFormats; i++)
+      {
+        xConfirmPara(((m_MSBExtendedBitDepths[i][channelType] > m_internalBitDepths[i][channelType]) && m_bPCMInputBitDepthFlag), "PCM bit depth cannot be greater than internal bit depth (PCMInputBitDepthFlag cannot be used when InputBitDepth or MSBExtendedBitDepth > InternalBitDepth)");
+      }
+#else
       xConfirmPara(((m_MSBExtendedBitDepth[channelType] > m_internalBitDepth[channelType]) && m_bPCMInputBitDepthFlag), "PCM bit depth cannot be greater than internal bit depth (PCMInputBitDepthFlag cannot be used when InputBitDepth or MSBExtendedBitDepth > InternalBitDepth)");
+#endif
     }
     xConfirmPara(  m_uiPCMLog2MinSize < 3,                                      "PCMLog2MinSize must be 3 or greater.");
@@ -2649,8 +3579,22 @@
 
   Bool tileFlag = (m_numTileColumnsMinus1 > 0 || m_numTileRowsMinus1 > 0 );
+
+#if !NH_MV
   if (m_profile!=Profile::HIGHTHROUGHPUTREXT)
   {
     xConfirmPara( tileFlag && m_entropyCodingSyncEnabledFlag, "Tiles and entropy-coding-sync (Wavefronts) can not be applied together, except in the High Throughput Intra 4:4:4 16 profile");
   }
+#else
+  for (Int i = 0; i < m_numRepFormats; i++)
+  {
+    ChromaFormat m_chromaFormatIDC  = m_chromaFormatIDCs[i];
+    Int*         m_aiPad            = &m_aiPads          [i][0];
+    Int          m_confWinLeft      = m_confWinLefts    [i];
+    Int          m_confWinRight     = m_confWinRights   [i];
+    Int          m_confWinTop       = m_confWinTops     [i];
+    Int          m_confWinBottom    = m_confWinBottoms  [i];  
+    Int          m_iSourceWidth     = m_iSourceWidths   [i];
+    Int          m_iSourceHeight    = m_iSourceHeights  [i];
+#endif
 
   xConfirmPara( m_iSourceWidth  % TComSPS::getWinUnitX(m_chromaFormatIDC) != 0, "Picture width must be an integer multiple of the specified chroma subsampling");
@@ -2674,4 +3618,8 @@
     xConfirmPara( m_defDispWinBottomOffset % TComSPS::getWinUnitY(m_chromaFormatIDC) != 0, "Bottom default display window offset must be an integer multiple of the specified chroma subsampling");
   }
+
+#if NH_MV
+  }
+#endif
 
 #if NH_3D_VSO || NH_3D
@@ -2717,7 +3665,7 @@
       for( Int i = 0; i < MAX_GOP; i++ )
       {
-        if( m_GOPListMvc[k][i].m_POC != m_GOPListMvc[0][i].m_POC )
+        if( xGetGopEntries(k)[i].m_POC != xGetGopEntries(0)[i].m_POC )
         {
-          printf( "\nError: Frame%d_l%d POC %d is not identical to Frame%d POC\n", i, k, m_GOPListMvc[k][i].m_POC, i );
+          printf( "\nError: Frame%d_l%d POC %d is not identical to Frame%d POC\n", i, k, xGetGopEntries(k)[i].m_POC, i );
           bErrorMvePoc = true;
         }
@@ -2731,5 +3679,5 @@
   for( Int i = 0; i < MAX_GOP; i++ )
   {
-    if( m_GOPListMvc[0][i].m_numActiveRefLayerPics != 0 )
+    if( xGetGopEntries(0)[i].m_numActiveRefLayerPics != 0 )
     {
       printf( "\nError: Frame%d inter_layer refs not available in layer 0\n", i );
@@ -2747,5 +3695,5 @@
       for( Int i = 0; i < MAX_GOP+1; i++ )
       {
-        GOPEntry gopEntry = m_GOPListMvc[layer][i];  
+        GOPEntry gopEntry = xGetGopEntries(layer)[i];  
         for( Int j = 0; j < gopEntry.m_numActiveRefLayerPics; j++ )
         {
@@ -2790,5 +3738,5 @@
           {
             printf( "\nWarning: temporal references not possible for FrameI_l%d\n", layer );
-            for( Int j = 0; j < m_GOPListMvc[layer][MAX_GOP].m_numRefPics; j++ )
+            for( Int j = 0; j < xGetGopEntries(layer)[MAX_GOP].m_numRefPics; j++ )
             {
               gopEntry.m_referencePics[j] = 0;
@@ -2850,9 +3798,9 @@
     for( Int layer = 0; layer < m_numberOfLayers; layer++ )
     {
-      GOPEntry* m_GOPList            = m_GOPListMvc           [layer]; // It is not a member, but this name helps avoiding code duplication !!!
+      GOPEntry* m_GOPList            = xGetGopEntries         (layer); // It is not a member, but this name helps avoiding code duplication !!!
       Int&      m_extraRPSs          = m_extraRPSsMvc         [layer]; // It is not a member, but this name helps avoiding code duplication !!!
       Int&      m_maxTempLayer       = m_maxTempLayerMvc      [layer]; // It is not a member, but this name helps avoiding code duplication !!!
       Int*      m_maxDecPicBuffering = m_maxDecPicBufferingMvc[layer]; // It is not a member, but this name helps avoiding code duplication !!!
-      Int*      m_numReorderPics     = m_numReorderPicsMvc    [layer]; // It is not a member, but this name helps avoiding code duplication !!!
+      Int*      m_numReorderPics     = m_numReorderPicsMvc    [layer]; // It is not a member, but this name helps avoiding code duplication !!!      
 #endif
 
@@ -2874,5 +3822,7 @@
   else
   {
+#if !NH_MV
     xConfirmPara( m_intraConstraintFlag, "IntraConstraintFlag cannot be 1 for inter sequences");
+#endif
   }
 
@@ -2920,5 +3870,4 @@
   }
 
-#if W0038_CQP_ADJ
   for(Int i=0; i<m_iGOPSize; i++)
   {
@@ -2928,9 +3877,8 @@
     xConfirmPara( abs(m_GOPList[i].m_CrQPoffset + m_crQpOffset) > 12, "Cr QP Offset for one of the GOP entries, when combined with the PPS Cr offset, exceeds supported range (-12 to 12)" );
   }
-  xConfirmPara( abs(m_sliceChromaQpOffsetIntraOrPeriodic[0]                 > 12), "Intra/periodic Cb QP Offset exceeds supported range (-12 to 12)" );
-  xConfirmPara( abs(m_sliceChromaQpOffsetIntraOrPeriodic[0]  + m_cbQpOffset > 12), "Intra/periodic Cb QP Offset, when combined with the PPS Cb offset, exceeds supported range (-12 to 12)" );
-  xConfirmPara( abs(m_sliceChromaQpOffsetIntraOrPeriodic[1]                 > 12), "Intra/periodic Cr QP Offset exceeds supported range (-12 to 12)" );
-  xConfirmPara( abs(m_sliceChromaQpOffsetIntraOrPeriodic[1]  + m_crQpOffset > 12), "Intra/periodic Cr QP Offset, when combined with the PPS Cr offset, exceeds supported range (-12 to 12)" );
-#endif
+  xConfirmPara( abs(m_sliceChromaQpOffsetIntraOrPeriodic[0]                 ) > 12, "Intra/periodic Cb QP Offset exceeds supported range (-12 to 12)" );
+  xConfirmPara( abs(m_sliceChromaQpOffsetIntraOrPeriodic[0]  + m_cbQpOffset ) > 12, "Intra/periodic Cb QP Offset, when combined with the PPS Cb offset, exceeds supported range (-12 to 12)" );
+  xConfirmPara( abs(m_sliceChromaQpOffsetIntraOrPeriodic[1]                 ) > 12, "Intra/periodic Cr QP Offset exceeds supported range (-12 to 12)" );
+  xConfirmPara( abs(m_sliceChromaQpOffsetIntraOrPeriodic[1]  + m_crQpOffset ) > 12, "Intra/periodic Cr QP Offset, when combined with the PPS Cr offset, exceeds supported range (-12 to 12)" );
 
   m_extraRPSs=0;
@@ -3206,4 +4154,14 @@
   if(m_vuiParametersPresentFlag && m_bitstreamRestrictionFlag)
   {
+#if NH_MV
+
+    if( m_numRepFormats > 1 )
+    {
+        AOT( true ); //TBD
+    }
+
+    Int m_iSourceWidth  = m_iSourceWidths [0];
+    Int m_iSourceHeight = m_iSourceHeights[0];
+#endif
     Int PicSizeInSamplesY =  m_iSourceWidth * m_iSourceHeight;
     if(tileFlag)
@@ -3307,5 +4265,12 @@
   if (m_chromaResamplingFilterSEIenabled)
   {
+#if NH_MV
+    for (Int i = 0 ; i < m_numRepFormats; i++ )
+    {
+      xConfirmPara( (m_chromaFormatIDCs[i] == CHROMA_400 ), "chromaResamplingFilterSEI is not allowed to be present when ChromaFormatIDC is equal to zero (4:0:0)" );
+    }
+#else
     xConfirmPara( (m_chromaFormatIDC == CHROMA_400 ), "chromaResamplingFilterSEI is not allowed to be present when ChromaFormatIDC is equal to zero (4:0:0)" );
+#endif
     xConfirmPara(m_vuiParametersPresentFlag && m_chromaLocInfoPresentFlag && (m_chromaSampleLocTypeTopField != m_chromaSampleLocTypeBottomField ), "When chromaResamplingFilterSEI is enabled, ChromaSampleLocTypeTopField has to be equal to ChromaSampleLocTypeBottomField" );
   }
@@ -3322,13 +4287,5 @@
     }
     xConfirmPara( m_uiDeltaQpRD > 0, "Rate control cannot be used together with slice level multiple-QP optimization!\n" );
-#if U0132_TARGET_BITS_SATURATION
-#if NH_MV
-    if ((m_RCCpbSaturationEnabled) && (m_level[0]!=Level::NONE) && (m_profile!=Profile::NONE))
-    {
-      UInt uiLevelIdx = (m_level[0] / 10) + (UInt)((m_level[0] % 10) / 3);    // (m_level / 30)*3 + ((m_level % 10) / 3);
-      xConfirmPara(m_RCCpbSize > g_uiMaxCpbSize[m_levelTier[0]][uiLevelIdx], "RCCpbSize should be smaller than or equal to Max CPB size according to tier and level");
-      xConfirmPara(m_RCInitialCpbFullness > 1, "RCInitialCpbFullness should be smaller than or equal to 1");
-    }
-#else
+#if !NH_MV    
     if ((m_RCCpbSaturationEnabled) && (m_level!=Level::NONE) && (m_profile!=Profile::NONE))
     {
@@ -3338,12 +4295,19 @@
     }
 #endif
-#endif
-  }
-#if U0132_TARGET_BITS_SATURATION
+  }
   else
   {
     xConfirmPara( m_RCCpbSaturationEnabled != 0, "Target bits saturation cannot be processed without Rate control" );
   }
-#endif
+
+  if (m_vuiParametersPresentFlag)
+  {
+    xConfirmPara(m_RCTargetBitrate == 0, "A target bit rate is required to be set for VUI/HRD parameters.");
+    if (m_RCCpbSize == 0)
+    {
+      printf ("Warning: CPB size is set equal to zero. Adjusting value to be equal to TargetBitrate!\n");
+      m_RCCpbSize = m_RCTargetBitrate;
+    }
+  }
 
 #if NH_MV
@@ -3370,5 +4334,5 @@
 #endif
 
-  xConfirmPara(!m_TransquantBypassEnableFlag && m_CUTransquantBypassFlagForce, "CUTransquantBypassFlagForce cannot be 1 when TransquantBypassEnableFlag is 0");
+  xConfirmPara(!m_TransquantBypassEnabledFlag && m_CUTransquantBypassFlagForce, "CUTransquantBypassFlagForce cannot be 1 when TransquantBypassEnableFlag is 0");
 
   xConfirmPara(m_log2ParallelMergeLevel < 2, "Log2ParallelMergeLevel should be larger than or equal to 2");
@@ -3394,4 +4358,12 @@
   }
 
+#if MCTS_ENC_CHECK
+  if ((m_tmctsSEIEnabled) && (m_tmctsSEITileConstraint) && (m_bLFCrossTileBoundaryFlag) )
+  {
+    printf("Warning: Constrained Encoding for Temporal Motion Constrained Tile Sets is enabled. Disabling filtering across tile boundaries!\n");
+    m_bLFCrossTileBoundaryFlag = false;
+  }
+#endif
+
   if(m_timeCodeSEIEnabled)
   {
@@ -3399,6 +4371,8 @@
   }
 
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
   xConfirmPara(m_preferredTransferCharacteristics > 255, "transfer_characteristics_idc should not be greater than 255.");
+
+#if EXTENSION_360_VIDEO
+  check_failed |= m_ext360.verifyParameters();
 #endif
 
@@ -3429,4 +4403,63 @@
 }
 
+#if NH_MV
+Void TAppEncCfg::xPrintProfiles()
+{
+  printf("Profiles                          :");
+  for (Int i = 0; i < m_profiles.size(); i++)
+  {
+    if (m_profiles[i] == Profile::MAINREXT)
+    {
+      UIProfileName validProfileName;
+      if (m_onePictureOnlyConstraintFlags[i])
+      {
+        validProfileName = m_bitDepthConstraints[i] == 8 ? UI_MAIN_444_STILL_PICTURE : (m_bitDepthConstraints[i] == 16 ? UI_MAIN_444_16_STILL_PICTURE : UI_NONE);
+      }
+      else
+      {
+        const UInt intraIdx        =  m_intraConstraintFlags[i] ? 1:0;
+        const UInt bitDepthIdx     = (m_bitDepthConstraints[i] == 8 ? 0 : (m_bitDepthConstraints[i] ==10 ? 1 : (m_bitDepthConstraints[i] == 12 ? 2 : (m_bitDepthConstraints[i] == 16 ? 3 : 4 ))));
+        const UInt chromaFormatIdx = UInt(m_chromaFormatConstraints[i]);
+        validProfileName = (bitDepthIdx > 3 || chromaFormatIdx>3) ? UI_NONE : validRExtProfileNames[intraIdx][bitDepthIdx][chromaFormatIdx];
+      }
+      std::string rextSubProfile;
+      if (validProfileName!=UI_NONE)
+      {
+        rextSubProfile=enumToString(strToUIProfileName, sizeof(strToUIProfileName)/sizeof(*strToUIProfileName), validProfileName);
+      }
+      if (rextSubProfile == "main_444_16")
+      {
+        rextSubProfile="main_444_16 [NON STANDARD]";
+      }
+      printf(" %s (%s) ", profileToString(m_profiles[i]), (rextSubProfile.empty())?"INVALID REXT PROFILE":rextSubProfile.c_str() );
+
+    }
+    else if (m_profiles[i] == Profile::HIGHTHROUGHPUTREXT)
+    {
+      UIProfileName validProfileName;
+      const UInt intraIdx    = m_intraConstraintFlags[i] ? 1 : 0;
+      const UInt bitDepthIdx = (m_bitDepthConstraints[i] == 8 ? 0 : (m_bitDepthConstraints[i] ==10 ? 1 : (m_bitDepthConstraints[i] == 12 ? 2 : (m_bitDepthConstraints[i] == 16 ? 3 : 4 ))));
+      validProfileName = (bitDepthIdx > 3) ? UI_NONE : validRExtHighThroughPutProfileNames[intraIdx][bitDepthIdx];
+      std::string subProfile;
+      if (validProfileName!=UI_NONE)
+      {
+        subProfile=enumToString(strToUIProfileName, sizeof(strToUIProfileName)/sizeof(*strToUIProfileName), validProfileName);
+      }
+      printf(" : %s (%s)\n", profileToString(m_profiles[i]), (subProfile.empty())?"INVALID HIGH THROUGHPUT REXT PROFILE":subProfile.c_str() );
+    }
+    else if (m_profiles[i] == Profile::MAIN10 && m_onePictureOnlyConstraintFlags[i])
+    {
+      printf(" : %s (main10-still-picture)\n", profileToString(m_profiles[i]) );
+    }
+    else
+    {
+      printf(" %s ", profileToString(m_profiles[i]) );
+    }
+  }
+  printf("\n\n");
+
+}
+#endif
+
 Void TAppEncCfg::xPrintParameter()
 {
@@ -3435,14 +4468,14 @@
   for( Int layer = 0; layer < m_numberOfLayers; layer++)
   {
-    printf("Input File %i                     : %s\n", layer, m_pchInputFileList[layer]);
+    printf("Input          File %i             : %s\n", layer, m_pchInputFileList[layer]);    
   }
 #else
   printf("Input          File                    : %s\n", m_inputFileName.c_str()          );
 #endif
-  printf("Bitstream      File                    : %s\n", m_bitstreamFileName.c_str()      );
+  printf("Bitstream      File               : %s\n", m_bitstreamFileName.c_str()      );
 #if NH_MV
   for( Int layer = 0; layer < m_numberOfLayers; layer++)
-  {
-    printf("Reconstruction File %i            : %s\n", layer, m_pchReconFileList[layer]);
+  { 
+    printf("Reconstruction File %i             : %s\n", layer, m_pchReconFileList[layer]);
   }
 #else
@@ -3464,14 +4497,37 @@
 #endif
 #if NH_MV  
+#if !JVET_E0059_FLOATING_POINT_QP_FIX
   xPrintParaVector( "QP"               , m_fQP                ); 
+#endif
   xPrintParaVector( "LoopFilterDisable", m_bLoopFilterDisable ); 
   xPrintParaVector( "SAO"              , m_bUseSAO            ); 
-#endif
-
+  printf("ShareParameterSets                : %d\n",  m_shareParameterSets ?  1  : 0  );         
+#endif
+
+#if NH_MV
+  printf("Real     Format                   :");
+  for(Int i = 0; i < m_numRepFormats; i++ )
+  { 
+    printf(" (%dx%d %gHz)", m_iSourceWidths[i] - m_confWinLefts[i] - m_confWinRights[i], m_iSourceHeights[i] - m_confWinTops[i] - m_confWinBottoms[i], (Double)m_iFrameRate/m_temporalSubsampleRatio );
+  }
+
+  printf("\nInternal Format                   :" );
+  for(Int i = 0; i < m_numRepFormats; i++ )
+  { 
+
+    printf(" (%dx%d %gHz)", m_iSourceWidths[i], m_iSourceHeights[i], (Double)m_iFrameRate/m_temporalSubsampleRatio );
+  }  
+  printf("\n"); 
+#else
   printf("Real     Format                        : %dx%d %gHz\n", m_iSourceWidth - m_confWinLeft - m_confWinRight, m_iSourceHeight - m_confWinTop - m_confWinBottom, (Double)m_iFrameRate/m_temporalSubsampleRatio );
   printf("Internal Format                        : %dx%d %gHz\n", m_iSourceWidth, m_iSourceHeight, (Double)m_iFrameRate/m_temporalSubsampleRatio );
+
+#endif
   printf("Sequence PSNR output              : %s\n", (m_printMSEBasedSequencePSNR ? "Linear average, MSE-based" : "Linear average only") );
   printf("Sequence MSE output               : %s\n", (m_printSequenceMSE ? "Enabled" : "Disabled") );
   printf("Frame MSE output                  : %s\n", (m_printFrameMSE    ? "Enabled" : "Disabled") );
+#if JVET_F0064_MSSSIM  
+  printf("MS-SSIM output                    : %s\n", (m_printMSSSIM      ? "Enabled" : "Disabled") );
+#endif
   printf("Cabac-zero-word-padding           : %s\n", (m_cabacZeroWordPaddingEnabled? "Enabled" : "Disabled") );
   if (m_isField)
@@ -3487,17 +4543,11 @@
     printf("Frame index                       : %u - %d (%d frames)\n", m_FrameSkip, m_FrameSkip+m_framesToBeEncoded-1, m_framesToBeEncoded );
   }
-#if NH_MV
-  printf("Profile                           :");
-  for (Int i = 0; i < m_profiles.size(); i++)
-  {
-    Profile::Name m_profile = m_profiles[i];
-
-#endif
+#if !NH_MV
     if (m_profile == Profile::MAINREXT)
     {
-    ExtendedProfileName validProfileName;
+    UIProfileName validProfileName;
     if (m_onePictureOnlyConstraintFlag)
     {
-      validProfileName = m_bitDepthConstraint == 8 ? MAIN_444_STILL_PICTURE : (m_bitDepthConstraint == 16 ? MAIN_444_16_STILL_PICTURE : NONE);
+      validProfileName = m_bitDepthConstraint == 8 ? UI_MAIN_444_STILL_PICTURE : (m_bitDepthConstraint == 16 ? UI_MAIN_444_16_STILL_PICTURE : UI_NONE);
     }
     else
@@ -3506,10 +4556,10 @@
       const UInt bitDepthIdx = (m_bitDepthConstraint == 8 ? 0 : (m_bitDepthConstraint ==10 ? 1 : (m_bitDepthConstraint == 12 ? 2 : (m_bitDepthConstraint == 16 ? 3 : 4 ))));
       const UInt chromaFormatIdx = UInt(m_chromaFormatConstraint);
-      validProfileName = (bitDepthIdx > 3 || chromaFormatIdx>3) ? NONE : validRExtProfileNames[intraIdx][bitDepthIdx][chromaFormatIdx];
+      validProfileName = (bitDepthIdx > 3 || chromaFormatIdx>3) ? UI_NONE : validRExtProfileNames[intraIdx][bitDepthIdx][chromaFormatIdx];
     }
       std::string rextSubProfile;
-      if (validProfileName!=NONE)
-      {
-        rextSubProfile=enumToString(strToExtendedProfile, sizeof(strToExtendedProfile)/sizeof(*strToExtendedProfile), validProfileName);
+    if (validProfileName!=UI_NONE)
+      {
+      rextSubProfile=enumToString(strToUIProfileName, sizeof(strToUIProfileName)/sizeof(*strToUIProfileName), validProfileName);
       }
       if (rextSubProfile == "main_444_16")
@@ -3517,24 +4567,34 @@
         rextSubProfile="main_444_16 [NON STANDARD]";
       }
-#if NH_MV
-      printf(" %s (%s) ", profileToString(m_profile), (rextSubProfile.empty())?"INVALID REXT PROFILE":rextSubProfile.c_str() );
-#else
       printf("Profile                           : %s (%s)\n", profileToString(m_profile), (rextSubProfile.empty())?"INVALID REXT PROFILE":rextSubProfile.c_str() );
-#endif
-    }
-    else
-    {
-#if NH_MV
-      printf(" %s ", profileToString(m_profile) );
-#else
+  }
+  else if (m_profile == Profile::HIGHTHROUGHPUTREXT)
+  {
+    UIProfileName validProfileName;
+    const UInt intraIdx = m_intraConstraintFlag ? 1:0;
+    const UInt bitDepthIdx = (m_bitDepthConstraint == 8 ? 0 : (m_bitDepthConstraint ==10 ? 1 : (m_bitDepthConstraint == 12 ? 2 : (m_bitDepthConstraint == 16 ? 3 : 4 ))));
+    validProfileName = (bitDepthIdx > 3) ? UI_NONE : validRExtHighThroughPutProfileNames[intraIdx][bitDepthIdx];
+    std::string subProfile;
+    if (validProfileName!=UI_NONE)
+    {
+      subProfile=enumToString(strToUIProfileName, sizeof(strToUIProfileName)/sizeof(*strToUIProfileName), validProfileName);
+    }
+    printf("Profile                                : %s (%s)\n", profileToString(m_profile), (subProfile.empty())?"INVALID HIGH THROUGHPUT REXT PROFILE":subProfile.c_str() );
+  }
+  else if (m_profile == Profile::MAIN10 && m_onePictureOnlyConstraintFlag)
+  {
+    printf("Profile                                : %s (main10-still-picture)\n", profileToString(m_profile) );
+  }
+  else
+  {
       printf("Profile                           : %s\n", profileToString(m_profile) );
-#endif
-    }
-#if NH_MV    
-  }
-  printf("\n");
-#endif
-
+   }
+#endif
+
+#if NH_MV
+  printf("CU size / depth / total-depth     : %d / %d / %d\n", m_uiMaxCUWidth, m_uiMaxCUDepth, m_uiMaxTotalCUDepth[0] );
+#else
   printf("CU size / depth / total-depth     : %d / %d / %d\n", m_uiMaxCUWidth, m_uiMaxCUDepth, m_uiMaxTotalCUDepth );
+#endif
   printf("RQT trans. size (min / max)       : %d / %d\n", 1 << m_uiQuadtreeTULog2MinSize, 1 << m_uiQuadtreeTULog2MaxSize );
   printf("Max RQT depth inter               : %d\n", m_uiQuadtreeTUMaxDepthInter);
@@ -3552,5 +4612,26 @@
 #endif
   printf("Decoding refresh type             : %d\n", m_iDecodingRefreshType );
-#if !NH_MV
+#if JVET_E0059_FLOATING_POINT_QP_FIX
+
+#if NH_MV
+  if ( !m_qpIncrementAtSourceFrame.empty() )
+  {
+    xPrintParaVector( "QPIncrementFrame", m_qpIncrementAtSourceFrame );     
+  }
+#else
+  if (m_qpIncrementAtSourceFrame.bPresent)
+  {
+    printf("QP                                     : %d (incrementing internal QP at source frame %d)\n", m_iQP, m_qpIncrementAtSourceFrame.value );
+  }
+#endif
+  else
+  {
+#if NH_MV
+    xPrintParaVector( "QP", m_iQP ); 
+#else
+    printf("QP                                     : %d\n", m_iQP );
+#endif
+  }
+#else
   printf("QP                                : %5.2f\n", m_fQP );
 #endif
@@ -3561,4 +4642,32 @@
   printf("QP adaptation                     : %d (range=%d)\n", m_bUseAdaptiveQP, (m_bUseAdaptiveQP ? m_iQPAdaptationRange : 0) );
   printf("GOP size                          : %d\n", m_iGOPSize );
+
+#if NH_MV
+  printf("Input bit depth                   :");
+  for (Int i = 0; i < m_numRepFormats; i++ )
+  {
+    printf(" (Y:%d, C:%d)", m_inputBitDepths[i][CHANNEL_TYPE_LUMA], m_inputBitDepths[i][CHANNEL_TYPE_CHROMA] );
+  }
+
+  printf("\nMSB-extended bit depth            :");
+  for (Int i = 0; i < m_numRepFormats; i++ )
+  {
+    printf(" (Y:%d, C:%d)", m_MSBExtendedBitDepths[i][CHANNEL_TYPE_LUMA], m_MSBExtendedBitDepths[i][CHANNEL_TYPE_CHROMA] );
+  }
+
+  printf("\nInternal bit depth                :");
+  for (Int i = 0; i < m_numRepFormats; i++ )
+  {
+    printf(" (Y:%d, C:%d)", m_internalBitDepths[i][CHANNEL_TYPE_LUMA], m_internalBitDepths[i][CHANNEL_TYPE_CHROMA] );
+  }
+  
+  printf("\nPCM sample bit depth              :");
+  for (Int i = 0; i < m_numRepFormats; i++ )
+  {
+    printf(" (Y:%d, C:%d)", m_bPCMInputBitDepthFlag ? m_MSBExtendedBitDepths[i][CHANNEL_TYPE_LUMA]   : m_internalBitDepths[i][CHANNEL_TYPE_LUMA], 
+                             m_bPCMInputBitDepthFlag ? m_MSBExtendedBitDepths[i][CHANNEL_TYPE_CHROMA] : m_internalBitDepths[i][CHANNEL_TYPE_CHROMA] );
+  }
+  printf("\n" );
+#else
   printf("Input bit depth                   : (Y:%d, C:%d)\n", m_inputBitDepth[CHANNEL_TYPE_LUMA], m_inputBitDepth[CHANNEL_TYPE_CHROMA] );
   printf("MSB-extended bit depth            : (Y:%d, C:%d)\n", m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA], m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] );
@@ -3566,4 +4675,5 @@
   printf("PCM sample bit depth              : (Y:%d, C:%d)\n", m_bPCMInputBitDepthFlag ? m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA] : m_internalBitDepth[CHANNEL_TYPE_LUMA],
                                                                m_bPCMInputBitDepthFlag ? m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA] : m_internalBitDepth[CHANNEL_TYPE_CHROMA] );
+#endif
   printf("Intra reference smoothing         : %s\n", (m_enableIntraReferenceSmoothing          ? "Enabled" : "Disabled") );
   printf("diff_cu_chroma_qp_offset_depth         : %d\n", m_diffCuChromaQpOffsetDepth);
@@ -3629,6 +4739,4 @@
     printf("InitialQP                         : %d\n", m_RCInitialQP );
     printf("ForceIntraQP                      : %d\n", m_RCForceIntraQP );
-
-#if U0132_TARGET_BITS_SATURATION
     printf("CpbSaturation                          : %d\n", m_RCCpbSaturationEnabled );
     if (m_RCCpbSaturationEnabled)
@@ -3637,5 +4745,4 @@
       printf("InitalCpbFullness                      : %.2f\n", m_RCInitialCpbFullness);
     }
-#endif
 
 #if KWU_RC_MADPRED_E0227
@@ -3686,12 +4793,19 @@
 #if NH_MV
   printf("TOOL CFG General: ");
+
+  for( Int i = 0; i < m_numRepFormats; i++)
+  {
+    printf("IBD(%d):%d ", i, ((m_internalBitDepths[i][CHANNEL_TYPE_LUMA] > m_MSBExtendedBitDepths[i][CHANNEL_TYPE_LUMA]) || (m_internalBitDepths[i][CHANNEL_TYPE_CHROMA] > m_MSBExtendedBitDepths[i][CHANNEL_TYPE_CHROMA])));
+  }
 #else
   printf("TOOL CFG: ");
-#endif
-  printf("IBD:%d ", ((m_internalBitDepth[CHANNEL_TYPE_LUMA] > m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA]) || (m_internalBitDepth[CHANNEL_TYPE_CHROMA] > m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA])));
+    printf("IBD:%d ", ((m_internalBitDepth[CHANNEL_TYPE_LUMA] > m_MSBExtendedBitDepth[CHANNEL_TYPE_LUMA]) || (m_internalBitDepth[CHANNEL_TYPE_CHROMA] > m_MSBExtendedBitDepth[CHANNEL_TYPE_CHROMA])));
+#endif
+
   printf("HAD:%d ", m_bUseHADME           );
   printf("RDQ:%d ", m_useRDOQ            );
   printf("RDQTS:%d ", m_useRDOQTS        );
   printf("RDpenalty:%d ", m_rdPenalty  );
+  printf("LQP:%d ", m_lumaLevelToDeltaQPMapping.mode     );
   printf("SQP:%d ", m_uiDeltaQpRD         );
   printf("ASR:%d ", m_bUseASR             );
@@ -3723,5 +4837,5 @@
   printf("PCM:%d ", (m_usePCM && (1<<m_uiPCMLog2MinSize) <= m_uiMaxCUWidth)? 1 : 0);
 
-  if (m_TransquantBypassEnableFlag && m_CUTransquantBypassFlagForce)
+  if (m_TransquantBypassEnabledFlag && m_CUTransquantBypassFlagForce)
   {
     printf("TransQuantBypassEnabled: =1");
@@ -3729,5 +4843,5 @@
   else
   {
-    printf("TransQuantBypassEnabled:%d ", (m_TransquantBypassEnableFlag)? 1:0 );
+    printf("TransQuantBypassEnabled:%d ", (m_TransquantBypassEnabledFlag)? 1:0 );
   }
 
@@ -3735,6 +4849,14 @@
   printf("WPB:%d ", (Int)m_useWeightedBiPred);
   printf("PME:%d ", m_log2ParallelMergeLevel);
+#if NH_MV
+  for( Int i = 0; i < m_numRepFormats; i++ )
+  {
+    const Int iWaveFrontSubstreams = m_entropyCodingSyncEnabledFlag ? (m_iSourceHeights[i] + m_uiMaxCUHeight - 1) / m_uiMaxCUHeight : 1;
+    printf(" WaveFrontSynchro(%d):%d WaveFrontSubstreams(%d):%d", i, m_entropyCodingSyncEnabledFlag?1:0, i, iWaveFrontSubstreams );
+  }
+#else
   const Int iWaveFrontSubstreams = m_entropyCodingSyncEnabledFlag ? (m_iSourceHeight + m_uiMaxCUHeight - 1) / m_uiMaxCUHeight : 1;
   printf(" WaveFrontSynchro:%d WaveFrontSubstreams:%d", m_entropyCodingSyncEnabledFlag?1:0, iWaveFrontSubstreams);
+#endif
   printf(" ScalingList:%d ", m_useScalingListId );
   printf("TMVPMode:%d ", m_TMVPModeId     );
@@ -3743,14 +4865,15 @@
 #endif
 
-  printf(" SignBitHidingFlag:%d ", m_signHideFlag);
+  printf(" SignBitHidingFlag:%d ", m_signDataHidingEnabledFlag);
   printf("RecalQP:%d", m_recalculateQPAccordingToLambda ? 1 : 0 );
+#if EXTENSION_360_VIDEO
+  m_ext360.outputConfigurationSummary();
+#endif
 #if NH_3D_VSO
   printf(" VSO:%d ", m_bUseVSO   );
   printf("WVSO:%d ", m_bUseWVSO );  
 #endif
-#if NH_3D_QTL
+#if NH_3D
   printf( "QTL:%d "                  , m_bUseQTL);
-#endif
-#if NH_3D
   printf( "IlluCompEnable:%d "       , m_abUseIC);
   printf( "IlluCompLowLatencyEnc:%d ",  m_bUseLowLatencyICEnc);
@@ -3780,4 +4903,199 @@
   fflush(stdout);
 }
+#if NH_MV
+
+Void TAppEncCfg::xConfirmRepFormat(const TComVPS& vps )
+{
+  Bool checkFailed = false; 
+
+  // This might not cover all disallowed cases. To be further tested.
+#if NH_3D
+  Bool allDepthSameBitDepth = true; 
+  Bool allSameSize          = true; 
+  Bool allTextureChroma420  = true; 
+  
+  Int  lastBitDepth         = -1; 
+  Int  lastWidth            = -1; 
+  Int  lastHeight           = -1; 
+
+  Int lastChromaFormat     = (Int) CHROMA_420; 
+
+  for(Int i = 0; i <= vps.getMaxLayersMinus1(); i++ )
+  {
+    Int curLayerIdInNuh = vps.getLayerIdInNuh( i );
+
+    const TComRepFormat* repFormat = vps.getRepFormat( vps.getVpsRepFormatIdx( i  ) ); 
+
+    Int curWidth = repFormat->getPicWidthVpsInLumaSamples();
+    allSameSize  = allSameSize && ( lastWidth == -1 || lastWidth  == curWidth );
+    lastWidth    = curWidth; 
+
+    Int curHeight = repFormat->getPicHeightVpsInLumaSamples();
+    allSameSize   = allSameSize && ( lastHeight == -1 || lastHeight  == curHeight );
+    lastHeight    = curHeight; 
+
+    if ( vps.getVpsDepthFlag( curLayerIdInNuh ))
+    { 
+      Int curBitDepth      = repFormat->getBitDepthVpsLumaMinus8(); 
+      allDepthSameBitDepth = allDepthSameBitDepth && ( lastBitDepth == -1 || lastBitDepth  == curBitDepth );
+      lastBitDepth         = curBitDepth; 
+    }
+    else
+    {
+      Int curChromaFormat = repFormat->getChromaFormatVpsIdc();
+      allTextureChroma420 = allTextureChroma420 && ( lastChromaFormat  == curChromaFormat );
+      lastChromaFormat    = curChromaFormat; 
+    }
+  }
+
+  checkFailed |= confirmPara( !allDepthSameBitDepth                                         ,  "The HTM implementation requires that InternalBitDepth of all depth layers must be equal."  );
+  checkFailed |= confirmPara( !allSameSize           && ( m_bUseVSO || m_bUseEstimatedVSD ) ,  "When VSO or VSD are enabled, the HTM implementation requires that SourceHeight and SourceWidth of all layers must be equal."  );
+  checkFailed |= confirmPara( !allTextureChroma420   &&  m_bUseVSO                          ,  "When VSO is enabled, the HTM implementation requires that all textures have ChromaFormat 420."  );  
+#endif
+
+  // Check reference layers
+  for (Int curLayerId = 0; curLayerId <= vps.getMaxLayersMinus1(); curLayerId++ )
+  {  
+
+    const TComRepFormat* curRepFormat = vps.getRepFormat( vps.getVpsRepFormatIdx( curLayerId  ) ); 
+
+    Int curLayerIdInNuh      = vps.getLayerIdInNuh( curLayerId );
+    
+    for( Int i = 0; i < vps.getNumDirectRefLayers( curLayerIdInNuh ); i++ )
+    { 
+      Int refLayerId =  vps.getLayerIdInVps( vps.getIdDirectRefLayer( curLayerIdInNuh, i ));//   refLayers[i];
+      const TComRepFormat* refRepFormat = vps.getRepFormat( vps.getVpsRepFormatIdx( refLayerId ) ); 
+
+      // Require equal size
+      xConfirmSingleRepFormat( checkFailed, "SourceHeight",curLayerId, refLayerId,  curRepFormat->getPicHeightVpsInLumaSamples(), refRepFormat->getPicHeightVpsInLumaSamples() );
+      xConfirmSingleRepFormat( checkFailed, "SourceWidth" ,curLayerId, refLayerId,  curRepFormat->getPicWidthVpsInLumaSamples() , refRepFormat->getPicWidthVpsInLumaSamples () );
+#if NH_3D
+
+      // For 3D-HEVC, dependencies can be e.g. from texture 4:2:0 to depth 4:0:0, so check only layers that might be inserted to the reference lists.
+    }
+
+    for( Int i = 0; i < vps.getNumRefListLayers( curLayerIdInNuh  ); i++ )
+    {
+      Int refLayerId =  vps.getLayerIdInVps( vps.getIdRefListLayer( curLayerIdInNuh, i ) );//   refLayers[i];
+      const TComRepFormat* refRepFormat = vps.getRepFormat( vps.getVpsRepFormatIdx( refLayerId ) ); 
+#endif
+      // Sample dependency -> require same bit depth and chroma format
+      xConfirmSingleRepFormat( checkFailed, "ChromaFormatIDC"          , curLayerId, refLayerId,  curRepFormat->getChromaFormatVpsIdc()     , refRepFormat->getChromaFormatVpsIdc()  );
+      xConfirmSingleRepFormat( checkFailed, "InternalBitDepth (Luma)"  , curLayerId, refLayerId,  curRepFormat->getBitDepthVpsLumaMinus8()  , refRepFormat->getBitDepthVpsLumaMinus8());
+      xConfirmSingleRepFormat( checkFailed, "InternalBitDepth (Chroma)", curLayerId, refLayerId,  curRepFormat->getBitDepthVpsChromaMinus8(), refRepFormat->getBitDepthVpsChromaMinus8());
+    }
+    // TBD: add 3D-HEVC constraints e.g. for VSP, QTL
+  }
+
+  if( checkFailed )
+  {
+    exit(0);
+  }
+}
+
+Void TAppEncCfg::xConvertRepFormatParameters(
+  IntAry2d& tmpPad                       ,             
+  IntAry2d& tmpInputBitDepth             ,
+  IntAry2d& tmpOutputBitDepth            ,
+  IntAry2d& tmpMSBExtendedBitDepth       ,
+  IntAry2d& tmpInternalBitDepth          ,
+  IntAry1d& tmpInputChromaFormat         ,
+  IntAry1d& tmpChromaFormat
+  ) 
+{
+  typedef std::pair< IntAry2d*,  IntAry2d* > ParamMapPair;
+  std::vector< ParamMapPair > paramTwoElem;
+  paramTwoElem.push_back( ParamMapPair( &tmpPad                ,  &m_aiPads               )  );
+  paramTwoElem.push_back( ParamMapPair( &tmpInputBitDepth      ,  &m_inputBitDepths       )  );
+  paramTwoElem.push_back( ParamMapPair( &tmpOutputBitDepth     ,  &m_outputBitDepths      )  );
+  paramTwoElem.push_back( ParamMapPair( &tmpMSBExtendedBitDepth,  &m_MSBExtendedBitDepths )  );
+  paramTwoElem.push_back( ParamMapPair( &tmpInternalBitDepth   ,  &m_internalBitDepths    )  );
+  
+  std::vector< IntAry1d* > paramOneElem;
+  paramOneElem.push_back(  &m_confWinLefts  );  
+  paramOneElem.push_back(  &m_confWinRights );
+  paramOneElem.push_back(  &m_confWinTops   );
+  paramOneElem.push_back(  &m_confWinBottoms);
+  paramOneElem.push_back(  &m_iSourceWidths );
+  paramOneElem.push_back(  &m_iSourceHeights);
+  paramOneElem.push_back(  &tmpInputChromaFormat );
+  paramOneElem.push_back(  &tmpChromaFormat );
+
+
+  // Get maximum number of representation formats
+  size_t maxSize = 0;
+
+  for (Int i = 0; i < paramTwoElem.size(); i++)
+  {
+    for (Int j = 0; j < 2; j++ )
+    {
+      IntAry1d& curElems = (* (paramTwoElem[i].first) )[j];
+      maxSize = std::max<size_t>(  maxSize, curElems.size()  );
+    }    
+  }
+
+  for (Int i = 0; i < paramOneElem.size(); i++)
+  {
+    maxSize = std::max<size_t>(  maxSize, (paramOneElem[i]->size() ) );
+  }
+
+  // Resize to maximum
+  for (Int i = 0; i < paramTwoElem.size(); i++)
+  {
+    IntAry2d& curElems = (* (paramTwoElem[i].first) );    
+    for (Int j = 0; j < 2; j++ )
+    { 
+      xResizeVector( curElems[j], (UInt) maxSize );        
+    }
+  }
+
+  for (Int i = 0; i < paramOneElem.size(); i++)
+  {
+    xResizeVector( (*paramOneElem[i]), (UInt) maxSize );              
+  }
+  
+  // Transpose
+  for (Int i = 0; i < paramTwoElem.size(); i++)
+  {
+    IntAry2d&  curElem  = (* (paramTwoElem[i].first  ) );
+    IntAry2d&  curElemT = (* (paramTwoElem[i].second ) );
+
+    curElemT.resize(maxSize);
+    for (Int k = 0; k < maxSize; k++ )
+    {
+      curElemT[k].resize(2);
+      for (Int j = 0; j < 2; j++ )
+      {
+        curElemT[k][j] = curElem[j][k];
+      }
+    }    
+  }
+
+  m_numRepFormats = (Int) maxSize; 
+}
+
+
+
+Void TAppEncCfg::xGetMaxValuesOfApplicableLayers(const TComVPS& vps, Int vpsPtlIdx, Int& maxBitDepthLuma, Int& maxBitDepthChroma, ChromaFormat& maxChromaFormatIdc, Int& maxNumRefLayers )
+{ 
+  maxChromaFormatIdc        = CHROMA_400;
+  maxBitDepthLuma   = -1;
+  maxBitDepthChroma = -1;
+  maxNumRefLayers   = 0; 
+
+  IntAry1d applicableLayerIdsInVps = vps.getLayersOfVpsPtl( vpsPtlIdx );
+
+  for (Int i = 0; i < applicableLayerIdsInVps.size(); i++ )
+  {
+    Int curLayerIdInVps       = applicableLayerIdsInVps[ i ];
+    Int repFormatIdx          = m_layerIdxInVpsToRepFormatIdx[ curLayerIdInVps ];
+    maxChromaFormatIdc        = std::max<ChromaFormat> ( m_chromaFormatIDCs[ repFormatIdx], maxChromaFormatIdc );
+    maxBitDepthLuma   = std::max<Int> ( m_internalBitDepths[ repFormatIdx ][CHANNEL_TYPE_LUMA  ], maxBitDepthLuma   );
+    maxBitDepthChroma = std::max<Int> ( m_internalBitDepths[ repFormatIdx ][CHANNEL_TYPE_CHROMA], maxBitDepthChroma );
+    maxNumRefLayers   = std::max<Int> ( vps.getNumRefLayers( vps.getLayerIdInNuh( curLayerIdInVps ) ), maxNumRefLayers ) ;
+  }
+}
+
+#endif
 
 Bool confirmPara(Bool bflag, const TChar* message)
Index: /trunk/source/App/TAppEncoder/TAppEncCfg.h
===================================================================
--- /trunk/source/App/TAppEncoder/TAppEncCfg.h	(revision 1412)
+++ /trunk/source/App/TAppEncoder/TAppEncCfg.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -42,4 +42,7 @@
 
 #include "TLibEncoder/TEncCfg.h"
+#if EXTENSION_360_VIDEO
+#include "TAppEncHelper360/TExt360AppEncCfg.h"
+#endif
 #include <sstream>
 #include <vector>
@@ -56,7 +59,80 @@
 // ====================================================================================================================
 
+#if NH_MV
+enum UIProfileName // this is used for determining profile strings, where multiple profiles map to a single profile idc with various constraint flag combinations
+{
+  UI_NONE = 0,
+  UI_MAIN = 1,
+  UI_MAIN10 = 2,
+  UI_MAIN10_STILL_PICTURE=10002,
+  UI_MAINSTILLPICTURE = 3,
+  UI_MAINREXT = 4,
+  UI_HIGHTHROUGHPUTREXT = 5,
+  // The following are RExt profiles, which would map to the MAINREXT profile idc.
+  // The enumeration indicates the bit-depth constraint in the bottom 2 digits
+  //                           the chroma format in the next digit
+  //                           the intra constraint in the next digit (1 for no intra constraint, 2 for intra constraint)
+  //                           If it is a RExt still picture, there is a '1' for the top digit.
+#if NH_MV
+  UI_MULTIVIEWMAIN     = 6,
+#if NH_3D
+  UI_MAIN3D            = 8, 
+#endif
+#endif
+  UI_MONOCHROME_8      = 1008,
+  UI_MONOCHROME_12     = 1012,
+  UI_MONOCHROME_16     = 1016,
+  UI_MAIN_12           = 1112,
+  UI_MAIN_422_10       = 1210,
+  UI_MAIN_422_12       = 1212,
+  UI_MAIN_444          = 1308,
+  UI_MAIN_444_10       = 1310,
+  UI_MAIN_444_12       = 1312,
+  UI_MAIN_444_16       = 1316, // non-standard profile definition, used for development purposes
+  UI_MAIN_INTRA        = 2108,
+  UI_MAIN_10_INTRA     = 2110,
+  UI_MAIN_12_INTRA     = 2112,
+  UI_MAIN_422_10_INTRA = 2210,
+  UI_MAIN_422_12_INTRA = 2212,
+  UI_MAIN_444_INTRA    = 2308,
+  UI_MAIN_444_10_INTRA = 2310,
+  UI_MAIN_444_12_INTRA = 2312,
+  UI_MAIN_444_16_INTRA = 2316,
+  UI_MAIN_444_STILL_PICTURE = 11308,
+  UI_MAIN_444_16_STILL_PICTURE = 12316,
+  // The following are high throughput profiles, which would map to the HIGHTHROUGHPUTREXT profile idc.
+  // The enumeration indicates the bit-depth constraint in the bottom 2 digits
+  //                           the chroma format in the next digit
+  //                           the intra constraint in the next digit
+  //                           There is a '2' for the top digit to indicate it is high throughput profile
+
+  UI_HIGHTHROUGHPUT_444     = 21308,
+  UI_HIGHTHROUGHPUT_444_10  = 21310,
+  UI_HIGHTHROUGHPUT_444_14  = 21314,
+  UI_HIGHTHROUGHPUT_444_16_INTRA  = 22316
+#if NH_MV_ALLOW_NON_CONFORMING
+  , 
+  UI_MULTIVIEWMAIN_NONCONF     = 10000006,
+#if NH_3D
+  UI_MAIN3D_NONCONF            = 10000008, 
+#endif
+#endif
+};
+#endif
+
 /// encoder configuration class
 class TAppEncCfg
 {
+#if JVET_E0059_FLOATING_POINT_QP_FIX
+public:
+  template <class T>
+  struct OptionalValue
+  {
+    Bool bPresent;
+    T    value;
+    OptionalValue() : bPresent(false), value() { }
+  };
+#endif
+
 protected:
   // file I/O
@@ -71,4 +147,11 @@
   Int                    m_numberOfLayers;                    ///< number of Layers to Encode
   Int                    m_iNumberOfViews;                    ///< number of Layers that are views
+#if NH_MV
+  Bool                   m_shareParameterSets;
+  IntAry1d               m_layerIdxInVpsToGopDefIdx;
+  IntAry1d               m_layerIdxInVpsToRepFormatIdx;  
+  Int                    m_numRepFormats;
+  Int                    m_numInputOutputRepFormats;
+#endif
 #else
   std::string m_reconFileName;                                ///< output reconstruction file
@@ -91,12 +174,12 @@
 // layer sets   
   Int                    m_vpsNumLayerSets;                   ///< Number of layer sets
-  IntAry2d m_layerIdxInVpsInSets;           ///< LayerIds in vps of layer set 
-  Int                    m_numAddLayerSets;                    ///< Number of additional layer sets
-  IntAry2d m_highestLayerIdxPlus1;      ///< HighestLayerIdxPlus1 for each additional layer set and each independent layer (value with index 0 will be ignored)
+  IntAry2d               m_layerIdxInVpsInSets;               ///< LayerIds in vps of layer set 
+  Int                    m_numAddLayerSets;                   ///< Number of additional layer sets
+  IntAry2d               m_highestLayerIdxPlus1;              ///< HighestLayerIdxPlus1 for each additional layer set and each independent layer (value with index 0 will be ignored)
   Int                    m_defaultOutputLayerIdc;             ///< Specifies output layers of layer sets, 0: output all layers, 1: output highest layers, 2: specified by LayerIdsInDefOuputLayerSet
   IntAry1d               m_outputLayerSetIdx;                 ///< Indices of layer sets used as additional output layer sets  
-  IntAry2d m_layerIdsInAddOutputLayerSet; ///< LayerIds in vps of additional output layers
-  IntAry2d m_layerIdsInDefOutputLayerSet; ///< Indices in vps of output layers in layer sets
-  IntAry2d               m_profileTierLevelIdx;      ///< Indices of of profile, per layer in layer set
+  IntAry2d               m_layerIdsInAddOutputLayerSet;       ///< LayerIds in vps of additional output layers
+  IntAry2d               m_layerIdsInDefOutputLayerSet;       ///< Indices in vps of output layers in layer sets
+  IntAry2d               m_profileTierLevelIdx;               ///< Indices of of profile, per layer in layer set
   BoolAry1d              m_altOutputLayerFlag;                ///< Alt output layer flag
 
@@ -145,8 +228,20 @@
   UInt      m_FrameSkip;                                   ///< number of skipped frames from the beginning
   UInt      m_temporalSubsampleRatio;                         ///< temporal subsample ratio, 2 means code every two frames
-  Int       m_iSourceWidth;                                   ///< source width in pixel
-  Int       m_iSourceHeight;                                  ///< source height in pixel (when interlaced = field height)
+  
+#if NH_MV
+  IntAry1d       m_iSourceWidths   ;                                   ///< source width in pixel
+  IntAry1d       m_iSourceHeights  ;                                  ///< source height in pixel (when interlaced = field height)
+  IntAry1d       m_inputFileWidths ;                                 ///< width of image in input file  (this is equivalent to sourceWidth,  if sourceWidth  is not subsequently altered due to padding)
+  IntAry1d       m_inputFileHeights;                                ///< height of image in input file (this is equivalent to sourceHeight, if sourceHeight is not subsequently altered due to padding)
+
+  IntAry1d       m_iSourceHeightOrgs;                               ///< original source height in pixel (when interlaced = frame height)
+#else
+  Int       m_iSourceWidth   ;                                   ///< source width in pixel
+  Int       m_iSourceHeight  ;                                  ///< source height in pixel (when interlaced = field height)
+  Int       m_inputFileWidth ;                                 ///< width of image in input file  (this is equivalent to sourceWidth,  if sourceWidth  is not subsequently altered due to padding)
+  Int       m_inputFileHeight;                                ///< height of image in input file (this is equivalent to sourceHeight, if sourceHeight is not subsequently altered due to padding)
 
   Int       m_iSourceHeightOrg;                               ///< original source height in pixel (when interlaced = frame height)
+#endif
 
   Bool      m_isField;                                        ///< enable field coding
@@ -156,19 +251,37 @@
 
   Int       m_conformanceWindowMode;
+#if NH_MV
+  IntAry1d  m_confWinLefts  ;
+  IntAry1d  m_confWinRights ;
+  IntAry1d  m_confWinTops   ;
+  IntAry1d  m_confWinBottoms;
+#else
   Int       m_confWinLeft;
   Int       m_confWinRight;
   Int       m_confWinTop;
   Int       m_confWinBottom;
+#endif
   Int       m_framesToBeEncoded;                              ///< number of encoded frames
+#if NH_MV
+  IntAry2d  m_aiPads;                              ///< number of padded pixels for width and height
+#else
   Int       m_aiPad[2];                                       ///< number of padded pixels for width and height
+#endif
   Bool      m_AccessUnitDelimiter;                            ///< add Access Unit Delimiter NAL units
   InputColourSpaceConversion m_inputColourSpaceConvert;       ///< colour space conversion to apply to input video
   Bool      m_snrInternalColourSpace;                       ///< if true, then no colour space conversion is applied for snr calculation, otherwise inverse of input is applied.
   Bool      m_outputInternalColourSpace;                    ///< if true, then no colour space conversion is applied for reconstructed video, otherwise inverse of input is applied.
+#if NH_MV
+  std::vector<ChromaFormat> m_InputChromaFormatIDC;
+#else
   ChromaFormat m_InputChromaFormatIDC;
+#endif
 
   Bool      m_printMSEBasedSequencePSNR;
   Bool      m_printFrameMSE;
   Bool      m_printSequenceMSE;
+#if JVET_F0064_MSSSIM
+  Bool      m_printMSSSIM;
+#endif
   Bool      m_cabacZeroWordPaddingEnabled;
   Bool      m_bClipInputVideoToRec709Range;
@@ -178,12 +291,26 @@
 #if NH_MV
   std::vector< Profile::Name > m_profiles;
+  
+  std::vector<UIProfileName>   m_uiProfiles;
+
   std::vector< Level::Tier   > m_levelTier;
   std::vector< Level::Name   > m_level;
   std::vector< Bool          > m_inblFlag; 
+
+  IntAry1d                    m_bitDepthConstraints          ;
+  IntAry1d                    m_tmpConstraintChromaFormats   ;
+  std::vector< ChromaFormat > m_chromaFormatConstraints      ;
+  BoolAry1d                   m_intraConstraintFlags         ;
+  BoolAry1d                   m_onePictureOnlyConstraintFlags;
+  BoolAry1d                   m_lowerBitRateConstraintFlags  ;
+  BoolAry1d                   m_progressiveSourceFlags       ;
+  BoolAry1d                   m_interlacedSourceFlags        ;
+  BoolAry1d                   m_nonPackedConstraintFlags     ;
+  BoolAry1d                   m_frameOnlyConstraintFlags     ;
+
 #else
   Profile::Name m_profile;
   Level::Tier   m_levelTier;
   Level::Name   m_level;
-#endif
   UInt          m_bitDepthConstraint;
   ChromaFormat  m_chromaFormatConstraint;
@@ -191,8 +318,9 @@
   Bool          m_onePictureOnlyConstraintFlag;
   Bool          m_lowerBitRateConstraintFlag;
-  Bool m_progressiveSourceFlag;
-  Bool m_interlacedSourceFlag;
-  Bool m_nonPackedConstraintFlag;
-  Bool m_frameOnlyConstraintFlag;
+  Bool          m_progressiveSourceFlag;
+  Bool          m_interlacedSourceFlag;
+  Bool          m_nonPackedConstraintFlag;
+  Bool          m_frameOnlyConstraintFlag;
+#endif
 
   // coding structure
@@ -204,4 +332,7 @@
   Int       m_iDecodingRefreshType;                           ///< random access type
   Int       m_iGOPSize;                                       ///< GOP size of hierarchical structure
+#if JCTVC_Y0038_PARAMS
+  Bool      m_bReWriteParamSetsFlag;                          ///< Flag to enable rewriting of parameter sets at random access points
+#endif  
 #if NH_MV
   Int       m_extraRPSsMvc[MAX_NUM_LAYERS];                       ///< extra RPSs added to handle CRA for each layer
@@ -234,9 +365,21 @@
   // coding quality
 #if NH_MV
+#if JVET_E0059_FLOATING_POINT_QP_FIX
+  std::vector<Int>   m_qpIncrementAtSourceFrame;             ///< Optional source frame number at which all subsequent frames are to use an increased internal QP.
+#else
   std::vector<Double>  m_fQP;                                 ///< QP value of key-picture (floating point) for each layer
+#endif
   std::vector<Int>     m_iQP;                                 ///< QP value of key-picture (integer) for each layer
 #else
+#if JVET_E0059_FLOATING_POINT_QP_FIX
+  OptionalValue<UInt> m_qpIncrementAtSourceFrame;             ///< Optional source frame number at which all subsequent frames are to use an increased internal QP.
+#else
   Double    m_fQP;                                            ///< QP value of key-picture (floating point)
+#endif
   Int       m_iQP;                                            ///< QP value of key-picture (integer)
+#endif
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+  Int       m_intraQPOffset;                                  ///< QP offset for intra slice (integer)
+  Bool      m_lambdaFromQPEnable;                             ///< enable flag for QP:lambda fix
 #endif
   std::string m_dQPFileName;                                  ///< QP offset for each slice (initialized from external file)
@@ -254,9 +397,8 @@
   Int       m_cbQpOffset;                                     ///< Chroma Cb QP Offset (0:default)
   Int       m_crQpOffset;                                     ///< Chroma Cr QP Offset (0:default)
-
-#if W0038_CQP_ADJ
+  WCGChromaQPControl m_wcgChromaQpControl;                    ///< Wide-colour-gamut chroma QP control.
   UInt      m_sliceChromaQpOffsetPeriodicity;                 ///< Used in conjunction with Slice Cb/Cr QpOffsetIntraOrPeriodic. Use 0 (default) to disable periodic nature.
   Int       m_sliceChromaQpOffsetIntraOrPeriodic[2/*Cb,Cr*/]; ///< Chroma Cb QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
-#endif
+  LumaLevelToDeltaQPMapping m_lumaLevelToDeltaQPMapping;      ///< mapping from luma level to Delta QP.
 #if ADAPTIVE_QP_SELECTION
   Bool      m_bUseAdaptQpSelect;
@@ -282,5 +424,9 @@
   UInt      m_uiMaxCUHeight;                                  ///< max. CU height in pixel
   UInt      m_uiMaxCUDepth;                                   ///< max. CU depth (as specified by command line)
-  UInt      m_uiMaxTotalCUDepth;                              ///< max. total CU depth - includes depth of transform-block structure
+#if NH_MV
+  IntAry1d  m_uiMaxTotalCUDepth;                              ///< max. total CU depth - includes depth of transform-block structure  
+#else
+  UInt      m_uiMaxTotalCUDepth;                              ///< max. total CU depth - includes depth of transform-block structure  
+#endif
   UInt      m_uiLog2DiffMaxMinCodingBlockSize;                ///< difference between largest and smallest CU depth
 
@@ -293,13 +439,25 @@
 
   // coding tools (bit-depth)
+#if NH_MV
+  IntAry2d  m_inputBitDepths      ;         ///< bit-depth of input file
+  IntAry2d  m_outputBitDepths     ;         ///< bit-depth of output file
+  IntAry2d  m_MSBExtendedBitDepths;         ///< bit-depth of input samples after MSB extension
+  IntAry2d  m_internalBitDepths   ;         ///< bit-depth codec operates at (input/output files will be converted)
+#else
   Int       m_inputBitDepth   [MAX_NUM_CHANNEL_TYPE];         ///< bit-depth of input file
   Int       m_outputBitDepth  [MAX_NUM_CHANNEL_TYPE];         ///< bit-depth of output file
   Int       m_MSBExtendedBitDepth[MAX_NUM_CHANNEL_TYPE];      ///< bit-depth of input samples after MSB extension
   Int       m_internalBitDepth[MAX_NUM_CHANNEL_TYPE];         ///< bit-depth codec operates at (input/output files will be converted)
+#endif
+
   Bool      m_extendedPrecisionProcessingFlag;
   Bool      m_highPrecisionOffsetsEnabledFlag;
 
   //coding tools (chroma format)
+#if NH_MV
+  std::vector<ChromaFormat> m_chromaFormatIDCs;
+#else
   ChromaFormat m_chromaFormatIDC;
+#endif
 
   // coding tools (PCM bit-depth)
@@ -317,7 +475,5 @@
   Int       m_maxNumOffsetsPerPic;                            ///< SAO maximun number of offset per picture
   Bool      m_saoCtuBoundary;                                 ///< SAO parameter estimation using non-deblocked pixels for CTU bottom and right boundary areas
-#if OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP
   Bool      m_saoResetEncoderStateAfterIRAP;                  ///< When true, SAO encoder state will be reset following an IRAP.
-#endif
   // coding tools (loop filter)
 #if NH_MV
@@ -329,9 +485,5 @@
   Int       m_loopFilterBetaOffsetDiv2;                     ///< beta offset for deblocking filter
   Int       m_loopFilterTcOffsetDiv2;                       ///< tc offset for deblocking filter
-#if W0038_DB_OPT
   Int       m_deblockingFilterMetric;                         ///< blockiness metric in encoder
-#else
-  Bool      m_DeblockingFilterMetric;                         ///< blockiness metric in encoder
-#endif
   // coding tools (PCM)
   Bool      m_usePCM;                                         ///< flag for using IPCM
@@ -346,7 +498,5 @@
   Bool      m_useRDOQ;                                       ///< flag for using RD optimized quantization
   Bool      m_useRDOQTS;                                     ///< flag for using RD optimized quantization for transform skip
-#if T0196_SELECTIVE_RDOQ
   Bool      m_useSelectiveRDOQ;                               ///< flag for using selective RDOQ
-#endif
   Int       m_rdPenalty;                                      ///< RD-penalty for 32x32 TU for intra in non-intra slices (0: no RD-penalty, 1: RD-penalty, 2: maximum RD-penalty)
   Bool      m_bDisableIntraPUsInInterSlices;                  ///< Flag for disabling intra predicted PUs in inter slices.
@@ -437,4 +587,7 @@
   Bool      m_scalableNestingSEIEnabled;
   Bool      m_tmctsSEIEnabled;
+#if MCTS_ENC_CHECK
+  Bool      m_tmctsSEITileConstraint;
+#endif
   Bool      m_timeCodeSEIEnabled;
   Int       m_timeCodeSEINumTs;
@@ -451,7 +604,7 @@
   Int*      m_kneeSEIInputKneePoint;
   Int*      m_kneeSEIOutputKneePoint;
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
   Int       m_preferredTransferCharacteristics;
-#endif
+  UInt      m_greenMetadataType;
+  UInt      m_xsdMetricType;
 
   // weighted prediction
@@ -464,5 +617,5 @@
 
   Int       m_TMVPModeId;
-  Bool      m_signHideFlag;
+  Bool      m_signDataHidingEnabledFlag;
   Bool      m_RCEnableRateControl;                ///< enable rate control or not
   Int       m_RCTargetBitrate;                    ///< target bitrate when rate control is enabled
@@ -472,10 +625,7 @@
   Int       m_RCInitialQP;                        ///< inital QP for rate control
   Bool      m_RCForceIntraQP;                     ///< force all intra picture to use initial QP or not
-
-#if U0132_TARGET_BITS_SATURATION
   Bool      m_RCCpbSaturationEnabled;             ///< enable target bits saturation to avoid CPB overflow and underflow
   UInt      m_RCCpbSize;                          ///< CPB size
   Double    m_RCInitialCpbFullness;               ///< initial CPB fullness 
-#endif
 
 #if KWU_RC_VIEWRC_E0227
@@ -490,6 +640,6 @@
   std::string m_scalingListFileName;                          ///< quantization matrix file name
 
-  Bool      m_TransquantBypassEnableFlag;                     ///< transquant_bypass_enable_flag setting in PPS.
-  Bool      m_CUTransquantBypassFlagForce;                    ///< if transquant_bypass_enable_flag, then, if true, all CU transquant bypass flags will be set to true.
+  Bool      m_TransquantBypassEnabledFlag;                    ///< transquant_bypass_enabled_flag setting in PPS.
+  Bool      m_CUTransquantBypassFlagForce;                    ///< if transquant_bypass_enabled_flag, then, if true, all CU transquant bypass flags will be set to true.
   CostMode  m_costMode;                                       ///< Cost mode to use
 
@@ -537,4 +687,11 @@
   std::string m_summaryPicFilenameBase;                       ///< Base filename to use for producing summary picture output files. The actual filenames used will have I.txt, P.txt and B.txt appended.
   UInt        m_summaryVerboseness;                           ///< Specifies the level of the verboseness of the text output.
+
+#if EXTENSION_360_VIDEO
+  TExt360AppEncCfg m_ext360;
+  friend class TExt360AppEncCfg;
+  friend class TExt360AppEncTop;
+#endif
+
 #if NH_MV
   Bool              m_outputVpsInfo;
@@ -546,6 +703,7 @@
   Bool      m_depth420OutputFlag;                             ///< Output depth layers in 4:2:0 format
 #endif
+
+#if NH_3D || NH_3D_VSO
     // Camera parameters
-#if NH_3D || NH_3D_VSO
   TChar*    m_pchCameraParameterFile;                         ///< camera parameter file
   TAppComCamPara m_cCameraData;
@@ -578,9 +736,6 @@
 #if NH_3D
   Bool       m_useDLT;                                        ///< flag for using DLT
-#endif
-#if NH_3D_QTL
   Bool       m_bUseQTL;                                        ///< flag for using depth QuadTree Limitation
-#endif
-#if NH_3D
+
   BoolAry1d  m_ivMvPredFlag;
   BoolAry1d  m_ivMvScalingFlag;
@@ -601,7 +756,26 @@
   // internal member functions
   Void  xCheckParameter ();                                   ///< check validity of configuration values
-  Void  xPrintParameter ();                                   ///< print configuration values
+  Void  xPrintParameter ();                                   ///< print configuration values  
+ 
   Void  xPrintUsage     ();                                   ///< print usage
 #if NH_MV
+  Void xConfirmRepFormat( const TComVPS& vps);
+  Void xDeriveProfAndConstrFlags( const TComVPS& vps ); 
+  Void xCheckProfiles           ( const TComVPS& vps ); 
+
+  Void xPrintProfiles();
+
+  template< typename T >
+  Void xConfirmSingleRepFormat(Bool& checkFailed, std::string name, Int curLayer, Int refLayer, T valCur, T valRef )
+  {
+    if ( valCur != valRef )
+    {
+      printf("Error: %s of layer %d and its reference layer %d must be equal. \n", name.c_str(), curLayer, refLayer ); 
+      checkFailed = true; 
+    }
+  }
+
+  GOPEntry*  xGetGopEntries( Int layerIdInVps );
+  GOPEntry*  xGetGopEntry( Int layerIdInVps, Int poc );
 
   template<typename T>
@@ -697,4 +871,16 @@
   Bool  parseCfg  ( Int argc, TChar* argv[] );                ///< parse configuration file to fill member variables
 
+private:
+  Void   xConvertRepFormatParameters(
+    IntAry2d& tmpPad                       ,             
+    IntAry2d& tmpInputBitDepth             ,
+    IntAry2d& tmpOutputBitDepth            ,
+    IntAry2d& tmpMSBExtendedBitDepth       ,
+    IntAry2d& tmpInternalBitDepth          ,
+    IntAry1d& tmpInputChromaFormat         ,
+    IntAry1d& tmpChromaFormat
+    );
+
+  Void xGetMaxValuesOfApplicableLayers(const TComVPS& vps, Int vpsPtlIdx, Int& maxBitDepthLuma, Int& maxBitDepthChroma, ChromaFormat& maxChromaFormatIdc, Int& maxNumRefLayers);
 };// END CLASS DEFINITION TAppEncCfg
 
Index: /trunk/source/App/TAppEncoder/TAppEncTop.cpp
===================================================================
--- /trunk/source/App/TAppEncoder/TAppEncTop.cpp	(revision 1412)
+++ /trunk/source/App/TAppEncoder/TAppEncTop.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -47,4 +47,8 @@
 #include "TLibEncoder/AnnexBwrite.h"
 
+#if EXTENSION_360_VIDEO
+#include "TAppEncHelper360/TExt360AppEncTop.h"
+#endif
+
 using namespace std;
 
@@ -57,6 +61,9 @@
 
 TAppEncTop::TAppEncTop()
+#if NH_MV
+  : m_spsMap( MAX_NUM_SPS ),
+    m_ppsMap( MAX_NUM_PPS )
+#endif
 {
-
 #if NH_MV
   m_vps = new TComVPS; 
@@ -88,9 +95,5 @@
   
 #if NH_3D
-  vps.createCamPars(m_iNumberOfViews);  
-#endif
-
-#if NH_3D_DLT
-  TComDLT dlt = TComDLT();
+  vps.createCamPars(m_iNumberOfViews);    
 #endif
 
@@ -140,7 +143,7 @@
   xSetDimensionIdAndLength ( vps );
   xSetDependencies         ( vps );
-  xSetRepFormat            ( vps ); 
-  xSetProfileTierLevel     ( vps ); 
-  xSetLayerSets            ( vps ); 
+  xSetRepFormat            ( vps );   
+  xSetLayerSets            ( vps );   
+  xSetProfileTierLevel     ( vps );   
   xSetDpbSize              ( vps ); 
   xSetVPSVUI               ( vps ); 
@@ -151,7 +154,12 @@
   m_ivPicLists.setVPS      ( &vps );
 #endif
-#if NH_3D_DLT
+#if NH_3D
+  TComDLT dlt = TComDLT();
   xDeriveDltArray          ( vps, &dlt );
 #endif
+
+
+  xDeriveParameterSetIds( vps );
+
   if ( m_targetEncLayerIdList.size() == 0 )
   {
@@ -182,4 +190,5 @@
     vps.printLayerSets(); 
     vps.printPTL(); 
+    vps.printRepFormat();
   }
 
@@ -188,23 +197,23 @@
   for (Int d = 0; d < 2; d++)
   {  
-    m_sps3dExtension.setIvDiMcEnabledFlag          ( d, m_ivMvPredFlag[d]       );
-    m_sps3dExtension.setIvMvScalEnabledFlag       ( d, m_ivMvScalingFlag[d]    );
+    m_sps3dExtension.setIvDiMcEnabledFlag             ( d, m_ivMvPredFlag[d]       );
+    m_sps3dExtension.setIvMvScalEnabledFlag           ( d, m_ivMvScalingFlag[d]    );
     if (d == 0 )
     {    
-      m_sps3dExtension.setLog2IvmcSubPbSizeMinus3   ( d, m_log2SubPbSizeMinus3   );
-      m_sps3dExtension.setIvResPredEnabledFlag         ( d, m_ivResPredFlag         );
-      m_sps3dExtension.setDepthRefEnabledFlag   ( d, m_depthRefinementFlag   );
-      m_sps3dExtension.setVspMcEnabledFlag ( d, m_viewSynthesisPredFlag );
-      m_sps3dExtension.setDbbpEnabledFlag ( d, m_depthBasedBlkPartFlag );
+      m_sps3dExtension.setLog2IvmcSubPbSizeMinus3     ( d, m_log2SubPbSizeMinus3   );
+      m_sps3dExtension.setIvResPredEnabledFlag        ( d, m_ivResPredFlag         );
+      m_sps3dExtension.setDepthRefEnabledFlag         ( d, m_depthRefinementFlag   );
+      m_sps3dExtension.setVspMcEnabledFlag            ( d, m_viewSynthesisPredFlag );
+      m_sps3dExtension.setDbbpEnabledFlag             ( d, m_depthBasedBlkPartFlag );
     }
     else
     {    
-      m_sps3dExtension.setTexMcEnabledFlag               ( d, m_mpiFlag               );
-      m_sps3dExtension.setLog2TexmcSubPbSizeMinus3( d, m_log2MpiSubPbSizeMinus3);
-      m_sps3dExtension.setIntraContourEnabledFlag      ( d, m_intraContourFlag      );
-      m_sps3dExtension.setIntraDcOnlyWedgeEnabledFlag     ( d, m_intraSdcFlag || m_intraWedgeFlag     );
-      m_sps3dExtension.setCqtCuPartPredEnabledFlag            ( d, m_qtPredFlag            );
-      m_sps3dExtension.setInterDcOnlyEnabledFlag          ( d, m_interSdcFlag          );
-      m_sps3dExtension.setSkipIntraEnabledFlag    ( d, m_depthIntraSkipFlag    );  
+      m_sps3dExtension.setTexMcEnabledFlag            ( d, m_mpiFlag               );
+      m_sps3dExtension.setLog2TexmcSubPbSizeMinus3    ( d, m_log2MpiSubPbSizeMinus3);
+      m_sps3dExtension.setIntraContourEnabledFlag     ( d, m_intraContourFlag      );
+      m_sps3dExtension.setIntraDcOnlyWedgeEnabledFlag ( d, m_intraSdcFlag || m_intraWedgeFlag     );
+      m_sps3dExtension.setCqtCuPartPredEnabledFlag    ( d, m_qtPredFlag            );
+      m_sps3dExtension.setInterDcOnlyEnabledFlag      ( d, m_interSdcFlag          );
+      m_sps3dExtension.setSkipIntraEnabledFlag        ( d, m_depthIntraSkipFlag    );  
     }
   }
@@ -216,5 +225,9 @@
   {
     m_frameRcvd                 .push_back(0);
+#if NH_MV
+    m_acTEncTopList             .push_back(new TEncTop( m_spsMap, m_ppsMap ) ); 
+#else
     m_acTEncTopList             .push_back(new TEncTop); 
+#endif
     m_acTVideoIOYuvInputFileList.push_back(new TVideoIOYuv);
     m_acTVideoIOYuvReconFileList.push_back(new TVideoIOYuv);
@@ -261,16 +274,10 @@
   for(Int layerIdInVps = 0; layerIdInVps < m_numberOfLayers; layerIdInVps++)
   {
+    Int repFormatIdx = m_layerIdxInVpsToRepFormatIdx[layerIdInVps];
     m_cListPicYuvRec            .push_back(new TComList<TComPicYuv*>) ;
-
-#if !NH_MV
-    m_ivPicLists.push_back( m_acTEncTopList[ layerIdInVps ]->getListPic()  ); 
-#endif
-
     TEncTop& m_cTEncTop = *m_acTEncTopList[ layerIdInVps ];  // It is not a member, but this name helps avoiding code duplication !!!
 
     Int layerId = vps.getLayerIdInNuh          ( layerIdInVps );
-#if NH_MV
     m_ivPicLists.getSubDpb( layerId, true ); 
-#endif
 
     m_cTEncTop.setLayerIdInVps                 ( layerIdInVps ); 
@@ -278,4 +285,6 @@
     m_cTEncTop.setViewId                       ( vps.getViewId      (  layerId ) );
     m_cTEncTop.setViewIndex                    ( vps.getViewIndex   (  layerId ) );
+    m_cTEncTop.setSendParameterSets            ( m_sendParameterSets[ layerIdInVps ]  );
+    m_cTEncTop.setParameterSetId               ( m_parameterSetId   [ layerIdInVps ]  );
 #if NH_3D_VSO || NH_3D
     Bool isDepth    = ( vps.getDepthId     ( layerId ) != 0  ) ;
@@ -305,18 +314,13 @@
 #endif // H_3D_VSO
 #if NH_3D
-#if NH_3D_IC
     m_cTEncTop.setUseIC                        ( vps.getViewIndex( layerId ) == 0 || isDepth ? false : m_abUseIC );
     m_cTEncTop.setUseICLowLatencyEnc           ( m_bUseLowLatencyICEnc );
-#endif
-
-    
+
     m_cTEncTop.setUseDMM                       ( isDepth ? m_intraWedgeFlag   : false );
     m_cTEncTop.setUseSDC                       ( isDepth ? m_intraSdcFlag     : false );
     m_cTEncTop.setUseDLT                       ( isDepth ? m_useDLT   : false );
-#endif
-#if NH_3D_QTL
+
     m_cTEncTop.setUseQTL                       ( isDepth || isAuxDepth ? m_bUseQTL  : false );
-#endif
-#if NH_3D
+
     m_cTEncTop.setSps3dExtension               ( m_sps3dExtension );
 #endif // NH_3D
@@ -326,15 +330,31 @@
   m_cTEncTop.setVPS(&vps);
 
-#if NH_3D_DLT
+#if NH_3D
   m_cTEncTop.setDLT(dlt);
 #endif
 
 #if NH_MV
-  m_cTEncTop.setProfile                                           ( m_profiles[0]);
-  m_cTEncTop.setLevel                                             ( m_levelTier[0], m_level[0] );
+  // These values go to the SPS of the base layer only and should apply as follows:
+  //   If the profile_tier_level( ) syntax structure is included in an active SPS for the base layer 
+  //    or is the profile_tier_level( ) syntax structure VpsProfileTierLevel[ 0 ], 
+  //    it applies to the OLS containing all layers in the bitstream but with only the base layer being the output layer.
+  //   Otherwise, if the profile_tier_level( ) syntax structure is included in an active SPS 
+  //    for an independent non-base layer with nuh_layer_id equal to layerId, it applies to the output bitstream 
+  //    of the independent non-base layer rewriting process of clause F.10.2 with the input variables assignedBaseLayerId equal to layerId and tIdTarget equal to 6.
+
+  m_cTEncTop.setProfile                                           ( m_profiles[0]                       );
+  m_cTEncTop.setLevel                                             ( m_levelTier[0], m_level[0]          );
+  m_cTEncTop.setProgressiveSourceFlag                             ( m_progressiveSourceFlags        [0] );
+  m_cTEncTop.setInterlacedSourceFlag                              ( m_interlacedSourceFlags         [0] );
+  m_cTEncTop.setNonPackedConstraintFlag                           ( m_nonPackedConstraintFlags      [0] );
+  m_cTEncTop.setFrameOnlyConstraintFlag                           ( m_frameOnlyConstraintFlags      [0] );
+  m_cTEncTop.setBitDepthConstraintValue                           ( m_bitDepthConstraints           [0] );
+  m_cTEncTop.setChromaFormatConstraintValue                       ( m_chromaFormatConstraints       [0] );
+  m_cTEncTop.setIntraConstraintFlag                               ( m_intraConstraintFlags          [0] );
+  m_cTEncTop.setOnePictureOnlyConstraintFlag                      ( m_onePictureOnlyConstraintFlags [0] );
+  m_cTEncTop.setLowerBitRateConstraintFlag                        ( m_lowerBitRateConstraintFlags   [0] );
 #else
   m_cTEncTop.setProfile                                           ( m_profile);
   m_cTEncTop.setLevel                                             ( m_levelTier, m_level);
-#endif
   m_cTEncTop.setProgressiveSourceFlag                             ( m_progressiveSourceFlag);
   m_cTEncTop.setInterlacedSourceFlag                              ( m_interlacedSourceFlag);
@@ -347,7 +367,12 @@
   m_cTEncTop.setLowerBitRateConstraintFlag                        ( m_lowerBitRateConstraintFlag );
 
+#endif
+
   m_cTEncTop.setPrintMSEBasedSequencePSNR                         ( m_printMSEBasedSequencePSNR);
   m_cTEncTop.setPrintFrameMSE                                     ( m_printFrameMSE);
   m_cTEncTop.setPrintSequenceMSE                                  ( m_printSequenceMSE);
+#if JVET_F0064_MSSSIM
+  m_cTEncTop.setPrintMSSSIM                                       ( m_printMSSSIM );
+#endif
   m_cTEncTop.setCabacZeroWordPaddingEnabled                       ( m_cabacZeroWordPaddingEnabled );
 
@@ -355,7 +380,14 @@
   m_cTEncTop.setFrameSkip                                         ( m_FrameSkip );
   m_cTEncTop.setTemporalSubsampleRatio                            ( m_temporalSubsampleRatio );
+#if NH_MV
+  m_cTEncTop.setSourceWidth                                       ( m_iSourceWidths [repFormatIdx] );
+  m_cTEncTop.setSourceHeight                                      ( m_iSourceHeights[repFormatIdx] );
+
+  m_cTEncTop.setConformanceWindow                                 ( m_confWinLefts[repFormatIdx], m_confWinRights[repFormatIdx], m_confWinTops[repFormatIdx], m_confWinBottoms[repFormatIdx] );
+#else
   m_cTEncTop.setSourceWidth                                       ( m_iSourceWidth );
   m_cTEncTop.setSourceHeight                                      ( m_iSourceHeight );
   m_cTEncTop.setConformanceWindow                                 ( m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom );
+#endif
   m_cTEncTop.setFramesToBeEncoded                                 ( m_framesToBeEncoded );
 
@@ -368,6 +400,9 @@
   m_cTEncTop.setDecodingRefreshType                               ( m_iDecodingRefreshType );
   m_cTEncTop.setGOPSize                                           ( m_iGOPSize );
-#if NH_MV
-  m_cTEncTop.setGopList                                           ( m_GOPListMvc[layerIdInVps] );
+#if JCTVC_Y0038_PARAMS
+  m_cTEncTop.setReWriteParamSetsFlag                              ( m_bReWriteParamSetsFlag );
+#endif
+#if NH_MV
+  m_cTEncTop.setGopList                                           ( xGetGopEntries(layerIdInVps) );
   m_cTEncTop.setExtraRPSs                                         ( m_extraRPSsMvc[layerIdInVps] );
   for(Int i = 0; i < MAX_TLAYER; i++)
@@ -398,5 +433,14 @@
 #endif
 
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+  m_cTEncTop.setIntraQPOffset                                     ( m_intraQPOffset );
+  m_cTEncTop.setLambdaFromQPEnable                                ( m_lambdaFromQPEnable );
+#endif
+#if NH_MV
+  m_cTEncTop.setPad                                               ( &m_aiPads[ repFormatIdx ][0] );
+#else
   m_cTEncTop.setPad                                               ( m_aiPad );
+#endif
+
   m_cTEncTop.setAccessUnitDelimiter                               ( m_AccessUnitDelimiter );
 #if NH_MV
@@ -418,9 +462,5 @@
   m_cTEncTop.setLoopFilterBetaOffset                              ( m_loopFilterBetaOffsetDiv2  );
   m_cTEncTop.setLoopFilterTcOffset                                ( m_loopFilterTcOffsetDiv2    );
-#if W0038_DB_OPT
   m_cTEncTop.setDeblockingFilterMetric                            ( m_deblockingFilterMetric );
-#else
-  m_cTEncTop.setDeblockingFilterMetric                            ( m_DeblockingFilterMetric );
-#endif
 
   //====== Motion search ========
@@ -444,10 +484,9 @@
   m_cTEncTop.setChromaCbQpOffset                                  ( m_cbQpOffset     );
   m_cTEncTop.setChromaCrQpOffset                                  ( m_crQpOffset  );
-#if W0038_CQP_ADJ
+  m_cTEncTop.setWCGChromaQpControl                                ( m_wcgChromaQpControl );
   m_cTEncTop.setSliceChromaOffsetQpIntraOrPeriodic                ( m_sliceChromaQpOffsetPeriodicity, m_sliceChromaQpOffsetIntraOrPeriodic );
-#endif
-
-#if NH_3D
-  m_cTEncTop.setChromaFormatIdc                                   ( isDepth ? CHROMA_400 : m_chromaFormatIDC );
+
+#if NH_MV
+  m_cTEncTop.setChromaFormatIdc                                   ( m_chromaFormatIDCs[ repFormatIdx ] );
 #else
   m_cTEncTop.setChromaFormatIdc                                   ( m_chromaFormatIDC  );
@@ -466,5 +505,10 @@
 
   //====== Tool list ========
+  m_cTEncTop.setLumaLevelToDeltaQPControls                        ( m_lumaLevelToDeltaQPMapping );
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+  m_cTEncTop.setDeltaQpRD( (m_costMode==COST_LOSSLESS_CODING) ? 0 : m_uiDeltaQpRD );
+#else
   m_cTEncTop.setDeltaQpRD                                         ( m_uiDeltaQpRD  );
+#endif
   m_cTEncTop.setFastDeltaQp                                       ( m_bFastDeltaQP  );
   m_cTEncTop.setUseASR                                            ( m_bUseASR      );
@@ -477,11 +521,13 @@
   m_cTEncTop.setUseRDOQ                                           ( m_useRDOQ     );
   m_cTEncTop.setUseRDOQTS                                         ( m_useRDOQTS   );
-#if T0196_SELECTIVE_RDOQ
   m_cTEncTop.setUseSelectiveRDOQ                                  ( m_useSelectiveRDOQ );
-#endif
   m_cTEncTop.setRDpenalty                                         ( m_rdPenalty );
   m_cTEncTop.setMaxCUWidth                                        ( m_uiMaxCUWidth );
   m_cTEncTop.setMaxCUHeight                                       ( m_uiMaxCUHeight );
+#if NH_MV
+  m_cTEncTop.setMaxTotalCUDepth                                   ( m_uiMaxTotalCUDepth[ repFormatIdx] );
+#else
   m_cTEncTop.setMaxTotalCUDepth                                   ( m_uiMaxTotalCUDepth );
+#endif
   m_cTEncTop.setLog2DiffMaxMinCodingBlockSize                     ( m_uiLog2DiffMaxMinCodingBlockSize );
   m_cTEncTop.setQuadtreeTULog2MaxSize                             ( m_uiQuadtreeTULog2MaxSize );
@@ -524,6 +570,11 @@
   for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
   {
+#if NH_MV
+    m_cTEncTop.setBitDepth((ChannelType)channelType, m_internalBitDepths[repFormatIdx][channelType]);
+    m_cTEncTop.setPCMBitDepth((ChannelType)channelType, m_bPCMInputBitDepthFlag ? m_MSBExtendedBitDepths[repFormatIdx][channelType] : m_internalBitDepths[repFormatIdx][channelType]);
+#else
     m_cTEncTop.setBitDepth((ChannelType)channelType, m_internalBitDepth[channelType]);
     m_cTEncTop.setPCMBitDepth((ChannelType)channelType, m_bPCMInputBitDepthFlag ? m_MSBExtendedBitDepth[channelType] : m_internalBitDepth[channelType]);
+#endif
   }
 
@@ -562,7 +613,5 @@
 
   m_cTEncTop.setSaoCtuBoundary                                    ( m_saoCtuBoundary);
-#if OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP
   m_cTEncTop.setSaoResetEncoderStateAfterIRAP                     ( m_saoResetEncoderStateAfterIRAP);
-#endif
   m_cTEncTop.setPCMInputBitDepthFlag                              ( m_bPCMInputBitDepthFlag);
   m_cTEncTop.setPCMFilterDisableFlag                              ( m_bPCMFilterDisableFlag);
@@ -620,4 +669,7 @@
   m_cTEncTop.setScalableNestingSEIEnabled                         ( m_scalableNestingSEIEnabled );
   m_cTEncTop.setTMCTSSEIEnabled                                   ( m_tmctsSEIEnabled );
+#if MCTS_ENC_CHECK
+  m_cTEncTop.setTMCTSSEITileConstraint                            ( m_tmctsSEITileConstraint );
+#endif
   m_cTEncTop.setTimeCodeSEIEnabled                                ( m_timeCodeSEIEnabled );
   m_cTEncTop.setNumberOfTimeSets                                  ( m_timeCodeSEINumTs );
@@ -639,9 +691,9 @@
   m_cTEncTop.setColourRemapInfoSEIFileRoot                        ( m_colourRemapSEIFileRoot );
   m_cTEncTop.setMasteringDisplaySEI                               ( m_masteringDisplay );
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
   m_cTEncTop.setSEIAlternativeTransferCharacteristicsSEIEnable    ( m_preferredTransferCharacteristics>=0     );
   m_cTEncTop.setSEIPreferredTransferCharacteristics               ( UChar(m_preferredTransferCharacteristics) );
-#endif
-
+  m_cTEncTop.setSEIGreenMetadataInfoSEIEnable                     ( m_greenMetadataType > 0 );
+  m_cTEncTop.setSEIGreenMetadataType                              ( UChar(m_greenMetadataType) );
+  m_cTEncTop.setSEIXSDMetricType                                  ( UChar(m_xsdMetricType) );
 #if NH_MV
   m_cTEncTop.setSeiMessages                                       ( &m_seiMessages ); 
@@ -667,5 +719,6 @@
   m_cTEncTop.setUseScalingListId                                  ( m_useScalingListId  );
   m_cTEncTop.setScalingListFileName                               ( m_scalingListFileName );
-  m_cTEncTop.setSignHideFlag                                      ( m_signHideFlag);
+  m_cTEncTop.setSignDataHidingEnabledFlag                         ( m_signDataHidingEnabledFlag);
+
 #if KWU_RC_VIEWRC_E0227 || KWU_RC_MADPRED_E0227
   if(!m_cTEncTop.getIsDepth())    //only for texture
@@ -688,9 +741,7 @@
   m_cTEncTop.setInitialQP                                         ( m_RCInitialQP );
   m_cTEncTop.setForceIntraQP                                      ( m_RCForceIntraQP );
-#if U0132_TARGET_BITS_SATURATION
   m_cTEncTop.setCpbSaturationEnabled                              ( m_RCCpbSaturationEnabled );
   m_cTEncTop.setCpbSize                                           ( m_RCCpbSize );
   m_cTEncTop.setInitialCpbFullness                                ( m_RCInitialCpbFullness );
-#endif
 
 #if KWU_RC_MADPRED_E0227
@@ -761,5 +812,5 @@
   }
 #endif
-  m_cTEncTop.setTransquantBypassEnableFlag                        ( m_TransquantBypassEnableFlag );
+  m_cTEncTop.setTransquantBypassEnabledFlag                       ( m_TransquantBypassEnabledFlag );
   m_cTEncTop.setCUTransquantBypassFlagForceValue                  ( m_CUTransquantBypassFlagForce );
   m_cTEncTop.setCostMode                                          ( m_costMode );
@@ -812,8 +863,18 @@
     if ( m_uiVSOMode == 4 )
     {
+
+      for( Int i = 1; i < m_numRepFormats; i++)
+      {
+        if ( m_iSourceWidths[0] != m_iSourceWidths[i] || m_iSourceHeights[0] != m_iSourceHeights[i] )
+        {
+          std::cout << "Enabling the RM requires equal size of all layers." << std::endl;
+          AOF( false );
+        }
+      }
+
 #if H_3D_VSO_EARLY_SKIP
-      m_cRendererModel.create( m_cRenModStrParser.getNumOfBaseViews(), m_cRenModStrParser.getNumOfModels(), m_iSourceWidth, m_uiMaxCUHeight , LOG2_DISP_PREC_LUT, 0, true, m_bVSOEarlySkip );
-#else
-      m_cRendererModel.create( m_cRenModStrParser.getNumOfBaseViews(), m_cRenModStrParser.getNumOfModels(), m_iSourceWidth, m_uiMaxCUHeight , LOG2_DISP_PREC_LUT, 0 , true);
+      m_cRendererModel.create( m_cRenModStrParser.getNumOfBaseViews(), m_cRenModStrParser.getNumOfModels(), m_iSourceWidths[0], m_uiMaxCUHeight , LOG2_DISP_PREC_LUT, 0, true, m_bVSOEarlySkip );
+#else
+      m_cRendererModel.create( m_cRenModStrParser.getNumOfBaseViews(), m_cRenModStrParser.getNumOfModels(), m_iSourceWidths[0], m_uiMaxCUHeight , LOG2_DISP_PREC_LUT, 0 , true);
 #endif
       for ( Int layer = 0; layer < m_numberOfLayers ; layer++ )
@@ -851,5 +912,5 @@
   // initialize global variables
   initROM();
-#if NH_3D_DMM
+#if NH_3D
   initWedgeLists( true );
 #endif
@@ -857,10 +918,11 @@
   for( Int layer=0; layer < m_numberOfLayers; layer++)
   {
-    m_acTVideoIOYuvInputFileList[layer]->open( m_pchInputFileList[layer],     false, m_inputBitDepth, m_MSBExtendedBitDepth, m_internalBitDepth );  // read  mode
-    m_acTVideoIOYuvInputFileList[layer]->skipFrames( m_FrameSkip, m_iSourceWidth - m_aiPad[0], m_iSourceHeight - m_aiPad[1], m_InputChromaFormatIDC);
+    Int repFormatIdx = m_layerIdxInVpsToRepFormatIdx[layer];
+    m_acTVideoIOYuvInputFileList[layer]->open( m_pchInputFileList[layer],     false, &m_inputBitDepths[repFormatIdx][0], &m_MSBExtendedBitDepths[repFormatIdx][0], &m_internalBitDepths[repFormatIdx][0] );  // read  mode
+    m_acTVideoIOYuvInputFileList[layer]->skipFrames( m_FrameSkip, m_iSourceWidths[repFormatIdx] - m_aiPads[repFormatIdx][0], m_iSourceHeights[repFormatIdx] - m_aiPads[repFormatIdx][1], m_InputChromaFormatIDC[repFormatIdx]);
 
     if (m_pchReconFileList[layer])
     {
-      m_acTVideoIOYuvReconFileList[layer]->open( m_pchReconFileList[layer], true, m_outputBitDepth, m_outputBitDepth, m_internalBitDepth);  // write mode
+      m_acTVideoIOYuvReconFileList[layer]->open( m_pchReconFileList[layer], true, &m_outputBitDepths[repFormatIdx][0], &m_outputBitDepths[repFormatIdx][0], &m_internalBitDepths[repFormatIdx][0]);  // write mode
     }
     m_acTEncTopList[layer]->create();
@@ -869,5 +931,5 @@
   // Video I/O
   m_cTVideoIOYuvInputFile.open( m_inputFileName,     false, m_inputBitDepth, m_MSBExtendedBitDepth, m_internalBitDepth );  // read  mode
-  m_cTVideoIOYuvInputFile.skipFrames(m_FrameSkip, m_iSourceWidth - m_aiPad[0], m_iSourceHeight - m_aiPad[1], m_InputChromaFormatIDC);
+  m_cTVideoIOYuvInputFile.skipFrames(m_FrameSkip, m_inputFileWidth, m_inputFileHeight, m_InputChromaFormatIDC);
 
   if (!m_reconFileName.empty())
@@ -949,5 +1011,5 @@
   }
 
-#if !NH_3D
+#if !NH_MV
   TComPicYuv*       pcPicYuvOrg = new TComPicYuv;
 #endif
@@ -958,6 +1020,7 @@
   xCreateLib();
   xInitLib(m_isField);
-
+#if NH_MV
   printChromaFormat();
+#endif
 
   // main encoder loop
@@ -985,12 +1048,12 @@
   list<AccessUnit> outputAccessUnits; ///< list of access units to write out.  is populated by the encoding process
   
-#if NH_3D
-  TComPicYuv* picYuvOrg[2]; 
-  TComPicYuv  picYuvTrueOrg[2]; 
-  for (Int d = 0; d < 2 ; d++)
-  {
+#if NH_MV
+  std::vector<TComPicYuv*> picYuvOrg    ( m_numRepFormats ); 
+  std::vector<TComPicYuv > picYuvTrueOrg( m_numRepFormats ); 
+  for (Int d = 0; d < m_numRepFormats ; d++)
+  { 
     picYuvOrg[d] = new TComPicYuv;
-    picYuvOrg[d]   ->create( m_iSourceWidth, m_isField ? m_iSourceHeightOrg : m_iSourceHeight, ( d > 0 ) ? CHROMA_400 : m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth, true );
-    picYuvTrueOrg[d].create( m_iSourceWidth, m_isField ? m_iSourceHeightOrg : m_iSourceHeight, ( d > 0 ) ? CHROMA_400 : m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth, true );
+    picYuvOrg[d]   ->create( m_iSourceWidths[d], m_isField ? m_iSourceHeightOrgs[d] : m_iSourceHeights[d], m_chromaFormatIDCs[d], m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth[d], true );
+    picYuvTrueOrg[d].create( m_iSourceWidths[d], m_isField ? m_iSourceHeightOrgs[d] : m_iSourceHeights[d], m_chromaFormatIDCs[d], m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth[d], true );
   }
 #else
@@ -1009,4 +1072,10 @@
   }
 #endif
+
+
+#if EXTENSION_360_VIDEO
+  TExt360AppEncTop           ext360(*this, m_cTEncTop.getGOPEncoder()->getExt360Data(), *(m_cTEncTop.getGOPEncoder()), *pcPicYuvOrg);
+#endif
+
 #if NH_MV
   while ( (m_targetEncLayerIdList.size() != 0 ) && !allEos )
@@ -1014,8 +1083,9 @@
     for(Int layer=0; layer < m_numberOfLayers; layer++ )
     {
-#if NH_3D
-      TComPicYuv* pcPicYuvOrg    =  picYuvOrg    [ m_depthFlag[layer] ];
-      TComPicYuv& cPicYuvTrueOrg =  picYuvTrueOrg[ m_depthFlag[layer] ];
-#endif
+      Int repFormatIdx = m_layerIdxInVpsToRepFormatIdx[layer];
+
+      TComPicYuv* pcPicYuvOrg    =  picYuvOrg    [ repFormatIdx ];
+      TComPicYuv& cPicYuvTrueOrg =  picYuvTrueOrg[ repFormatIdx ];
+
       if (!xLayerIdInTargetEncLayerIdList( m_vps->getLayerIdInNuh( layer ) ))
       {
@@ -1030,5 +1100,5 @@
 
         // read input YUV file        
-        m_acTVideoIOYuvInputFileList[layer]->read      ( pcPicYuvOrg, &cPicYuvTrueOrg, ipCSC, m_aiPad, m_InputChromaFormatIDC );
+        m_acTVideoIOYuvInputFileList[layer]->read      ( pcPicYuvOrg, &cPicYuvTrueOrg, ipCSC, &m_aiPads[repFormatIdx][0], m_InputChromaFormatIDC[repFormatIdx] );
         m_acTEncTopList             [layer]->initNewPic( pcPicYuvOrg );
 
@@ -1062,7 +1132,8 @@
       for(Int layer=0; layer < m_numberOfLayers; layer++ )
       {
-#if NH_3D
-        TComPicYuv* pcPicYuvOrg    =  picYuvOrg    [ m_depthFlag[layer] ];
-        TComPicYuv& cPicYuvTrueOrg =  picYuvTrueOrg[ m_depthFlag[layer] ];
+        Int repFormatIdx = m_layerIdxInVpsToRepFormatIdx[layer];
+#if NH_MV
+        TComPicYuv* pcPicYuvOrg    =  picYuvOrg    [ repFormatIdx ];
+        TComPicYuv& cPicYuvTrueOrg =  picYuvTrueOrg[ repFormatIdx ];
 #endif
         if (!xLayerIdInTargetEncLayerIdList( m_vps->getLayerIdInNuh( layer ) ))
@@ -1104,7 +1175,17 @@
     // get buffers
     xGetBuffer(pcPicYuvRec);
-
     // read input YUV file
+#if EXTENSION_360_VIDEO
+    if (ext360.isEnabled())
+    {
+      ext360.read(m_cTVideoIOYuvInputFile, *pcPicYuvOrg, cPicYuvTrueOrg, ipCSC);
+    }
+    else
+    {
+      m_cTVideoIOYuvInputFile.read( pcPicYuvOrg, &cPicYuvTrueOrg, ipCSC, m_aiPad, m_InputChromaFormatIDC, m_bClipInputVideoToRec709Range );
+    }
+#else
     m_cTVideoIOYuvInputFile.read( pcPicYuvOrg, &cPicYuvTrueOrg, ipCSC, m_aiPad, m_InputChromaFormatIDC, m_bClipInputVideoToRec709Range );
+#endif
 
     // increase number of received frames
@@ -1142,5 +1223,5 @@
     if( m_temporalSubsampleRatio > 1 )
     {
-      m_cTVideoIOYuvInputFile.skipFrames(m_temporalSubsampleRatio-1, m_iSourceWidth - m_aiPad[0], m_iSourceHeight - m_aiPad[1], m_InputChromaFormatIDC);
+      m_cTVideoIOYuvInputFile.skipFrames(m_temporalSubsampleRatio-1, m_inputFileWidth, m_inputFileHeight, m_InputChromaFormatIDC);
     }
   }
@@ -1149,7 +1230,7 @@
 #endif
 
-#if NH_3D
+#if NH_MV
   // delete original YUV buffer
-  for (Int d = 0; d < 2; d++)
+  for (Int d = 0; d < m_numRepFormats; d++)
   {
     picYuvOrg[d]->destroy();
@@ -1169,6 +1250,4 @@
   // delete used buffers in encoder class
   m_cTEncTop.deletePicBuffer();
-#endif
-#if !NH_3D
   cPicYuvTrueOrg.destroy();
 #endif
@@ -1212,4 +1291,6 @@
   // org. buffer
 #if NH_MV
+  Int repFormatIdx = m_layerIdxInVpsToRepFormatIdx[layer];
+
   if ( m_cListPicYuvRec[layer]->size() == (UInt)m_iGOPSize )
   {
@@ -1224,6 +1305,6 @@
   {
     rpcPicYuvRec = new TComPicYuv;
-#if NH_3D
-    rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, m_depthFlag[layer] > 0 ? CHROMA_400 : m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth, true );
+#if NH_MV
+    rpcPicYuvRec->create( m_iSourceWidths[ repFormatIdx ], m_iSourceHeights[ repFormatIdx ], m_chromaFormatIDCs[ repFormatIdx ], m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth[repFormatIdx], true );
 #else
     rpcPicYuvRec->create( m_iSourceWidth, m_iSourceHeight, m_chromaFormatIDC, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth, true );
@@ -1306,8 +1387,9 @@
       if (m_pchReconFileList[layerIdx])
       {
+        Int repFormatIdx = m_layerIdxInVpsToRepFormatIdx[layerIdx];
 #if NH_3D
-        m_acTVideoIOYuvReconFileList[layerIdx]->write( pcPicYuvRecTop, pcPicYuvRecBottom, ipCSC, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, m_depth420OutputFlag && m_depthFlag[layerIdx ] ? CHROMA_420 : NUM_CHROMA_FORMAT, m_isTopFieldFirst );
-#else
-        m_acTVideoIOYuvReconFileList[layerIdx]->write( pcPicYuvRecTop, pcPicYuvRecBottom, ipCSC, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, NUM_CHROMA_FORMAT, m_isTopFieldFirst );
+        m_acTVideoIOYuvReconFileList[layerIdx]->write( pcPicYuvRecTop, pcPicYuvRecBottom, ipCSC, m_confWinLefts[repFormatIdx], m_confWinRights[repFormatIdx], m_confWinTops[repFormatIdx], m_confWinBottoms[repFormatIdx], m_depth420OutputFlag && m_depthFlag[layerIdx ] ? CHROMA_420 : NUM_CHROMA_FORMAT, m_isTopFieldFirst );
+#else
+        m_acTVideoIOYuvReconFileList[layerIdx]->write( pcPicYuvRecTop, pcPicYuvRecBottom, ipCSC, m_confWinLefts[repFormatIdx], m_confWinRights[repFormatIdx], m_confWinTops[repFormatIdx], m_confWinBottoms[repFormatIdx], NUM_CHROMA_FORMAT, m_isTopFieldFirst );
 #endif
       }
@@ -1361,10 +1443,11 @@
       TComPicYuv*  pcPicYuvRec  = *(iterPicYuvRec++);
 #if NH_MV
+      Int repFormatIdx = m_layerIdxInVpsToRepFormatIdx[layerIdx];
       if (m_pchReconFileList[layerIdx])
       {
 #if NH_3D
-        m_acTVideoIOYuvReconFileList[layerIdx]->write( pcPicYuvRec, ipCSC, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom, m_depth420OutputFlag && m_depthFlag[layerIdx ] ? CHROMA_420 : NUM_CHROMA_FORMAT  );
-#else
-        m_acTVideoIOYuvReconFileList[layerIdx]->write( pcPicYuvRec, ipCSC, m_confWinLeft, m_confWinRight, m_confWinTop, m_confWinBottom );
+        m_acTVideoIOYuvReconFileList[layerIdx]->write( pcPicYuvRec, ipCSC, m_confWinLefts[repFormatIdx], m_confWinRights[repFormatIdx], m_confWinTops[repFormatIdx], m_confWinBottoms[repFormatIdx], m_depth420OutputFlag && m_depthFlag[layerIdx ] ? CHROMA_420 : NUM_CHROMA_FORMAT  );
+#else
+        m_acTVideoIOYuvReconFileList[layerIdx]->write( pcPicYuvRec, ipCSC, m_confWinLefts[repFormatIdx], m_confWinRights[repFormatIdx], m_confWinTops[repFormatIdx], m_confWinBottoms[repFormatIdx] );
 #endif
 
@@ -1454,6 +1537,16 @@
 Void TAppEncTop::printChromaFormat()
 {
+  
+#if NH_MV    
+  std::cout << "Input ChromaFormatIDC             : ";
+  for (Int i = 0; i < m_numRepFormats; i++)
+  {
+    
+    
+    switch (m_InputChromaFormatIDC[i])
+#else
   std::cout << std::setw(43) << "Input ChromaFormatIDC = ";
   switch (m_InputChromaFormatIDC)
+#endif
   {
   case CHROMA_400:  std::cout << "  4:0:0"; break;
@@ -1465,11 +1558,17 @@
     exit(1);
   }
+#if NH_MV
+  std::cout << " ";
+}
+#endif
+
   std::cout << std::endl;
 
 #if NH_MV
-  for (Int i = 0; i < m_numberOfLayers; i++)
-  {
-    std::cout << "Layer " << i << std::setw( 43 - (i > 9 ? 6 : 7) ) << "Internal ChromaFormatIDC = ";
-    switch (m_acTEncTopList[i]->getChromaFormatIdc())
+  std::cout << "Output (internal) ChromaFormatIDC : ";
+  for (Int i = 0; i < m_numRepFormats; i++)
+  {
+    
+    switch ( m_chromaFormatIDCs[i] )
 #else
     std::cout << std::setw(43) << "Output (internal) ChromaFormatIDC = ";
@@ -1486,5 +1585,5 @@
     }
 #if NH_MV
-    std::cout << std::endl;
+    std::cout << " ";
   }
 #endif
@@ -1492,20 +1591,22 @@
 }
 
-#if NH_3D_DLT
+#if NH_3D
 Void TAppEncTop::xAnalyzeInputBaseDepth(UInt layer, UInt uiNumFrames, TComVPS* vps, TComDLT* dlt)
 {
+  Int repFormatIdx = m_layerIdxInVpsToRepFormatIdx[layer];
+
   TComPicYuv*       pcDepthPicYuvOrg = new TComPicYuv;
   TComPicYuv*       pcDepthPicYuvTrueOrg = new TComPicYuv;
   // allocate original YUV buffer
-  pcDepthPicYuvOrg->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth, false );
-  pcDepthPicYuvTrueOrg->create( m_iSourceWidth, m_iSourceHeight, CHROMA_420, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth, false );
+  pcDepthPicYuvOrg->create( m_iSourceWidths[ repFormatIdx ], m_iSourceHeights[ repFormatIdx ], CHROMA_420, m_uiMaxCUWidth, m_uiMaxCUHeight    , m_uiMaxTotalCUDepth[repFormatIdx], false );
+  pcDepthPicYuvTrueOrg->create( m_iSourceWidths[ repFormatIdx ], m_iSourceHeights[ repFormatIdx ], CHROMA_420, m_uiMaxCUWidth, m_uiMaxCUHeight, m_uiMaxTotalCUDepth[repFormatIdx], false );
   
   TVideoIOYuv* depthVideoFile = new TVideoIOYuv;
   
-  UInt uiMaxDepthValue = ((1 << m_inputBitDepth[CHANNEL_TYPE_LUMA])-1);
+  UInt uiMaxDepthValue = ((1 << m_inputBitDepths[repFormatIdx][CHANNEL_TYPE_LUMA])-1);
   
   std::vector<Bool> abValidDepths(256, false);
   
-  depthVideoFile->open( m_pchInputFileList[layer], false, m_inputBitDepth, m_MSBExtendedBitDepth, m_internalBitDepth );
+  depthVideoFile->open( m_pchInputFileList[layer], false, &m_inputBitDepths[repFormatIdx][0], &m_MSBExtendedBitDepths[repFormatIdx][0], &m_internalBitDepths[repFormatIdx][0] );
   
   Int iHeight   = pcDepthPicYuvOrg->getHeight(COMPONENT_Y);
@@ -1515,7 +1616,8 @@
   Pel* pInDM    = pcDepthPicYuvOrg->getAddr(COMPONENT_Y);
   
+  
   for(Int uiFrame=0; uiFrame < uiNumFrames; uiFrame++ )
   {
-    depthVideoFile->read( pcDepthPicYuvOrg, pcDepthPicYuvTrueOrg, IPCOLOURSPACE_UNCHANGED, m_aiPad, m_InputChromaFormatIDC, m_bClipInputVideoToRec709Range );
+    depthVideoFile->read( pcDepthPicYuvOrg, pcDepthPicYuvTrueOrg, IPCOLOURSPACE_UNCHANGED, &m_aiPads[repFormatIdx][0], m_InputChromaFormatIDC[repFormatIdx], m_bClipInputVideoToRec709Range );
     
     // check all pixel values
@@ -1551,5 +1653,5 @@
   }
   
-  if( uiNumFrames == 0 || gCeilLog2(iNumDepthValues) == m_inputBitDepth[CHANNEL_TYPE_LUMA] )
+  if( uiNumFrames == 0 || gCeilLog2(iNumDepthValues) == m_inputBitDepths[repFormatIdx][CHANNEL_TYPE_LUMA] )
   {
     dlt->setUseDLTFlag(layer, false);
@@ -1653,5 +1755,5 @@
     for( Int i = 0; i < getGOPSize(); i++ ) 
     {
-      GOPEntry geCur =  m_GOPListMvc[curLayerIdInVps][i];
+      GOPEntry geCur =  xGetGopEntries(curLayerIdInVps)[i];
       curSubLayersMaxMinus1 = std::max( curSubLayersMaxMinus1, geCur.m_temporalId ); 
     }  
@@ -1679,6 +1781,6 @@
           for( Int i = 0; i < ( getGOPSize() + 1); i++ ) 
           {        
-            GOPEntry geCur =  m_GOPListMvc[curLayerIdInVps][( i < getGOPSize()  ? i : MAX_GOP )];
-            GOPEntry geRef =  m_GOPListMvc[refLayerIdInVps][( i < getGOPSize()  ? i : MAX_GOP )];
+            GOPEntry geCur =  xGetGopEntries(curLayerIdInVps)[( i < getGOPSize()  ? i : MAX_GOP )];
+            GOPEntry geRef =  xGetGopEntries(refLayerIdInVps)[( i < getGOPSize()  ? i : MAX_GOP )];
             for (Int j = 0; j < geCur.m_numActiveRefLayerPics; j++)
             {
@@ -1705,6 +1807,6 @@
               for( Int i = 0; i < ( getGOPSize() + 1); i++ ) 
               {        
-                GOPEntry geCur =  m_GOPListMvc[curLayerIdInVps][( i < getGOPSize()  ? i : MAX_GOP )];
-                GOPEntry geRef =  m_GOPListMvc[refLayerIdInVps][( i < getGOPSize()  ? i : MAX_GOP )];
+                GOPEntry geCur =  xGetGopEntries(curLayerIdInVps)[( i < getGOPSize()  ? i : MAX_GOP )];
+                GOPEntry geRef =  xGetGopEntries(refLayerIdInVps)[( i < getGOPSize()  ? i : MAX_GOP )];
                 if ( geCur.m_interCompPredFlag )
                 {
@@ -1719,6 +1821,6 @@
             for( Int i = 0; i < ( getGOPSize() + 1); i++ ) 
             {        
-              GOPEntry geCur =  m_GOPListMvc[curLayerIdInVps][( i < getGOPSize()  ? i : MAX_GOP )];
-              GOPEntry geRef =  m_GOPListMvc[refLayerIdInVps][( i < getGOPSize()  ? i : MAX_GOP )];
+              GOPEntry geCur =  xGetGopEntries(curLayerIdInVps)[( i < getGOPSize()  ? i : MAX_GOP )];
+              GOPEntry geRef =  xGetGopEntries(refLayerIdInVps)[( i < getGOPSize()  ? i : MAX_GOP )];
 
               if ( geCur.m_interCompPredFlag )
@@ -1761,5 +1863,5 @@
     for( Int i = 0; i < ( getGOPSize() + 1) && maxOneActiveRefLayerFlag; i++ ) 
     {        
-      GOPEntry ge =  m_GOPListMvc[layerIdInVps][ ( i < getGOPSize()  ? i : MAX_GOP ) ]; 
+      GOPEntry ge =  xGetGopEntries(layerIdInVps)[ ( i < getGOPSize()  ? i : MAX_GOP ) ]; 
       maxOneActiveRefLayerFlag =  maxOneActiveRefLayerFlag && (ge.m_numActiveRefLayerPics <= 1); 
     }            
@@ -1784,5 +1886,5 @@
     for( Int i = 0; i < ( getGOPSize() + 1) && allRefLayersActiveFlag; i++ ) 
     {        
-      GOPEntry ge =  m_GOPListMvc[layerIdInVps][ ( i < getGOPSize()  ? i : MAX_GOP ) ]; 
+      GOPEntry ge =  xGetGopEntries(layerIdInVps)[ ( i < getGOPSize()  ? i : MAX_GOP ) ]; 
       Int tId = ge.m_temporalId;  // Should be equal for all layers. 
       
@@ -1838,20 +1940,4 @@
 
 
-GOPEntry* TAppEncTop::xGetGopEntry( Int layerIdInVps, Int poc )
-{
-  GOPEntry* geFound = NULL; 
-  for( Int i = 0; i < ( getGOPSize() + 1) && geFound == NULL ; i++ ) 
-  {
-    GOPEntry* ge = &(m_GOPListMvc[layerIdInVps][ ( i < getGOPSize()  ? i : MAX_GOP ) ]);
-    if ( ge->m_POC == poc )
-    {
-      geFound = ge;       
-    }
-  }
-  assert( geFound != NULL ); 
-  return geFound; 
-}
-
-
 Void TAppEncTop::xSetTimingInfo( TComVPS& vps )
 {
@@ -1905,4 +1991,8 @@
 { 
 
+  xDeriveProfAndConstrFlags( vps );  
+  xCheckProfiles           ( vps );
+  xPrintProfiles           (  );
+  
   // SET PTL
   assert( m_profiles.size() == m_level.size() && m_profiles.size() == m_levelTier.size() ); 
@@ -1912,18 +2002,40 @@
     if ( ptlIdx > 1 )
     {
-      Bool vpsProfilePresentFlag = ( m_profiles[ptlIdx] != m_profiles[ptlIdx - 1] )
-        || ( m_inblFlag[ptlIdx ] != m_inblFlag[ptlIdx - 1] ); 
+      Bool vpsProfilePresentFlag = 
+           ( m_profiles                [ptlIdx ] != m_profiles                [ptlIdx - 1] )
+        || ( m_progressiveSourceFlags  [ptlIdx ] != m_progressiveSourceFlags  [ptlIdx - 1] )
+        || ( m_interlacedSourceFlags   [ptlIdx ] != m_interlacedSourceFlags   [ptlIdx - 1] )
+        || ( m_nonPackedConstraintFlags[ptlIdx ] != m_nonPackedConstraintFlags[ptlIdx - 1] )
+        || ( m_frameOnlyConstraintFlags[ptlIdx ] != m_frameOnlyConstraintFlags[ptlIdx - 1] )
+        || ( m_inblFlag                [ptlIdx ] != m_inblFlag                [ptlIdx - 1] );
+
+      
+      if ( m_profiles[ ptlIdx ] >= 4 && m_profiles[ ptlIdx ] <= 7 )
+      {
+
+        vpsProfilePresentFlag = vpsProfilePresentFlag
+          || ( m_profiles                [ptlIdx ] != m_profiles                [ptlIdx - 1] )
+          || ( m_progressiveSourceFlags  [ptlIdx ] != m_progressiveSourceFlags  [ptlIdx - 1] )
+          || ( m_interlacedSourceFlags   [ptlIdx ] != m_interlacedSourceFlags   [ptlIdx - 1] )
+          || ( m_nonPackedConstraintFlags[ptlIdx ] != m_nonPackedConstraintFlags[ptlIdx - 1] )
+          || ( m_frameOnlyConstraintFlags[ptlIdx ] != m_frameOnlyConstraintFlags[ptlIdx - 1] )
+          || ( m_inblFlag                [ptlIdx ] != m_inblFlag                [ptlIdx - 1] );
+
+      }
+
+      
       vps.setVpsProfilePresentFlag( ptlIdx, vpsProfilePresentFlag ); 
     }
 
     xSetProfileTierLevel( vps, ptlIdx, -1, m_profiles[ptlIdx], m_level[ptlIdx], 
-      m_levelTier[ ptlIdx ], m_progressiveSourceFlag, m_interlacedSourceFlag,
-      m_nonPackedConstraintFlag, m_frameOnlyConstraintFlag,  m_inblFlag[ptlIdx] );     
-  }  
-}
-
-Void TAppEncTop::xSetProfileTierLevel(TComVPS& vps, Int profileTierLevelIdx, Int subLayer, Profile::Name profile, Level::Name level, Level::Tier tier, Bool progressiveSourceFlag, Bool interlacedSourceFlag, Bool nonPackedConstraintFlag, Bool frameOnlyConstraintFlag, Bool inbldFlag)
+      m_levelTier[ ptlIdx ], m_progressiveSourceFlags[ptlIdx], m_interlacedSourceFlags[ptlIdx],
+      m_nonPackedConstraintFlags[ptlIdx], m_frameOnlyConstraintFlags[ptlIdx],  m_inblFlag[ptlIdx] );     
+  }
+}
+
+Void TAppEncTop::xSetProfileTierLevel(TComVPS& vps, Int ptlIdx, Int subLayer, Profile::Name profile, Level::Name level, Level::Tier tier, Bool progressiveSourceFlag, Bool interlacedSourceFlag, Bool nonPackedConstraintFlag, Bool frameOnlyConstraintFlag, Bool inbldFlag)
 {
-  TComPTL* ptlStruct = vps.getPTL( profileTierLevelIdx );    
+  
+  TComPTL* ptlStruct = vps.getPTL( ptlIdx );    
   assert( ptlStruct != NULL ); 
 
@@ -1940,49 +2052,27 @@
   assert( ptl != NULL );
 
-  ptl->setProfileIdc( profile );
-  ptl->setTierFlag  ( tier    );
-  ptl->setLevelIdc  ( level   );
-  ptl->setProfileCompatibilityFlag( profile, true );
-  ptl->setInbldFlag( inbldFlag );
-
-  switch ( profile )
-  {
-  case Profile::MAIN:
-    break; 
-  case Profile::MULTIVIEWMAIN:
-#if NH_3D
-  case Profile::MAIN3D:
-#endif
-    ptl->setMax12bitConstraintFlag      ( true  ); 
-    ptl->setMax12bitConstraintFlag      ( true  );
-    ptl->setMax10bitConstraintFlag      ( true  );
-    ptl->setMax8bitConstraintFlag       ( true  );
-    ptl->setMax422chromaConstraintFlag  ( true  );
-    ptl->setMax420chromaConstraintFlag  ( true  );
-    ptl->setMaxMonochromeConstraintFlag ( false );
-    ptl->setIntraConstraintFlag         ( false ); 
-    ptl->setOnePictureOnlyConstraintFlag( false );
-    ptl->setLowerBitRateConstraintFlag  ( true  );        
-    break; 
-  default:
-    assert( 0 ); // other profiles currently not supported
-    break; 
-  }
+  ptl->setProfileIdc              ( m_profiles [ ptlIdx ] );
+  ptl->setTierFlag                ( m_levelTier[ ptlIdx ] );
+  ptl->setLevelIdc                ( m_level    [ ptlIdx ] );
+  ptl->setProfileCompatibilityFlag( m_profiles [ ptlIdx ], true );
+  ptl->setInbldFlag               ( m_inblFlag [ ptlIdx ] );
+
+  Int        bitDepth = m_bitDepthConstraints[ptlIdx];
+  ChromaFormat chroma = m_chromaFormatConstraints[ptlIdx];
+
+  ptl->setMax12bitConstraintFlag      (  bitDepth <= 12  );   
+  ptl->setMax10bitConstraintFlag      (  bitDepth <= 10 );
+  ptl->setMax8bitConstraintFlag       (  bitDepth <= 8 );
+  ptl->setMax422chromaConstraintFlag  ( chroma == CHROMA_400 || chroma == CHROMA_420 || chroma == CHROMA_422    );
+  ptl->setMax420chromaConstraintFlag  ( chroma == CHROMA_400 || chroma == CHROMA_420                            );                         ;
+  ptl->setMaxMonochromeConstraintFlag ( chroma == CHROMA_400                       );
+  ptl->setIntraConstraintFlag         ( m_intraConstraintFlags[ ptlIdx ]           ); 
+  ptl->setOnePictureOnlyConstraintFlag( m_onePictureOnlyConstraintFlags[ ptlIdx ]  );
+  ptl->setLowerBitRateConstraintFlag  ( m_lowerBitRateConstraintFlags[ ptlIdx ]    );    
 }
 
 Void TAppEncTop::xSetRepFormat( TComVPS& vps )
 {
-
-  Bool anyDepth = false; 
-#if NH_3D
-  for ( Int i = 0; i < m_numberOfLayers; i++ )
-  {
-    vps.setVpsRepFormatIdx( i, m_depthFlag[ i ] ? 1 : 0 );
-    anyDepth = anyDepth || m_depthFlag[ i ];
-  }
-#endif
-
-  vps.setRepFormatIdxPresentFlag( anyDepth ); 
-  vps.setVpsNumRepFormatsMinus1 ( anyDepth ? 1 : 0     ); 
+  vps.setVpsNumRepFormatsMinus1 ( m_numRepFormats - 1 ); 
 
 
@@ -1991,9 +2081,9 @@
   for ( Int j = 0; j <= vps.getVpsNumRepFormatsMinus1(); j++ )
   {           
-    repFormat[j].setBitDepthVpsChromaMinus8   ( m_internalBitDepth[CHANNEL_TYPE_LUMA  ] - 8 ); 
-    repFormat[j].setBitDepthVpsLumaMinus8     ( m_internalBitDepth[CHANNEL_TYPE_CHROMA] - 8 );
-    repFormat[j].setChromaFormatVpsIdc        ( j == 1 ? CHROMA_400 :  CHROMA_420 );
-    repFormat[j].setPicHeightVpsInLumaSamples ( m_iSourceHeight );
-    repFormat[j].setPicWidthVpsInLumaSamples  ( m_iSourceWidth  );    
+    repFormat[j].setBitDepthVpsChromaMinus8   ( m_internalBitDepths[j][CHANNEL_TYPE_LUMA  ] - 8 ); 
+    repFormat[j].setBitDepthVpsLumaMinus8     ( m_internalBitDepths[j][CHANNEL_TYPE_CHROMA] - 8 );
+    repFormat[j].setChromaFormatVpsIdc        ( m_chromaFormatIDCs[j] );
+    repFormat[j].setPicHeightVpsInLumaSamples ( m_iSourceHeights[j] );
+    repFormat[j].setPicWidthVpsInLumaSamples  ( m_iSourceWidths [j] );    
     repFormat[j].setChromaAndBitDepthVpsPresentFlag( true );    
     // ToDo not supported yet. 
@@ -2001,11 +2091,39 @@
 
     repFormat[j].setConformanceWindowVpsFlag( true );
-    repFormat[j].setConfWinVpsLeftOffset    ( m_confWinLeft   / TComSPS::getWinUnitX( repFormat[j].getChromaFormatVpsIdc() ) );
-    repFormat[j].setConfWinVpsRightOffset   ( m_confWinRight  / TComSPS::getWinUnitX( repFormat[j].getChromaFormatVpsIdc() )  );
-    repFormat[j].setConfWinVpsTopOffset     ( m_confWinTop    / TComSPS::getWinUnitY( repFormat[j].getChromaFormatVpsIdc() )  );
-    repFormat[j].setConfWinVpsBottomOffset  ( m_confWinBottom / TComSPS::getWinUnitY( repFormat[j].getChromaFormatVpsIdc() ) ); 
+    repFormat[j].setConfWinVpsLeftOffset    ( m_confWinLefts  [j] / TComSPS::getWinUnitX( repFormat[j].getChromaFormatVpsIdc() ) );
+    repFormat[j].setConfWinVpsRightOffset   ( m_confWinRights [j] / TComSPS::getWinUnitX( repFormat[j].getChromaFormatVpsIdc() ) );
+    repFormat[j].setConfWinVpsTopOffset     ( m_confWinTops   [j] / TComSPS::getWinUnitY( repFormat[j].getChromaFormatVpsIdc() ) );
+    repFormat[j].setConfWinVpsBottomOffset  ( m_confWinBottoms[j] / TComSPS::getWinUnitY( repFormat[j].getChromaFormatVpsIdc() ) ); 
   }
 
   vps.setRepFormat( repFormat );
+
+
+  if ( vps.getVpsNumRepFormatsMinus1() > 0 )
+  {
+    Bool repFormatIdxPresentFlag = false;
+    for( Int i = vps.getVpsBaseLayerInternalFlag() ? 1 : 0; i <= vps.getMaxLayersMinus1(); i++ )
+    {
+      repFormatIdxPresentFlag = repFormatIdxPresentFlag ||  ( m_layerIdxInVpsToRepFormatIdx[i]  != vps.inferVpsRepFormatIdx( i ) );
+    }
+    vps.setRepFormatIdxPresentFlag( repFormatIdxPresentFlag ); 
+  }
+
+  for( Int i =  0; i <=  vps.getMaxLayersMinus1(); i++ )
+  {
+    // When base_layer_internal_flag is equal to 1, the first repFormatIdx cannot be signaled but is inferred.
+    if( !vps.getRepFormatIdxPresentFlag() || ( vps.getVpsBaseLayerInternalFlag() && i == 0 )   ) 
+    {
+      vps.setVpsRepFormatIdx( i, vps.inferVpsRepFormatIdx( i ) );
+      AOF( vps.getVpsRepFormatIdx( i ) == m_layerIdxInVpsToRepFormatIdx[i] ); 
+    }
+    else
+    {
+      vps.setVpsRepFormatIdx( i, m_layerIdxInVpsToRepFormatIdx[i] );          
+    }
+  }
+
+
+  xConfirmRepFormat( vps );
 
 }
@@ -2431,7 +2549,8 @@
 
 
-#if NH_3D_DLT
+#if NH_3D
 Void TAppEncTop::xDeriveDltArray( TComVPS& vps, TComDLT* dlt )
 {
+  std::cout << "Analyzing input depth for DLT ";
   Int  iNumDepthViews  = 0;
   Bool bDltPresentFlag = false;
@@ -2449,4 +2568,5 @@
     if( dlt->getUseDLTFlag( layer ) )
     {
+      std::cout << ".";
       xAnalyzeInputBaseDepth(layer, max(m_iIntraPeriod[layer], 24), &vps, dlt);
       bDltPresentFlag = bDltPresentFlag || dlt->getUseDLTFlag(layer);
@@ -2523,5 +2643,6 @@
       
       // bit map branch
-      uiNumBitsBitMap = 1 << m_inputBitDepth[CHANNEL_TYPE_LUMA];
+      Int repFormatIdx = m_layerIdxInVpsToRepFormatIdx[ layer ];
+      uiNumBitsBitMap = 1 << m_inputBitDepths[repFormatIdx][CHANNEL_TYPE_LUMA];
       
       // determine bDltBitMapFlag
@@ -2529,10 +2650,14 @@
       
       dlt->setUseBitmapRep(layer, bDltBitMapRepFlag);
-    }
+
+      AOF( m_inputBitDepths[repFormatIdx][CHANNEL_TYPE_LUMA] == m_inputBitDepths[0][CHANNEL_TYPE_LUMA] )
+    }
+    
   }
 
   dlt->setDltPresentFlag( bDltPresentFlag );
   dlt->setNumDepthViews ( iNumDepthViews  );
-  dlt->setDepthViewBitDepth( m_inputBitDepth[CHANNEL_TYPE_LUMA] );
+  dlt->setDepthViewBitDepth( m_inputBitDepths[CHANNEL_TYPE_LUMA][0] );
+  std::cout << " done." << std::endl; 
 }
 #endif
Index: /trunk/source/App/TAppEncoder/TAppEncTop.h
===================================================================
--- /trunk/source/App/TAppEncoder/TAppEncTop.h	(revision 1412)
+++ /trunk/source/App/TAppEncoder/TAppEncTop.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -73,6 +73,13 @@
 
   std::vector<Int>           m_frameRcvd;                   ///< number of received frames 
-
   TComPicLists               m_ivPicLists;                  ///< picture buffers of encoder instances
+
+  ParameterSetMap<TComSPS>   m_spsMap;
+  ParameterSetMap<TComPPS>   m_ppsMap;
+  
+  IntAry1d                   m_parameterSetId;  
+  BoolAry1d                  m_sendParameterSets;
+
+
 #if NH_MV
   TComVPS*                   m_vps;                         ///< vps
@@ -147,9 +154,82 @@
   Void xSetCamPara                ( TComVPS& vps );
 #endif
-  GOPEntry* xGetGopEntry( Int layerIdInVps, Int poc );
+
+  Void xDeriveParameterSetIds( TComVPS& vps )
+  {
+
+    m_parameterSetId  .clear();
+    m_sendParameterSets.clear();
+
+    m_parameterSetId  .resize( m_numberOfLayers, -1 );
+    m_sendParameterSets.resize( m_numberOfLayers, false );
+    if ( !m_shareParameterSets )
+    {
+      AOT( m_numberOfLayers > 16 ); 
+      for (Int curVpsLayerId = 0; curVpsLayerId < m_numberOfLayers; curVpsLayerId++ )
+      {
+        m_parameterSetId   [curVpsLayerId] = curVpsLayerId; 
+        m_sendParameterSets[curVpsLayerId] = true         ; 
+      }
+    }
+    else
+    {
+      // The spec requires e.g.:
+      // - It is a requirement of bitstream conformance that, when present, the value of chroma_format_idc shall be less than or equal to chroma_format_vps_idc 
+      //   of the vps_rep_format_idx[ j ]-th rep_format( ) syntax structure in the active VPS, where j is equal to LayerIdxInVps[ layerIdCurr ].  
+
+      // Consequently, a depth layer with chorma format 4:0:0 cannot refer to a base layer SPS with chroma format 4:2:0
+
+      // Furthermore, it is required that
+      // - the SPS RBSP shall have nuh_layer_id equal to 0, nuhLayerId, or IdRefLayer[ nuhLayerId ][ i ] with any value of i in the range of 0 to NumRefLayers[ nuhLayerId ] - 1, inclusive.
+
+      // Because of these requirements and when parameter set sharing is enabled, HTM sends the parameter sets for a current layer in its smallest reference layer having the same representation format. 
+
+
+      Int curPsId = 0; 
+
+      // Loop all layers
+      for (Int curVpsLayerId = 0; curVpsLayerId < m_numberOfLayers; curVpsLayerId++ )
+      {
+        // Get smallest reference layer with same rep format idx
+        Int curNuhLayerId = vps.getLayerIdInNuh(curVpsLayerId);
+        Int smallestRefNuhLIdSameRepFmt   = curNuhLayerId;
+
+        Int curRepFormatIdx = m_layerIdxInVpsToRepFormatIdx[ curVpsLayerId ];
+
+        for (Int j = 0; j < vps.getNumRefLayers( curNuhLayerId ); j++ )
+        {
+          Int refNuhLayerId = vps.getIdRefLayer( curNuhLayerId, j );
+          Int refVpsLayerId = vps.getLayerIdInVps( refNuhLayerId ); 
+
+          if ( smallestRefNuhLIdSameRepFmt > refNuhLayerId &&  m_layerIdxInVpsToRepFormatIdx[refVpsLayerId] == curRepFormatIdx  )
+          {
+            smallestRefNuhLIdSameRepFmt = refNuhLayerId; 
+          }
+        }
+
+        Int smallestRefVpsLIdSameRepFmt =   vps.getLayerIdInVps(  smallestRefNuhLIdSameRepFmt ); 
+
+        if (smallestRefVpsLIdSameRepFmt == curVpsLayerId )
+        {
+          m_sendParameterSets[ curVpsLayerId ] = true;         
+          m_parameterSetId   [ curVpsLayerId ] = curPsId;
+          curPsId++;
+          AOT( curPsId > 15 ); 
+        }
+        else
+        {
+          AOT( m_parameterSetId   [ smallestRefVpsLIdSameRepFmt  ] == -1 );
+          m_parameterSetId   [ curVpsLayerId ] = m_parameterSetId   [ smallestRefVpsLIdSameRepFmt  ];
+        }
+
+        
+      }
+    }
+  }
+
   Int  xGetMax( std::vector<Int>& vec);
   Bool xLayerIdInTargetEncLayerIdList( Int nuhLayerId );
 #endif
-#if NH_3D_DLT
+#if NH_3D
   Void xDeriveDltArray( TComVPS& vps, TComDLT* dlt );
   Void xAnalyzeInputBaseDepth(UInt layer, UInt uiNumFrames, TComVPS* vps, TComDLT* dlt);
@@ -165,5 +245,8 @@
 #else
   TEncTop&    getTEncTop  ()   { return  m_cTEncTop; }      ///< return encoder class pointer reference
-#endif
+ 
+#endif
+private:
+
 };// END CLASS DEFINITION TAppEncTop
 
Index: /trunk/source/App/TAppEncoder/encmain.cpp
===================================================================
--- /trunk/source/App/TAppEncoder/encmain.cpp	(revision 1412)
+++ /trunk/source/App/TAppEncoder/encmain.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -57,5 +57,10 @@
   fprintf( stdout, "\n" );
 #if NH_MV
-  fprintf( stdout, "3D-HTM Software: Encoder Version [%s] based on HM Version [%s]", NV_VERSION, HM_VERSION );  
+#if NH_3D
+  const char* hevcExt = "3D";
+#else
+  const char* hevcExt = "MV";
+#endif
+  fprintf( stdout, "HTM Software: Encoder Version [%s][%s] based on HM Version [%s]", NV_VERSION, hevcExt , HM_VERSION);  
 #else
   fprintf( stdout, "HM software: Encoder Version [%s] (including RExt)", NV_VERSION );
@@ -65,5 +70,7 @@
   fprintf( stdout, NVM_BITS );
   fprintf( stdout, "\n\n" );
-
+#if NH_MV
+  fprintf( stdout, "Use the HEVC_EXT define to select between MV- and 3D-HEVC. \n\n" );  
+#endif
   // create application encoder class
   cTAppEncTop.create();
Index: /trunk/source/App/utils/BitrateTargeting/ExtractBitrates.cpp
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/ExtractBitrates.cpp	(revision 1412)
+++ /trunk/source/App/utils/BitrateTargeting/ExtractBitrates.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/App/utils/BitrateTargeting/ExtractBitrates.h
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/ExtractBitrates.h	(revision 1412)
+++ /trunk/source/App/utils/BitrateTargeting/ExtractBitrates.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp	(revision 1412)
+++ /trunk/source/App/utils/BitrateTargeting/ExtractBitratesMain.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp	(revision 1412)
+++ /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h	(revision 1412)
+++ /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiers.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp	(revision 1412)
+++ /trunk/source/App/utils/BitrateTargeting/GuessLambdaModifiersMain.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/App/utils/BitrateTargeting/RuntimeError.h
===================================================================
--- /trunk/source/App/utils/BitrateTargeting/RuntimeError.h	(revision 1412)
+++ /trunk/source/App/utils/BitrateTargeting/RuntimeError.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/App/utils/annexBbytecount.cpp
===================================================================
--- /trunk/source/App/utils/annexBbytecount.cpp	(revision 1412)
+++ /trunk/source/App/utils/annexBbytecount.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/App/utils/convert_NtoMbit_YCbCr.cpp
===================================================================
--- /trunk/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 1412)
+++ /trunk/source/App/utils/convert_NtoMbit_YCbCr.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TAppCommon/program_options_lite.cpp
===================================================================
--- /trunk/source/Lib/TAppCommon/program_options_lite.cpp	(revision 1412)
+++ /trunk/source/Lib/TAppCommon/program_options_lite.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TAppCommon/program_options_lite.h
===================================================================
--- /trunk/source/Lib/TAppCommon/program_options_lite.h	(revision 1412)
+++ /trunk/source/Lib/TAppCommon/program_options_lite.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/AccessUnit.h
===================================================================
--- /trunk/source/Lib/TLibCommon/AccessUnit.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/AccessUnit.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/CommonDef.h
===================================================================
--- /trunk/source/Lib/TLibCommon/CommonDef.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/CommonDef.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -72,7 +72,7 @@
 #if NH_MV
 #define NV_VERSION        "16.2"                ///< Current software version
-#define HM_VERSION        "16.9"                ///< 
-#else
-#define NV_VERSION        "16.9"                 ///< Current software version
+#define HM_VERSION        "16.18"                ///< 
+#else
+#define NV_VERSION        "16.18"                 ///< Current software version
 #endif
 // ====================================================================================================================
@@ -267,8 +267,5 @@
 static const Int LAST_SIGNIFICANT_GROUPS =                        10 ;
 
-#if W0038_DB_OPT
 static const Int MAX_ENCODER_DEBLOCKING_QUALITY_LAYERS =           8 ;
-#endif
-
 
 #if NH_MV
@@ -290,4 +287,7 @@
 #endif
 
+static const UInt LUMA_LEVEL_TO_DQP_LUT_MAXSIZE =                1024; ///< max LUT size for QP offset based on luma
+
+
 // ====================================================================================================================
 // Macro functions
@@ -373,5 +373,5 @@
 #endif
 
-#if NH_3D_MLC  || NH_3D_ARP
+#if NH_3D
 #define MRG_MAX_NUM_CANDS_MEM       (MRG_MAX_NUM_CANDS+1) // one extra for inter-view motion prediction
 #endif
Index: /trunk/source/Lib/TLibCommon/ContextModel.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/ContextModel.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/ContextModel.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/ContextModel.h
===================================================================
--- /trunk/source/Lib/TLibCommon/ContextModel.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/ContextModel.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/ContextModel3DBuffer.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/ContextModel3DBuffer.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/ContextModel3DBuffer.h
===================================================================
--- /trunk/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/ContextModel3DBuffer.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/ContextTables.h
===================================================================
--- /trunk/source/Lib/TLibCommon/ContextTables.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/ContextTables.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -51,5 +51,5 @@
 #define NUM_SPLIT_FLAG_CTX            3       ///< number of context models for split flag
 #define NUM_SKIP_FLAG_CTX             3       ///< number of context models for skip flag
-#if NH_3D_DIS
+#if NH_3D
 #define NUM_DIS_FLAG_CTX              1
 #define NUM_DIS_TYPE_CTX              1       
@@ -162,30 +162,22 @@
 #define NUM_CU_TRANSQUANT_BYPASS_FLAG_CTX  1
 
-#if NH_3D_ARP
+#if NH_3D
 #define NUM_ARPW_CTX                  3       ///< number of context models for weighting factor index used by advanced residual prediction
-#endif
-
-#if NH_3D_IC
 #define NUM_IC_FLAG_CTX               1       ///< number of context models for illumination compensation flag
 #endif
+
 #define NUM_CROSS_COMPONENT_PREDICTION_CTX 10
 
 #define CNU                          154      ///< dummy initialization value for unused context models 'Context model Not Used'
 
-#if NH_3D_DMM
+#if NH_3D
 #define NUM_NOTDMM_FLAG_CTX           1       ///< number of context models for not-DMM flag
 #define NUM_DMM_MODE_CTX              1       ///< number of context models for DMM modes
-#endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA
 #define NUM_DDC_DATA_CTX              1       ///< number of context models for deltaDC data (DMM or SDC)
-#endif
-#if NH_3D_SDC_INTRA
 #define SDC_NUM_RESIDUAL_FLAG_CTX     1
 #define SDC_NUM_RESIDUAL_CTX          1
 #define NUM_SDC_FLAG_CTX              1      ///< number of context 
 #define NUM_DDC_FLAG_CTX              2       ///< number of context models for deltaDC flag (SDC only)
-#endif
-#if NH_3D_DBBP
-#define DBBP_NUM_FLAG_CTX                 1
+#define DBBP_NUM_FLAG_CTX             1
 #endif
 // ====================================================================================================================
@@ -218,5 +210,5 @@
   { CNU,  CNU,  CNU, },
 };
-#if NH_3D_DIS
+#if NH_3D
 static const UChar 
 INIT_DIS_FLAG[3][NUM_DIS_FLAG_CTX] =  
@@ -540,5 +532,5 @@
 //! \}
 
-#if NH_3D_ARP
+#if NH_3D
 static const UChar 
 INIT_ARPW[3][NUM_ARPW_CTX] = 
@@ -549,6 +541,4 @@
 };
 
-#endif
-#if NH_3D_IC
 static const UChar 
 INIT_IC_FLAG[3][NUM_IC_FLAG_CTX] =  
@@ -559,7 +549,4 @@
 };
 
-#endif
-
-#if NH_3D_DMM
 static const UChar 
 INIT_NOTDMM_FLAG[3][NUM_NOTDMM_FLAG_CTX] =
@@ -576,6 +563,5 @@
   { CNU }
 };
-#endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA
+
 static const UChar
 INIT_DDC_DATA[3][NUM_DDC_DATA_CTX] = 
@@ -585,6 +571,5 @@
   { CNU }, 
 };
-#endif
-#if NH_3D_SDC_INTRA
+
 static const UChar
 INIT_SDC_RESIDUAL_FLAG[3][SDC_NUM_RESIDUAL_FLAG_CTX] =
@@ -615,13 +600,11 @@
   {64, CNU}
 };
+static const UChar INIT_DBBP_FLAG[3][DBBP_NUM_FLAG_CTX] =
+{
+  { CNU },
+  { CNU },
+  { CNU },
+};
 #endif
-#if NH_3D_DBBP
-static const UChar INIT_DBBP_FLAG[3][DBBP_NUM_FLAG_CTX] =
-{
-  { CNU },
-  { CNU },
-  { CNU },
-};
+
 #endif
-
-#endif
Index: /trunk/source/Lib/TLibCommon/Debug.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/Debug.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/Debug.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -180,5 +180,7 @@
 
   PRINT_CONSTANT(ME_ENABLE_ROUNDING_OF_MVS,                                         settingNameWidth, settingValueWidth);
-  PRINT_CONSTANT(U0040_MODIFIED_WEIGHTEDPREDICTION_WITH_BIPRED_AND_CLIPPING,        settingNameWidth, settingValueWidth);
+#if NH_MV
+  PRINT_CONSTANT(NH_MV_ALLOW_NON_CONFORMING,                                        settingNameWidth, settingValueWidth);
+#endif
 
   //------------------------------------------------
Index: /trunk/source/Lib/TLibCommon/Debug.h
===================================================================
--- /trunk/source/Lib/TLibCommon/Debug.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/Debug.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/NAL.h
===================================================================
--- /trunk/source/Lib/TLibCommon/NAL.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/NAL.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/SEI.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/SEI.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/SEI.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -124,19 +124,20 @@
     case SEI::BUFFERING_PERIOD:                     return "Buffering period";
     case SEI::PICTURE_TIMING:                       return "Picture timing";
-    case SEI::PAN_SCAN_RECT:                        return "Pan-scan rectangle";                   // not currently decoded
-    case SEI::FILLER_PAYLOAD:                       return "Filler payload";                       // not currently decoded
-    case SEI::USER_DATA_REGISTERED_ITU_T_T35:       return "User data registered";                 // not currently decoded
+    case SEI::PAN_SCAN_RECT:                        return "Pan-scan rectangle";
+    case SEI::FILLER_PAYLOAD:                       return "Filler payload";
+    case SEI::USER_DATA_REGISTERED_ITU_T_T35:       return "User data registered";
     case SEI::USER_DATA_UNREGISTERED:               return "User data unregistered";
     case SEI::RECOVERY_POINT:                       return "Recovery point";
-    case SEI::SCENE_INFO:                           return "Scene information";                    // not currently decoded
-    case SEI::FULL_FRAME_SNAPSHOT:                  return "Picture snapshot";                     // not currently decoded
-    case SEI::PROGRESSIVE_REFINEMENT_SEGMENT_START: return "Progressive refinement segment start"; // not currently decoded
-    case SEI::PROGRESSIVE_REFINEMENT_SEGMENT_END:   return "Progressive refinement segment end";   // not currently decoded
-    case SEI::FILM_GRAIN_CHARACTERISTICS:           return "Film grain characteristics";           // not currently decoded
-    case SEI::POST_FILTER_HINT:                     return "Post filter hint";                     // not currently decoded
+    case SEI::SCENE_INFO:                           return "Scene information";
+    case SEI::PICTURE_SNAPSHOT:                     return "Picture snapshot";
+    case SEI::PROGRESSIVE_REFINEMENT_SEGMENT_START: return "Progressive refinement segment start";
+    case SEI::PROGRESSIVE_REFINEMENT_SEGMENT_END:   return "Progressive refinement segment end";
+    case SEI::FILM_GRAIN_CHARACTERISTICS:           return "Film grain characteristics";
+    case SEI::POST_FILTER_HINT:                     return "Post filter hint";
     case SEI::TONE_MAPPING_INFO:                    return "Tone mapping information";
     case SEI::KNEE_FUNCTION_INFO:                   return "Knee function information";
     case SEI::FRAME_PACKING:                        return "Frame packing arrangement";
     case SEI::DISPLAY_ORIENTATION:                  return "Display orientation";
+    case SEI::GREEN_METADATA:                       return "Green metadata information";
     case SEI::SOP_DESCRIPTION:                      return "Structure of pictures information";
     case SEI::ACTIVE_PARAMETER_SETS:                return "Active parameter sets";
@@ -153,10 +154,12 @@
     case SEI::CHROMA_RESAMPLING_FILTER_HINT:        return "Chroma sampling filter hint";
     case SEI::COLOUR_REMAPPING_INFO:                return "Colour remapping info";
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
+    case SEI::DEINTERLACE_FIELD_IDENTIFICATION:     return "Deinterlace field identification";
+    case SEI::CONTENT_LIGHT_LEVEL_INFO:             return "Content light level info";
+    case SEI::DEPENDENT_RAP_INDICATION:             return "Dependent RAP indication";
+    case SEI::CODED_REGION_COMPLETION:              return "Coded region completion";
     case SEI::ALTERNATIVE_TRANSFER_CHARACTERISTICS: return "Alternative transfer characteristics";
-#endif
+    case SEI::AMBIENT_VIEWING_ENVIRONMENT:          return "Ambient viewing environment";
 
 #if NH_MV
-    case SEI::DEINTERLACED_FIELD_IDENTIFICATION:         return "Deinterlaced field identification";
     case SEI::LAYERS_NOT_PRESENT:                        return "Layers not present";
     case SEI::INTER_LAYER_CONSTRAINED_TILE_SETS:         return "Inter-layer constrained tile sets";
Index: /trunk/source/Lib/TLibCommon/SEI.h
===================================================================
--- /trunk/source/Lib/TLibCommon/SEI.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/SEI.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -68,18 +68,19 @@
     BUFFERING_PERIOD                     = 0,
     PICTURE_TIMING                       = 1,
-    PAN_SCAN_RECT                        = 2,
-    FILLER_PAYLOAD                       = 3,
-    USER_DATA_REGISTERED_ITU_T_T35       = 4,
-    USER_DATA_UNREGISTERED               = 5,
+    PAN_SCAN_RECT                        = 2,   // TODO: add encoder command line control to create these messages
+    FILLER_PAYLOAD                       = 3,   // TODO: add encoder command line control to create these messages
+    USER_DATA_REGISTERED_ITU_T_T35       = 4,   // TODO: add encoder command line control to create these messages
+    USER_DATA_UNREGISTERED               = 5,   // TODO: add encoder command line control to create these messages
     RECOVERY_POINT                       = 6,
-    SCENE_INFO                           = 9,
-    FULL_FRAME_SNAPSHOT                  = 15,
-    PROGRESSIVE_REFINEMENT_SEGMENT_START = 16,
-    PROGRESSIVE_REFINEMENT_SEGMENT_END   = 17,
-    FILM_GRAIN_CHARACTERISTICS           = 19,
-    POST_FILTER_HINT                     = 22,
+    SCENE_INFO                           = 9,   // TODO: add encoder command line control to create these messages
+    PICTURE_SNAPSHOT                     = 15,  // TODO: add encoder command line control to create these messages
+    PROGRESSIVE_REFINEMENT_SEGMENT_START = 16,  // TODO: add encoder command line control to create these messages
+    PROGRESSIVE_REFINEMENT_SEGMENT_END   = 17,  // TODO: add encoder command line control to create these messages
+    FILM_GRAIN_CHARACTERISTICS           = 19,  // TODO: add encoder command line control to create these messages
+    POST_FILTER_HINT                     = 22,  // TODO: add encoder command line control to create these messages
     TONE_MAPPING_INFO                    = 23,
     FRAME_PACKING                        = 45,
     DISPLAY_ORIENTATION                  = 47,
+    GREEN_METADATA                       = 56,
     SOP_DESCRIPTION                      = 128,
     ACTIVE_PARAMETER_SETS                = 129,
@@ -97,8 +98,11 @@
     KNEE_FUNCTION_INFO                   = 141,
     COLOUR_REMAPPING_INFO                = 142,
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
-    ALTERNATIVE_TRANSFER_CHARACTERISTICS = 182,
-#endif
-    DEINTERLACED_FIELD_IDENTIFICATION         = 143,
+    DEINTERLACE_FIELD_IDENTIFICATION     = 143, // TODO: add encoder command line control to create these messages
+    CONTENT_LIGHT_LEVEL_INFO             = 144, // TODO: add encoder command line control to create these messages
+    DEPENDENT_RAP_INDICATION             = 145, // TODO: add encoder command line control to create these messages
+    CODED_REGION_COMPLETION              = 146, // TODO: add encoder command line control to create these messages
+    ALTERNATIVE_TRANSFER_CHARACTERISTICS = 147,
+    AMBIENT_VIEWING_ENVIRONMENT          = 148, // TODO: add encoder command line control to create these messages
+#if NH_MV
     LAYERS_NOT_PRESENT                        = 160,
     INTER_LAYER_CONSTRAINED_TILE_SETS         = 161,
@@ -118,4 +122,5 @@
     ,ALTERNATIVE_DEPTH_INFO                    = 181
 #endif
+#endif
 
   };
@@ -165,57 +170,16 @@
 };
 
-static const UInt ISO_IEC_11578_LEN=16;
-
-class SEIuserDataUnregistered : public SEI
-{
-public:
-  PayloadType payloadType() const { return USER_DATA_UNREGISTERED; }
-
-  SEIuserDataUnregistered()
-    : userData(0)
-    {}
-
-  virtual ~SEIuserDataUnregistered()
-  {
-    delete userData;
-  }
-
-  UChar uuid_iso_iec_11578[ISO_IEC_11578_LEN];
-  UInt  userDataLength;
-  UChar *userData;
-};
-
-class SEIDecodedPictureHash : public SEI
-{
-public:
-  PayloadType payloadType() const { return DECODED_PICTURE_HASH; }
-
-  SEIDecodedPictureHash() {}
-  virtual ~SEIDecodedPictureHash() {}
-
-  HashType method;
-
-  TComPictureHash m_pictureHash;
-};
-
-class SEIActiveParameterSets : public SEI
-{
-public:
-  PayloadType payloadType() const { return ACTIVE_PARAMETER_SETS; }
-
-  SEIActiveParameterSets()
-    : activeVPSId            (0)
-    , m_selfContainedCvsFlag (false)
-    , m_noParameterSetUpdateFlag (false)
-    , numSpsIdsMinus1        (0)
-  {}
-  virtual ~SEIActiveParameterSets() {}
-
-  Int activeVPSId;
-  Bool m_selfContainedCvsFlag;
-  Bool m_noParameterSetUpdateFlag;
-  Int numSpsIdsMinus1;
-  std::vector<Int> activeSeqParameterSetId;
-};
+
+typedef std::list<SEI*> SEIMessages;
+
+/// output a selection of SEI messages by payload type. Ownership stays in original message list.
+SEIMessages getSeisByType(SEIMessages &seiList, SEI::PayloadType seiType);
+
+/// remove a selection of SEI messages by payload type from the original list and return them in a new list.
+SEIMessages extractSeisByType(SEIMessages &seiList, SEI::PayloadType seiType);
+
+/// delete list of SEI messages (freeing the referenced objects)
+Void deleteSEIs (SEIMessages &seiList);
+
 
 class SEIBufferingPeriod : public SEI
@@ -279,21 +243,66 @@
 };
 
-class SEIDecodingUnitInfo : public SEI
-{
-public:
-  PayloadType payloadType() const { return DECODING_UNIT_INFO; }
-
-  SEIDecodingUnitInfo()
-    : m_decodingUnitIdx(0)
-    , m_duSptCpbRemovalDelay(0)
-    , m_dpbOutputDuDelayPresentFlag(false)
-    , m_picSptDpbOutputDuDelay(0)
-  {}
-  virtual ~SEIDecodingUnitInfo() {}
-  Int m_decodingUnitIdx;
-  Int m_duSptCpbRemovalDelay;
-  Bool m_dpbOutputDuDelayPresentFlag;
-  Int m_picSptDpbOutputDuDelay;
-};
+class SEIPanScanRect : public SEI
+{
+public:
+  PayloadType payloadType() const { return PAN_SCAN_RECT; }
+
+  SEIPanScanRect() {}
+  virtual ~SEIPanScanRect() {}
+
+  struct PanScanRect
+  {
+    Int leftOffset;
+    Int rightOffset;
+    Int topOffset;
+    Int bottomOffset;
+  };
+
+  UInt m_panScanRectId;
+  Bool m_panScanRectCancelFlag;
+  std::vector<PanScanRect> m_panScanRectRegions;
+  Bool m_panScanRectPersistenceFlag;
+};
+
+
+class SEIFillerPayload : public SEI
+{
+public:
+  PayloadType payloadType() const { return FILLER_PAYLOAD; }
+
+  SEIFillerPayload() {}
+  virtual ~SEIFillerPayload() {}
+
+  UInt m_numFillerFFBytes;
+};
+
+
+class SEIUserDataRegistered : public SEI
+{
+public:
+  PayloadType payloadType() const { return USER_DATA_REGISTERED_ITU_T_T35; }
+
+  SEIUserDataRegistered() {}
+  virtual ~SEIUserDataRegistered() {}
+
+  UShort m_ituCountryCode;
+  std::vector<UChar> m_userData;
+};
+
+
+static const UInt ISO_IEC_11578_LEN=16;
+
+class SEIUserDataUnregistered : public SEI
+{
+public:
+  PayloadType payloadType() const { return USER_DATA_UNREGISTERED; }
+
+  SEIUserDataUnregistered() {}
+  virtual ~SEIUserDataUnregistered() { }
+
+  UChar m_uuid_iso_iec_11578[ISO_IEC_11578_LEN];
+  std::vector<UChar> m_userData;
+};
+
 
 class SEIRecoveryPoint : public SEI
@@ -310,122 +319,109 @@
 };
 
-class SEIFramePacking : public SEI
-{
-public:
-  PayloadType payloadType() const { return FRAME_PACKING; }
-
-  SEIFramePacking() {}
-  virtual ~SEIFramePacking() {}
-
-  Int  m_arrangementId;
-  Bool m_arrangementCancelFlag;
-  Int  m_arrangementType;
-  Bool m_quincunxSamplingFlag;
-  Int  m_contentInterpretationType;
-  Bool m_spatialFlippingFlag;
-  Bool m_frame0FlippedFlag;
-  Bool m_fieldViewsFlag;
-  Bool m_currentFrameIsFrame0Flag;
-  Bool m_frame0SelfContainedFlag;
-  Bool m_frame1SelfContainedFlag;
-  Int  m_frame0GridPositionX;
-  Int  m_frame0GridPositionY;
-  Int  m_frame1GridPositionX;
-  Int  m_frame1GridPositionY;
-  Int  m_arrangementReservedByte;
-  Bool m_arrangementPersistenceFlag;
-  Bool m_upsampledAspectRatio;
-};
-
-class SEISegmentedRectFramePacking : public SEI
-{
-public:
-  PayloadType payloadType() const { return SEGM_RECT_FRAME_PACKING; }
-
-  SEISegmentedRectFramePacking() {}
-  virtual ~SEISegmentedRectFramePacking() {}
-
-  Bool m_arrangementCancelFlag;
-  Int  m_contentInterpretationType;
-  Bool m_arrangementPersistenceFlag;
-};
-
-class SEIDisplayOrientation : public SEI
-{
-public:
-  PayloadType payloadType() const { return DISPLAY_ORIENTATION; }
-
-  SEIDisplayOrientation()
-    : cancelFlag(true)
-    , persistenceFlag(0)
-    , extensionFlag(false)
-    {}
-  virtual ~SEIDisplayOrientation() {}
-
-  Bool cancelFlag;
-  Bool horFlip;
-  Bool verFlip;
-
-  UInt anticlockwiseRotation;
-  Bool persistenceFlag;
-  Bool extensionFlag;
-};
-
-class SEITemporalLevel0Index : public SEI
-{
-public:
-  PayloadType payloadType() const { return TEMPORAL_LEVEL0_INDEX; }
-
-  SEITemporalLevel0Index()
-    : tl0Idx(0)
-    , rapIdx(0)
-    {}
-  virtual ~SEITemporalLevel0Index() {}
-
-  UInt tl0Idx;
-  UInt rapIdx;
-};
-
-class SEIGradualDecodingRefreshInfo : public SEI
-{
-public:
-  PayloadType payloadType() const { return REGION_REFRESH_INFO; }
-
-  SEIGradualDecodingRefreshInfo()
-    : m_gdrForegroundFlag(0)
-  {}
-  virtual ~SEIGradualDecodingRefreshInfo() {}
-
-  Bool m_gdrForegroundFlag;
-};
-
-class SEINoDisplay : public SEI
-{
-public:
-  PayloadType payloadType() const { return NO_DISPLAY; }
-
-  SEINoDisplay()
-    : m_noDisplay(false)
-  {}
-  virtual ~SEINoDisplay() {}
-
-  Bool m_noDisplay;
-};
-
-class SEISOPDescription : public SEI
-{
-public:
-  PayloadType payloadType() const { return SOP_DESCRIPTION; }
-
-  SEISOPDescription() {}
-  virtual ~SEISOPDescription() {}
-
-  UInt m_sopSeqParameterSetId;
-  UInt m_numPicsInSopMinus1;
-
-  UInt m_sopDescVclNaluType[MAX_NUM_PICS_IN_SOP];
-  UInt m_sopDescTemporalId[MAX_NUM_PICS_IN_SOP];
-  UInt m_sopDescStRpsIdx[MAX_NUM_PICS_IN_SOP];
-  Int m_sopDescPocDelta[MAX_NUM_PICS_IN_SOP];
+class SEISceneInfo : public SEI
+{
+public:
+  PayloadType payloadType() const { return SCENE_INFO; }
+
+  SEISceneInfo() {}
+  virtual ~SEISceneInfo() {}
+
+  Bool m_bSceneInfoPresentFlag;
+  Bool m_bPrevSceneIdValidFlag;
+  UInt m_sceneId;
+  UInt m_sceneTransitionType;
+  UInt m_secondSceneId;
+};
+
+class SEIPictureSnapshot : public SEI
+{
+public:
+  PayloadType payloadType() const { return PICTURE_SNAPSHOT; }
+
+  SEIPictureSnapshot() {}
+  virtual ~SEIPictureSnapshot() {}
+
+  UInt m_snapshotId;
+};
+
+
+class SEIProgressiveRefinementSegmentStart : public SEI
+{
+public:
+  PayloadType payloadType() const { return PROGRESSIVE_REFINEMENT_SEGMENT_START; }
+
+  SEIProgressiveRefinementSegmentStart() {}
+  virtual ~SEIProgressiveRefinementSegmentStart() {}
+
+  UInt m_progressiveRefinementId;
+  UInt m_picOrderCntDelta;
+};
+
+
+class SEIProgressiveRefinementSegmentEnd: public SEI
+{
+public:
+  PayloadType payloadType() const { return PROGRESSIVE_REFINEMENT_SEGMENT_END; }
+
+  SEIProgressiveRefinementSegmentEnd() {}
+  virtual ~SEIProgressiveRefinementSegmentEnd() {}
+
+  UInt m_progressiveRefinementId;
+};
+
+
+class SEIFilmGrainCharacteristics: public SEI
+{
+public:
+  PayloadType payloadType() const { return FILM_GRAIN_CHARACTERISTICS; }
+
+  SEIFilmGrainCharacteristics() {}
+  virtual ~SEIFilmGrainCharacteristics() {}
+
+  Bool      m_filmGrainCharacteristicsCancelFlag;
+  UChar     m_filmGrainModelId;
+  Bool      m_separateColourDescriptionPresentFlag;
+  UChar     m_filmGrainBitDepthLumaMinus8;
+  UChar     m_filmGrainBitDepthChromaMinus8;
+  Bool      m_filmGrainFullRangeFlag;
+  UChar     m_filmGrainColourPrimaries;
+  UChar     m_filmGrainTransferCharacteristics;
+  UChar     m_filmGrainMatrixCoeffs;
+  UChar     m_blendingModeId;
+  UChar     m_log2ScaleFactor;
+
+  struct CompModelIntensityValues
+{
+    UChar intensityIntervalLowerBound;
+    UChar intensityIntervalUpperBound;
+    std::vector<Int> compModelValue;
+  };
+
+  struct CompModel
+  {
+    Bool  bPresentFlag;
+    UChar numModelValues; // this must be the same as intensityValues[*].compModelValue.size()
+    std::vector<CompModelIntensityValues> intensityValues;
+  };
+
+  CompModel m_compModel[MAX_NUM_COMPONENT];
+  Bool      m_filmGrainCharacteristicsPersistenceFlag;
+
+};
+
+
+class SEIPostFilterHint: public SEI
+{
+public:
+  PayloadType payloadType() const { return POST_FILTER_HINT; }
+
+  SEIPostFilterHint() {}
+  virtual ~SEIPostFilterHint() {}
+
+  UInt             m_filterHintSizeY;
+  UInt             m_filterHintSizeX;
+  UInt             m_filterHintType;
+  Bool             m_bIsMonochrome;
+  std::vector<Int> m_filterHintValues; // values stored in linear array, [ ( ( component * sizeY + y ) * SizeX ) + x ]
 };
 
@@ -465,4 +461,325 @@
 };
 
+class SEIFramePacking : public SEI
+{
+public:
+  PayloadType payloadType() const { return FRAME_PACKING; }
+
+  SEIFramePacking() {}
+  virtual ~SEIFramePacking() {}
+
+  Int  m_arrangementId;
+  Bool m_arrangementCancelFlag;
+  Int  m_arrangementType;
+  Bool m_quincunxSamplingFlag;
+  Int  m_contentInterpretationType;
+  Bool m_spatialFlippingFlag;
+  Bool m_frame0FlippedFlag;
+  Bool m_fieldViewsFlag;
+  Bool m_currentFrameIsFrame0Flag;
+  Bool m_frame0SelfContainedFlag;
+  Bool m_frame1SelfContainedFlag;
+  Int  m_frame0GridPositionX;
+  Int  m_frame0GridPositionY;
+  Int  m_frame1GridPositionX;
+  Int  m_frame1GridPositionY;
+  Int  m_arrangementReservedByte;
+  Bool m_arrangementPersistenceFlag;
+  Bool m_upsampledAspectRatio;
+};
+
+class SEIDisplayOrientation : public SEI
+{
+public:
+  PayloadType payloadType() const { return DISPLAY_ORIENTATION; }
+
+  SEIDisplayOrientation()
+    : cancelFlag(true)
+    , persistenceFlag(0)
+    , extensionFlag(false)
+    {}
+  virtual ~SEIDisplayOrientation() {}
+
+  Bool cancelFlag;
+  Bool horFlip;
+  Bool verFlip;
+
+  UInt anticlockwiseRotation;
+  Bool persistenceFlag;
+  Bool extensionFlag;
+};
+
+
+class SEIGreenMetadataInfo : public SEI
+  {
+public:
+    PayloadType payloadType() const { return GREEN_METADATA; }
+    SEIGreenMetadataInfo() {}
+
+    virtual ~SEIGreenMetadataInfo() {}
+
+    UInt m_greenMetadataType;
+    UInt m_xsdMetricType;
+    UInt m_xsdMetricValue;
+};
+
+
+class SEISOPDescription : public SEI
+    {
+public:
+  PayloadType payloadType() const { return SOP_DESCRIPTION; }
+
+  SEISOPDescription() {}
+  virtual ~SEISOPDescription() {}
+
+  UInt m_sopSeqParameterSetId;
+  UInt m_numPicsInSopMinus1;
+
+  UInt m_sopDescVclNaluType[MAX_NUM_PICS_IN_SOP];
+  UInt m_sopDescTemporalId[MAX_NUM_PICS_IN_SOP];
+  UInt m_sopDescStRpsIdx[MAX_NUM_PICS_IN_SOP];
+  Int m_sopDescPocDelta[MAX_NUM_PICS_IN_SOP];
+  };
+
+
+class SEIActiveParameterSets : public SEI
+      {
+public:
+  PayloadType payloadType() const { return ACTIVE_PARAMETER_SETS; }
+
+  SEIActiveParameterSets()
+    : activeVPSId            (0)
+    , m_selfContainedCvsFlag (false)
+    , m_noParameterSetUpdateFlag (false)
+    , numSpsIdsMinus1        (0)
+  {}
+  virtual ~SEIActiveParameterSets() {}
+
+  Int activeVPSId;
+  Bool m_selfContainedCvsFlag;
+  Bool m_noParameterSetUpdateFlag;
+  Int numSpsIdsMinus1;
+  std::vector<Int> activeSeqParameterSetId;
+};
+
+class SEIDecodingUnitInfo : public SEI
+{
+public:
+  PayloadType payloadType() const { return DECODING_UNIT_INFO; }
+
+  SEIDecodingUnitInfo()
+    : m_decodingUnitIdx(0)
+    , m_duSptCpbRemovalDelay(0)
+    , m_dpbOutputDuDelayPresentFlag(false)
+    , m_picSptDpbOutputDuDelay(0)
+  {}
+  virtual ~SEIDecodingUnitInfo() {}
+  Int m_decodingUnitIdx;
+  Int m_duSptCpbRemovalDelay;
+  Bool m_dpbOutputDuDelayPresentFlag;
+  Int m_picSptDpbOutputDuDelay;
+};
+
+class SEITemporalLevel0Index : public SEI
+{
+public:
+  PayloadType payloadType() const { return TEMPORAL_LEVEL0_INDEX; }
+
+  SEITemporalLevel0Index()
+    : tl0Idx(0)
+    , rapIdx(0)
+    {}
+  virtual ~SEITemporalLevel0Index() {}
+
+  UInt tl0Idx;
+  UInt rapIdx;
+};
+
+
+class SEIDecodedPictureHash : public SEI
+{
+public:
+  PayloadType payloadType() const { return DECODED_PICTURE_HASH; }
+
+  SEIDecodedPictureHash() {}
+  virtual ~SEIDecodedPictureHash() {}
+
+  HashType method;
+
+  TComPictureHash m_pictureHash;
+};
+
+
+class SEIScalableNesting : public SEI
+{
+public:
+  PayloadType payloadType() const { return SCALABLE_NESTING; }
+
+  SEIScalableNesting() {}
+
+  virtual ~SEIScalableNesting()
+  {
+    deleteSEIs(m_nestedSEIs);
+  }
+
+  Bool  m_bitStreamSubsetFlag;
+  Bool  m_nestingOpFlag;
+  Bool  m_defaultOpFlag;                             //value valid if m_nestingOpFlag != 0
+  UInt  m_nestingNumOpsMinus1;                       // -"-
+  UInt  m_nestingMaxTemporalIdPlus1[MAX_TLAYER];     // -"-
+  UInt  m_nestingOpIdx[MAX_NESTING_NUM_OPS];         // -"-
+
+  Bool  m_allLayersFlag;                             //value valid if m_nestingOpFlag == 0
+  UInt  m_nestingNoOpMaxTemporalIdPlus1;             //value valid if m_nestingOpFlag == 0 and m_allLayersFlag == 0
+  UInt  m_nestingNumLayersMinus1;                    //value valid if m_nestingOpFlag == 0 and m_allLayersFlag == 0
+  UChar m_nestingLayerId[MAX_NESTING_NUM_LAYER];     //value valid if m_nestingOpFlag == 0 and m_allLayersFlag == 0. This can e.g. be a static array of 64 UChar values
+
+  SEIMessages m_nestedSEIs;
+};
+
+
+class SEIRegionRefreshInfo : public SEI
+{
+public:
+  PayloadType payloadType() const { return REGION_REFRESH_INFO; }
+
+  SEIRegionRefreshInfo()
+    : m_gdrForegroundFlag(0)
+  {}
+  virtual ~SEIRegionRefreshInfo() {}
+
+  Bool m_gdrForegroundFlag;
+};
+
+
+class SEINoDisplay : public SEI
+{
+public:
+  PayloadType payloadType() const { return NO_DISPLAY; }
+
+  SEINoDisplay()
+    : m_noDisplay(false)
+  {}
+  virtual ~SEINoDisplay() {}
+
+  Bool m_noDisplay;
+};
+
+
+class SEITimeCode : public SEI
+{
+public:
+  PayloadType payloadType() const { return TIME_CODE; }
+  SEITimeCode() {}
+  virtual ~SEITimeCode(){}
+
+  UInt numClockTs;
+  TComSEITimeSet timeSetArray[MAX_TIMECODE_SEI_SETS];
+};
+
+
+class SEIMasteringDisplayColourVolume : public SEI
+{
+public:
+    PayloadType payloadType() const { return MASTERING_DISPLAY_COLOUR_VOLUME; }
+    SEIMasteringDisplayColourVolume() {}
+    virtual ~SEIMasteringDisplayColourVolume(){}
+
+    TComSEIMasteringDisplay values;
+};
+
+
+class SEISegmentedRectFramePacking : public SEI
+{
+public:
+  PayloadType payloadType() const { return SEGM_RECT_FRAME_PACKING; }
+
+  SEISegmentedRectFramePacking() {}
+  virtual ~SEISegmentedRectFramePacking() {}
+
+  Bool m_arrangementCancelFlag;
+  Int  m_contentInterpretationType;
+  Bool m_arrangementPersistenceFlag;
+};
+
+
+//definition according to P1005_v1;
+class SEITempMotionConstrainedTileSets: public SEI
+{
+  class TileSetData
+  {
+    protected:
+      std::vector<Int> m_top_left_tile_index;  //[tileSetIdx][tileIdx];
+      std::vector<Int> m_bottom_right_tile_index;
+
+    public:
+      Int     m_mcts_id;
+      Bool    m_display_tile_set_flag;
+      Int     m_num_tile_rects_in_set; //_minus1;
+      Bool    m_exact_sample_value_match_flag;
+      Bool    m_mcts_tier_level_idc_present_flag;
+      Bool    m_mcts_tier_flag;
+      Int     m_mcts_level_idc;
+
+      Void setNumberOfTileRects(const Int number)
+      {
+        m_top_left_tile_index    .resize(number);
+        m_bottom_right_tile_index.resize(number);
+      }
+
+      Int  getNumberOfTileRects() const
+      {
+        assert(m_top_left_tile_index.size() == m_bottom_right_tile_index.size());
+        return Int(m_top_left_tile_index.size());
+      }
+
+            Int &topLeftTileIndex    (const Int tileRectIndex)       { return m_top_left_tile_index    [tileRectIndex]; }
+            Int &bottomRightTileIndex(const Int tileRectIndex)       { return m_bottom_right_tile_index[tileRectIndex]; }
+      const Int &topLeftTileIndex    (const Int tileRectIndex) const { return m_top_left_tile_index    [tileRectIndex]; }
+      const Int &bottomRightTileIndex(const Int tileRectIndex) const { return m_bottom_right_tile_index[tileRectIndex]; }
+  };
+
+protected:
+  std::vector<TileSetData> m_tile_set_data;
+
+public:
+
+  Bool    m_mc_all_tiles_exact_sample_value_match_flag;
+  Bool    m_each_tile_one_tile_set_flag;
+  Bool    m_limited_tile_set_display_flag;
+  Bool    m_max_mcs_tier_level_idc_present_flag;
+  Bool    m_max_mcts_tier_flag;
+  Int     m_max_mcts_level_idc;
+
+  PayloadType payloadType() const { return TEMP_MOTION_CONSTRAINED_TILE_SETS; }
+  SEITempMotionConstrainedTileSets() { }
+  virtual ~SEITempMotionConstrainedTileSets() { }
+
+  Void setNumberOfTileSets(const Int number)       { m_tile_set_data.resize(number);     }
+  Int  getNumberOfTileSets()                 const { return Int(m_tile_set_data.size()); }
+
+        TileSetData &tileSetData (const Int index)       { return m_tile_set_data[index]; }
+  const TileSetData &tileSetData (const Int index) const { return m_tile_set_data[index]; }
+
+};
+
+
+class SEIChromaResamplingFilterHint : public SEI
+{
+public:
+  PayloadType payloadType() const {return CHROMA_RESAMPLING_FILTER_HINT;}
+  SEIChromaResamplingFilterHint() {}
+  virtual ~SEIChromaResamplingFilterHint() {}
+
+  Int                            m_verChromaFilterIdc;
+  Int                            m_horChromaFilterIdc;
+  Bool                           m_verFilteringFieldProcessingFlag;
+  Int                            m_targetFormatIdc;
+  Bool                           m_perfectReconstructionFlag;
+  std::vector<std::vector<Int> > m_verFilterCoeff;
+  std::vector<std::vector<Int> > m_horFilterCoeff;
+};
+
+
 class SEIKneeFunctionInfo : public SEI
 {
@@ -484,4 +801,5 @@
 };
 
+
 class SEIColourRemappingInfo : public SEI
 {
@@ -503,5 +821,5 @@
 
   Void copyFrom( const SEIColourRemappingInfo &seiCriInput)
-      {
+  {
     (*this) = seiCriInput;
   }
@@ -526,138 +844,53 @@
 };
 
-class SEIChromaResamplingFilterHint : public SEI
-{
-public:
-  PayloadType payloadType() const {return CHROMA_RESAMPLING_FILTER_HINT;}
-  SEIChromaResamplingFilterHint() {}
-  virtual ~SEIChromaResamplingFilterHint() {}
-
-  Int   m_verChromaFilterIdc;
-  Int   m_horChromaFilterIdc;
-  Bool                           m_verFilteringFieldProcessingFlag;
-  Int   m_targetFormatIdc;
-  Bool  m_perfectReconstructionFlag;
-  std::vector<std::vector<Int> > m_verFilterCoeff;
-  std::vector<std::vector<Int> > m_horFilterCoeff;
-};
-
-class SEIMasteringDisplayColourVolume : public SEI
-{
-public:
-    PayloadType payloadType() const { return MASTERING_DISPLAY_COLOUR_VOLUME; }
-    SEIMasteringDisplayColourVolume() {}
-    virtual ~SEIMasteringDisplayColourVolume(){}
-
-    TComSEIMasteringDisplay values;
-};
-
-typedef std::list<SEI*> SEIMessages;
-
-/// output a selection of SEI messages by payload type. Ownership stays in original message list.
-SEIMessages getSeisByType(SEIMessages &seiList, SEI::PayloadType seiType);
-
-/// remove a selection of SEI messages by payload type from the original list and return them in a new list.
-SEIMessages extractSeisByType(SEIMessages &seiList, SEI::PayloadType seiType);
-
-/// delete list of SEI messages (freeing the referenced objects)
-Void deleteSEIs (SEIMessages &seiList);
-
-class SEIScalableNesting : public SEI
-{
-public:
-  PayloadType payloadType() const { return SCALABLE_NESTING; }
-
-  SEIScalableNesting() {}
-
-  virtual ~SEIScalableNesting()
-  {
-    deleteSEIs(m_nestedSEIs);
-  }
-
-  Bool  m_bitStreamSubsetFlag;
-  Bool  m_nestingOpFlag;
-  Bool  m_defaultOpFlag;                             //value valid if m_nestingOpFlag != 0
-  UInt  m_nestingNumOpsMinus1;                       // -"-
-  UInt  m_nestingMaxTemporalIdPlus1[MAX_TLAYER];     // -"-
-  UInt  m_nestingOpIdx[MAX_NESTING_NUM_OPS];         // -"-
-
-  Bool  m_allLayersFlag;                             //value valid if m_nestingOpFlag == 0
-  UInt  m_nestingNoOpMaxTemporalIdPlus1;             //value valid if m_nestingOpFlag == 0 and m_allLayersFlag == 0
-  UInt  m_nestingNumLayersMinus1;                    //value valid if m_nestingOpFlag == 0 and m_allLayersFlag == 0
-  UChar m_nestingLayerId[MAX_NESTING_NUM_LAYER];     //value valid if m_nestingOpFlag == 0 and m_allLayersFlag == 0. This can e.g. be a static array of 64 UChar values
-
-  SEIMessages m_nestedSEIs;
-};
-
-class SEITimeCode : public SEI
-{
-public:
-  PayloadType payloadType() const { return TIME_CODE; }
-  SEITimeCode() {}
-  virtual ~SEITimeCode(){}
-
-  UInt numClockTs;
-  TComSEITimeSet timeSetArray[MAX_TIMECODE_SEI_SETS];
-};
-
-//definition according to P1005_v1;
-class SEITempMotionConstrainedTileSets: public SEI
-{
-  struct TileSetData
-  {
-    protected:
-      std::vector<Int> m_top_left_tile_index;  //[tileSetIdx][tileIdx];
-      std::vector<Int> m_bottom_right_tile_index;
-
-    public:
-      Int     m_mcts_id;
-      Bool    m_display_tile_set_flag;
-      Int     m_num_tile_rects_in_set; //_minus1;
-      Bool    m_exact_sample_value_match_flag;
-      Bool    m_mcts_tier_level_idc_present_flag;
-      Bool    m_mcts_tier_flag;
-      Int     m_mcts_level_idc;
-
-      Void setNumberOfTileRects(const Int number)
-      {
-        m_top_left_tile_index    .resize(number);
-        m_bottom_right_tile_index.resize(number);
-      }
-
-      Int  getNumberOfTileRects() const
-      {
-        assert(m_top_left_tile_index.size() == m_bottom_right_tile_index.size());
-        return Int(m_top_left_tile_index.size());
-      }
-
-            Int &topLeftTileIndex    (const Int tileRectIndex)       { return m_top_left_tile_index    [tileRectIndex]; }
-            Int &bottomRightTileIndex(const Int tileRectIndex)       { return m_bottom_right_tile_index[tileRectIndex]; }
-      const Int &topLeftTileIndex    (const Int tileRectIndex) const { return m_top_left_tile_index    [tileRectIndex]; }
-      const Int &bottomRightTileIndex(const Int tileRectIndex) const { return m_bottom_right_tile_index[tileRectIndex]; }
-  };
-
-protected:
-  std::vector<TileSetData> m_tile_set_data;
-
-public:
-
-  Bool    m_mc_all_tiles_exact_sample_value_match_flag;
-  Bool    m_each_tile_one_tile_set_flag;
-  Bool    m_limited_tile_set_display_flag;
-  Bool    m_max_mcs_tier_level_idc_present_flag;
-  Bool    m_max_mcts_tier_flag;
-  Int     m_max_mcts_level_idc;
-
-  PayloadType payloadType() const { return TEMP_MOTION_CONSTRAINED_TILE_SETS; }
-
-  Void setNumberOfTileSets(const Int number)       { m_tile_set_data.resize(number);     }
-  Int  getNumberOfTileSets()                 const { return Int(m_tile_set_data.size()); }
-
-        TileSetData &tileSetData (const Int index)       { return m_tile_set_data[index]; }
-  const TileSetData &tileSetData (const Int index) const { return m_tile_set_data[index]; }
-
-};
-
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
+
+class SEIDeinterlaceFieldIdentification : public SEI
+{
+public:
+    PayloadType payloadType() const { return  DEINTERLACE_FIELD_IDENTIFICATION; }
+    SEIDeinterlaceFieldIdentification() { }
+
+    virtual ~SEIDeinterlaceFieldIdentification() {}
+
+    Bool m_deinterlacedPictureSourceParityFlag;
+};
+
+
+class SEIContentLightLevelInfo : public SEI
+{
+public:
+    PayloadType payloadType() const { return CONTENT_LIGHT_LEVEL_INFO; }
+    SEIContentLightLevelInfo() { }
+
+    virtual ~SEIContentLightLevelInfo() { }
+
+    UInt m_maxContentLightLevel;
+    UInt m_maxPicAverageLightLevel;
+};
+
+
+class SEIDependentRAPIndication : public SEI
+{
+public:
+  PayloadType payloadType() const { return DEPENDENT_RAP_INDICATION; }
+  SEIDependentRAPIndication() { }
+
+  virtual ~SEIDependentRAPIndication() { }
+};
+
+
+class SEICodedRegionCompletion : public SEI
+{
+public:
+  PayloadType payloadType() const { return CODED_REGION_COMPLETION; }
+  SEICodedRegionCompletion() { }
+
+  virtual ~SEICodedRegionCompletion() { }
+
+  UInt m_nextSegmentAddress;
+  Bool m_independentSliceSegmentFlag;
+};
+
+
 class SEIAlternativeTransferCharacteristics : public SEI
 {
@@ -672,5 +905,18 @@
   UInt m_preferredTransferCharacteristics;
 };
-#endif
+
+
+class SEIAmbientViewingEnvironment : public SEI
+{
+public:
+  PayloadType payloadType() const { return AMBIENT_VIEWING_ENVIRONMENT; }
+  SEIAmbientViewingEnvironment() { }
+
+  virtual ~SEIAmbientViewingEnvironment() { }
+
+  UInt m_ambientIlluminance;
+  UShort m_ambientLightX;
+  UShort m_ambientLightY;
+};
 
 
Index: /trunk/source/Lib/TLibCommon/TComBitCounter.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComBitCounter.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComBitCounter.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComBitStream.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComBitStream.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComBitStream.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComBitStream.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComBitStream.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComBitStream.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComCABACTables.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComCABACTables.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComCABACTables.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComCABACTables.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComCABACTables.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComChromaFormat.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComChromaFormat.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComChromaFormat.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComChromaFormat.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComChromaFormat.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComChromaFormat.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComCodingStatistics.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComCodingStatistics.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComCodingStatistics.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -81,8 +81,6 @@
   STATS__CABAC_BITS__ESCAPE_BITS,
 
-#if NH_3D_DBBP
+#if NH_3D
   STATS__CABAC_BITS__DBBP_FLAG,
-#endif
-#if NH_3D_ARP
   STATS__CABAC_BITS__ARP_FLAG,
 #endif
@@ -99,18 +97,12 @@
   STATS__CABAC_BITS__ALIGNED_ESCAPE_BITS,
 
-#if NH_3D_IC
+#if NH_3D
   STATS__CABAC_BITS__3D_IC,
-#endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   STATS__CABAC_BITS__DELTADC_SIGN_EP,
   STATS__CABAC_BITS__DELTADC_PREFIX,
   STATS__CABAC_BITS__DELTADC_SUFFIX_EP,
-#endif
-#if NH_3D_DMM
   STATS__CABAC_BITS__NOTDMM_FLAG,
   STATS__CABAC_BITS__DMMMODE,
   STATS__CABAC_BITS__DMM1_BITS_EP,
-#endif
-#if NH_3D_SDC_INTRA
   STATS__CABAC_BITS__SDC_INTRA_FLAG,
   STATS__CABAC_BITS__SDC_DELTADC_FLAG,
@@ -156,5 +148,5 @@
     "CABAC_BITS__SIGN_BIT",
     "CABAC_BITS__ESCAPE_BITS",
-#if NH_3D_DBBP
+#if NH_3D
     "CABAC_BITS__DBBP_FLAG",
 #endif
@@ -171,18 +163,12 @@
     "CABAC_BITS__ALIGNED_ESCAPE_BITS"
 
-#if NH_3D_IC
+#if NH_3D
     "CABAC_BITS__3D_IC"
-#endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
    ,"STATS__CABAC_BITS__DELTADC_SIGN_EP"
    ,"STATS__CABAC_BITS__DELTADC_PREFIX"
    ,"STATS__CABAC_BITS__DELTADC_SUFFIX_EP"
-#endif
-#if NH_3D_DMM
    ,"STATS__CABAC_BITS__NOTDMM_FLAG"
    ,"STATS__CABAC_BITS__DMMMODE"
    ,"STATS__CABAC_BITS__DMM1_BITS_EP"
-#endif
-#if NH_3D_SDC_INTRA
     ,"STATS__CABAC_BITS__SDC_INTRA_FLAG"
     ,"STATS__CABAC_BITS__SDC_DELTADC_FLAG"
Index: /trunk/source/Lib/TLibCommon/TComDataCU.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComDataCU.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComDataCU.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -55,5 +55,5 @@
 
   m_skipFlag           = NULL;
-#if NH_3D_DIS
+#if NH_3D
   m_bDISFlag           = NULL;
   m_ucDISType          = NULL;
@@ -99,10 +99,9 @@
   for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
   {
-    m_apcCUColocated[i]  = NULL;
     m_apiMVPIdx[i]       = NULL;
     m_apiMVPNum[i]       = NULL;
   }
 
-#if NH_3D_DMM
+#if NH_3D
   for( Int i = 0; i < NUM_DMM; i++ )
   {
@@ -111,6 +110,5 @@
   }
   m_dmm1WedgeTabIdx = NULL;
-#endif
-#if NH_3D_SDC_INTRA
+
   m_pbSDCFlag             = NULL;
   m_apSegmentDCOffset[0]  = NULL;
@@ -120,20 +118,10 @@
   m_bDecSubCu          = false;
 
-#if NH_3D_NBDV
+#if NH_3D
   m_pDvInfo              = NULL;
-#endif
-#if NH_3D_VSP
   m_piVSPFlag            = NULL;
-#endif
-#if NH_3D_SPIVMP
   m_pbSPIVMPFlag         = NULL;
-#endif
-#if NH_3D_ARP
   m_puhARPW              = NULL;
-#endif
-#if NH_3D_IC
   m_pbICFlag             = NULL;
-#endif
-#if NH_3D_DBBP
   m_pbDBBPFlag         = NULL;
 #endif
@@ -167,5 +155,5 @@
     m_ChromaQpAdj        = new UChar[ uiNumPartition ];
     m_skipFlag           = new Bool[ uiNumPartition ];
-#if NH_3D_DIS
+#if NH_3D
     m_bDISFlag           = new Bool[ uiNumPartition ];
     m_ucDISType          = (UChar*)xMalloc(UChar, uiNumPartition);
@@ -178,8 +166,6 @@
     m_pbMergeFlag        = (Bool*  )xMalloc(Bool,   uiNumPartition);
     m_puhMergeIndex      = (UChar* )xMalloc(UChar,  uiNumPartition);
-#if NH_3D_VSP
+#if NH_3D
     m_piVSPFlag          = (SChar* )xMalloc(SChar, uiNumPartition);
-#endif
-#if NH_3D_SPIVMP
     m_pbSPIVMPFlag       = (Bool*  )xMalloc(Bool,   uiNumPartition);
 #endif
@@ -201,5 +187,5 @@
     }
 
-#if NH_3D_NBDV 
+#if NH_3D
     m_pDvInfo            = (DisInfo* )xMalloc(DisInfo,  uiNumPartition);
 #endif
@@ -242,11 +228,7 @@
     }
 
-#if NH_3D_ARP
+#if NH_3D
     m_puhARPW            = (UChar*  )xMalloc(UChar,   uiNumPartition);
-#endif
-#if NH_3D_IC
     m_pbICFlag           = (Bool* )xMalloc(Bool,   uiNumPartition);
-#endif
-#if NH_3D_DMM
     for( Int i = 0; i < NUM_DMM; i++ )
     {
@@ -255,11 +237,7 @@
     }
     m_dmm1WedgeTabIdx    = (UInt*)xMalloc(UInt, uiNumPartition);
-#endif
-#if NH_3D_SDC_INTRA
     m_pbSDCFlag             = (Bool*)xMalloc(Bool, uiNumPartition);
     m_apSegmentDCOffset[0]  = (Pel*)xMalloc(Pel, uiNumPartition);
     m_apSegmentDCOffset[1]  = (Pel*)xMalloc(Pel, uiNumPartition);
-#endif
-#if NH_3D_DBBP
     m_pbDBBPFlag         = (Bool*  )xMalloc(Bool,   uiNumPartition);
 #endif
@@ -280,9 +258,4 @@
   m_pCtuAbove          = NULL;
   m_pCtuLeft           = NULL;
-
-  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
-  {
-    m_apcCUColocated[i]  = NULL;
-  }
 }
 
@@ -319,5 +292,5 @@
     }
 
-#if NH_3D_DIS
+#if NH_3D
     if ( m_bDISFlag           ) { delete[] m_bDISFlag;   m_bDISFlag     = NULL; }
     if ( m_ucDISType         ) { xFree(m_ucDISType);  m_ucDISType    = NULL; }
@@ -360,5 +333,5 @@
     }
 
-#if NH_3D_VSP
+#if NH_3D
     if ( m_piVSPFlag )
     {
@@ -366,6 +339,4 @@
       m_piVSPFlag = NULL;
     }
-#endif
-#if NH_3D_SPIVMP
     if ( m_pbSPIVMPFlag       ) { xFree(m_pbSPIVMPFlag);           m_pbSPIVMPFlag         = NULL; }
 #endif
@@ -455,17 +426,8 @@
       m_acCUMvField[rpl].destroy();
     }
-#if NH_3D_NBDV 
+#if NH_3D
     if ( m_pDvInfo            ) { xFree(m_pDvInfo);             m_pDvInfo           = NULL; }
-#endif
-
-
-#if NH_3D_ARP
     if ( m_puhARPW            ) { xFree(m_puhARPW);             m_puhARPW           = NULL; }
-#endif
-#if NH_3D_IC
     if ( m_pbICFlag           ) { xFree(m_pbICFlag);            m_pbICFlag          = NULL; }
-#endif
-
-#if NH_3D_DMM
     for( Int i = 0; i < NUM_DMM; i++ )
     {
@@ -474,12 +436,8 @@
     }
     if ( m_dmm1WedgeTabIdx    ) { xFree( m_dmm1WedgeTabIdx );  m_dmm1WedgeTabIdx = NULL;  }
-#endif
-#if NH_3D_SDC_INTRA
     if ( m_pbSDCFlag            ) { xFree(m_pbSDCFlag);             m_pbSDCFlag             = NULL; }
     if ( m_apSegmentDCOffset[0] ) { xFree(m_apSegmentDCOffset[0]);  m_apSegmentDCOffset[0]  = NULL; }
     if ( m_apSegmentDCOffset[1] ) { xFree(m_apSegmentDCOffset[1]);  m_apSegmentDCOffset[1]  = NULL; }
-#endif    
-#if NH_3D_DBBP
-    if ( m_pbDBBPFlag         ) { xFree(m_pbDBBPFlag);          m_pbDBBPFlag        = NULL; }
+    if ( m_pbDBBPFlag           ) { xFree(m_pbDBBPFlag);          m_pbDBBPFlag        = NULL; }
 #endif
 
@@ -493,10 +451,4 @@
   m_pCtuAbove          = NULL;
   m_pCtuLeft           = NULL;
-
-
-  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
-  {
-    m_apcCUColocated[i]  = NULL;
-  }
 
 }
@@ -572,5 +524,5 @@
   memset( m_skipFlag          , false,                      m_uiNumPartition * sizeof( *m_skipFlag ) );
 
-#if NH_3D_DIS
+#if NH_3D
     memset( m_bDISFlag        , false,                      m_uiNumPartition * sizeof( *m_bDISFlag ) );
     memset( m_ucDISType       , false,                      m_uiNumPartition * sizeof( *m_ucDISType ) );
@@ -585,5 +537,5 @@
   memset( m_puhHeight         , maxCUHeight,                m_uiNumPartition * sizeof( *m_puhHeight ) );
 
-#if NH_3D_IC
+#if NH_3D
   memset( m_pbICFlag          , false,                      m_uiNumPartition * sizeof( *m_pbICFlag ) );
 #endif
@@ -606,14 +558,8 @@
   memset( m_puhMergeIndex     , 0,                        m_uiNumPartition * sizeof( *m_puhMergeIndex ) );
 
-#if NH_3D_VSP
+#if NH_3D
   memset( m_piVSPFlag         , 0,                        m_uiNumPartition * sizeof( *m_piVSPFlag ) );
-#endif
-#if NH_3D_SPIVMP
   memset( m_pbSPIVMPFlag      , 0,                     m_uiNumPartition * sizeof( *m_pbSPIVMPFlag ) );   
-#endif
-#if NH_3D_SDC_INTRA
   memset( m_pbSDCFlag, false, m_uiNumPartition * sizeof( *m_pbSDCFlag ) );
-#endif
-#if NH_3D_DBBP
   memset( m_pbDBBPFlag , false, m_uiNumPartition * sizeof( *m_pbDBBPFlag ));
 #endif
@@ -624,10 +570,6 @@
   }
 
-#if NH_3D_ARP
+#if NH_3D
   memset( m_puhARPW      ,      0,        m_uiNumPartition * sizeof( *m_puhARPW )         );
-#endif
-
-
-#if NH_3D_DMM
   for( Int i = 0; i < NUM_DMM; i++ )
   {
@@ -635,8 +577,6 @@
     memset( m_dmmDeltaDC[i][1], 0,                        m_uiNumPartition * sizeof( *m_dmmDeltaDC[i][1] ) );
   }
-  memset( m_dmm1WedgeTabIdx,    0,                        m_uiNumPartition * sizeof( *m_dmm1WedgeTabIdx   ) );
-#endif
-#if NH_3D_SDC_INTRA
-    memset( m_pbSDCFlag,     false,                m_uiNumPartition * sizeof( *m_pbSDCFlag ) );
+    memset( m_dmm1WedgeTabIdx,    0,                        m_uiNumPartition * sizeof( *m_dmm1WedgeTabIdx   ) );
+    memset( m_pbSDCFlag      ,     false,                m_uiNumPartition * sizeof( *m_pbSDCFlag ) );
     memset( m_apSegmentDCOffset[0],     0,                m_uiNumPartition * sizeof( *m_apSegmentDCOffset[0] ) );
     memset( m_apSegmentDCOffset[1],     0,                m_uiNumPartition * sizeof( *m_apSegmentDCOffset[1] ) );
@@ -667,10 +607,4 @@
   m_pCtuAboveRight  = NULL;
 
-
-  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
-  {
-    m_apcCUColocated[i]  = NULL;
-  }
-
   UInt frameWidthInCtus = pcPic->getFrameWidthInCtus();
   if ( m_ctuRsAddr % frameWidthInCtus )
@@ -692,13 +626,4 @@
   {
     m_pCtuAboveRight = pcPic->getCtu( m_ctuRsAddr - frameWidthInCtus + 1 );
-  }
-
-  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
-  {
-    const RefPicList rpl=RefPicList(i);
-    if ( getSlice()->getNumRefIdx( rpl ) > 0 )
-    {
-      m_apcCUColocated[rpl] = getSlice()->getRefPic( rpl, 0)->getCtu( m_ctuRsAddr );
-    }
   }
 }
@@ -743,5 +668,5 @@
     }
     m_skipFlag[ui]      = false;
-#if NH_3D_DIS
+#if NH_3D
     m_bDISFlag[ui]      = false;
     m_ucDISType[ui]     = 0;
@@ -755,8 +680,6 @@
     m_pbMergeFlag[ui]   = 0;
     m_puhMergeIndex[ui] = 0;
-#if NH_3D_VSP
+#if NH_3D
     m_piVSPFlag[ui]     = 0;
-#endif
-#if NH_3D_SPIVMP
     m_pbSPIVMPFlag[ui] = 0;
 #endif
@@ -772,27 +695,17 @@
       m_puhCbf[comp][ui] = 0;
     }
-#if NH_3D_ARP
-      m_puhARPW[ui] = 0;
-#endif
-#if NH_3D_IC
-      m_pbICFlag[ui]  = false;
-#endif
-
-
-#if NH_3D_DMM
+#if NH_3D
+    m_puhARPW[ui] = 0;
+    m_pbICFlag[ui]  = false;
     for( Int i = 0; i < NUM_DMM; i++ )
     {
-      m_dmmDeltaDC[i][0] [ui] = 0;
-      m_dmmDeltaDC[i][1] [ui] = 0;
-    }
-    m_dmm1WedgeTabIdx    [ui] = 0;
-#endif
-#if NH_3D_SDC_INTRA
-      m_pbSDCFlag           [ui] = false;
-      m_apSegmentDCOffset[0][ui] = 0;
-      m_apSegmentDCOffset[1][ui] = 0;
-#endif
-#if NH_3D_DBBP
-      m_pbDBBPFlag[ui] = false;
+      m_dmmDeltaDC[i][0]  [ui] = 0;
+      m_dmmDeltaDC[i][1]  [ui] = 0;
+    }
+    m_dmm1WedgeTabIdx     [ui] = 0;
+    m_pbSDCFlag           [ui] = false;
+    m_apSegmentDCOffset[0][ui] = 0;
+    m_apSegmentDCOffset[1][ui] = 0;
+    m_pbDBBPFlag          [ui] = false;
 #endif
   }
@@ -849,8 +762,6 @@
   memset( m_pbMergeFlag,        0, iSizeInBool  );
   memset( m_puhMergeIndex,      0, iSizeInUchar );
-#if NH_3D_VSP
+#if NH_3D
   memset( m_piVSPFlag,          0, sizeof( SChar ) * m_uiNumPartition );
-#endif
-#if NH_3D_SPIVMP
   memset( m_pbSPIVMPFlag,       0, sizeof( Bool  ) * m_uiNumPartition );
 #endif
@@ -876,11 +787,7 @@
   memset( m_puhHeight,         uhHeight, iSizeInUchar );
   memset( m_pbIPCMFlag,        0, iSizeInBool  );
-#if NH_3D_ARP
+#if NH_3D
   memset( m_puhARPW,           0, iSizeInUchar  );
-#endif
-#if NH_3D_IC
   memset( m_pbICFlag,          0, iSizeInBool  );
-#endif
-#if NH_3D_DMM
   for( Int i = 0; i < NUM_DMM; i++ )
   {
@@ -889,11 +796,7 @@
   }
   memset( m_dmm1WedgeTabIdx,    0, sizeof(UInt) * m_uiNumPartition );
-#endif
-#if NH_3D_SDC_INTRA
   memset( m_pbSDCFlag,            0, sizeof(Bool) * m_uiNumPartition  );
   memset( m_apSegmentDCOffset[0], 0, sizeof(Pel) * m_uiNumPartition   );
   memset( m_apSegmentDCOffset[1], 0, sizeof(Pel) * m_uiNumPartition   );
-#endif
-#if NH_3D_DBBP
   memset( m_pbDBBPFlag,         0, sizeof(Bool) * m_uiNumPartition  );
 #endif
@@ -902,5 +805,5 @@
   {
     m_skipFlag[ui]   = false;
-#if NH_3D_DIS
+#if NH_3D
     m_bDISFlag[ui]   = false;
     m_ucDISType[ui]  = 0;
@@ -918,36 +821,22 @@
       m_apiMVPNum[rpl][ui] = -1;
     }
-#if NH_3D_DIS
-      m_bDISFlag[ui]    = pcCU->getDISFlag(uiPartOffset+ui);
-      m_ucDISType[ui]   = pcCU->getDISType(uiPartOffset+ui);
-#endif
-#if NH_3D_VSP
-    m_piVSPFlag[ui] = pcCU->m_piVSPFlag[uiPartOffset+ui];
-    m_pDvInfo[ ui ] = pcCU->m_pDvInfo[uiPartOffset+ui];
-#endif
-#if NH_3D_SPIVMP
-    m_pbSPIVMPFlag[ui]=pcCU->m_pbSPIVMPFlag[uiPartOffset+ui];
-#endif
-#if NH_3D_ARP
-      m_puhARPW           [ui] = pcCU->getARPW( uiPartOffset+ui );
-#endif
-#if NH_3D_IC
-      m_pbICFlag          [ui] = pcCU->m_pbICFlag[uiPartOffset+ui];
-#endif
-#if NH_3D_DMM
-  for( Int i = 0; i < NUM_DMM; i++ )
-  {
-    m_dmmDeltaDC[i][0] [ui] = pcCU->m_dmmDeltaDC[i][0] [uiPartOffset+ui];
-    m_dmmDeltaDC[i][1] [ui] = pcCU->m_dmmDeltaDC[i][1] [uiPartOffset+ui];
-  }
-  m_dmm1WedgeTabIdx    [ui] = pcCU->m_dmm1WedgeTabIdx  [uiPartOffset+ui];
-#endif
-#if NH_3D_SDC_INTRA
+#if NH_3D
+    m_bDISFlag    [ui] = pcCU->getDISFlag(uiPartOffset+ui);
+    m_ucDISType   [ui] = pcCU->getDISType(uiPartOffset+ui);
+    m_piVSPFlag   [ui] = pcCU->m_piVSPFlag[uiPartOffset+ui];
+    m_pDvInfo     [ui] = pcCU->m_pDvInfo[uiPartOffset+ui];
+    m_pbSPIVMPFlag[ui] = pcCU->m_pbSPIVMPFlag[uiPartOffset+ui];
+    m_puhARPW     [ui] = pcCU->getARPW( uiPartOffset+ui );
+    m_pbICFlag    [ui] = pcCU->m_pbICFlag[uiPartOffset+ui];
+    for( Int i = 0; i < NUM_DMM; i++ )
+    {
+      m_dmmDeltaDC[i][0] [ui] = pcCU->m_dmmDeltaDC[i][0] [uiPartOffset+ui];
+      m_dmmDeltaDC[i][1] [ui] = pcCU->m_dmmDeltaDC[i][1] [uiPartOffset+ui];
+    }
+    m_dmm1WedgeTabIdx    [ui] = pcCU->m_dmm1WedgeTabIdx  [uiPartOffset+ui];
     m_pbSDCFlag           [ui] = pcCU->m_pbSDCFlag            [ uiPartOffset + ui ];
     m_apSegmentDCOffset[0][ui] = pcCU->m_apSegmentDCOffset[0] [ uiPartOffset + ui ];
     m_apSegmentDCOffset[1][ui] = pcCU->m_apSegmentDCOffset[1] [ uiPartOffset + ui ];
-#endif
-#if NH_3D_DBBP
-      m_pbDBBPFlag[ui]=pcCU->m_pbDBBPFlag[uiPartOffset+ui];
+    m_pbDBBPFlag[ui]=pcCU->m_pbDBBPFlag[uiPartOffset+ui];
 #endif
   }
@@ -973,9 +862,4 @@
   m_pCtuAboveLeft   = pcCU->getCtuAboveLeft();
   m_pCtuAboveRight  = pcCU->getCtuAboveRight();
-
-  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
-  {
-    m_apcCUColocated[i] = pcCU->getCUColocated(RefPicList(i));
-  }
 }
 
@@ -1009,5 +893,5 @@
 
   m_skipFlag=pcCU->getSkipFlag()          + uiPart;
-#if NH_3D_DIS
+#if NH_3D
   m_bDISFlag     = pcCU->getDISFlag()     + uiPart;
   m_ucDISType    = pcCU->getDISType()     + uiPart;
@@ -1019,20 +903,13 @@
   m_pePredMode=pcCU->getPredictionMode()  + uiPart;
   m_CUTransquantBypass  = pcCU->getCUTransquantBypass()+uiPart;
-#if NH_3D_NBDV
+#if NH_3D
   m_pDvInfo             = pcCU->getDvInfo()           + uiPart;
 #endif
-
   m_pbMergeFlag         = pcCU->getMergeFlag()        + uiPart;
   m_puhMergeIndex       = pcCU->getMergeIndex()       + uiPart;
-#if NH_3D_VSP
+#if NH_3D
   m_piVSPFlag           = pcCU->getVSPFlag()          + uiPart;
-#endif
-#if NH_3D_SPIVMP
-  m_pbSPIVMPFlag        = pcCU->getSPIVMPFlag()          + uiPart;
-#endif
-#if NH_3D_ARP
+  m_pbSPIVMPFlag        = pcCU->getSPIVMPFlag()       + uiPart;
   m_puhARPW             = pcCU->getARPW()             + uiPart;
-#endif
-#if NH_3D_IC
   m_pbICFlag            = pcCU->getICFlag()           + uiPart;
 #endif
@@ -1053,5 +930,5 @@
     m_explicitRdpcmMode[comp]             = pcCU->getExplicitRdpcmMode(ComponentID(comp))             + uiPart;
   }
-#if NH_3D_DMM
+#if NH_3D
   for( Int i = 0; i < NUM_DMM; i++ )
   {
@@ -1060,11 +937,7 @@
   }
   m_dmm1WedgeTabIdx    = pcCU->getDmm1WedgeTabIdx()  + uiPart;
-#endif
-#if NH_3D_SDC_INTRA
   m_pbSDCFlag               = pcCU->getSDCFlag()              + uiPart;
   m_apSegmentDCOffset[0]    = pcCU->getSDCSegmentDCOffset(0)  + uiPart;
   m_apSegmentDCOffset[1]    = pcCU->getSDCSegmentDCOffset(1)  + uiPart;
-#endif  
-#if NH_3D_DBBP
   m_pbDBBPFlag              = pcCU->getDBBPFlag()         + uiPart;
 #endif
@@ -1084,5 +957,4 @@
   {
     const RefPicList rpl=RefPicList(i);
-    m_apcCUColocated[rpl] = pcCU->getCUColocated(rpl);
     m_apiMVPIdx[rpl]=pcCU->getMVPIdx(rpl)  + uiPart;
     m_apiMVPNum[rpl]=pcCU->getMVPNum(rpl)  + uiPart;
@@ -1113,5 +985,5 @@
 }
 
-#if NH_3D_NBDV
+#if NH_3D
 Void TComDataCU::copyDVInfoFrom (TComDataCU* pcCU, UInt uiAbsPartIdx)
 {
@@ -1121,5 +993,5 @@
 
 // Copy inter prediction info from the biggest CU
-#if NH_3D_NBDV
+#if NH_3D
 Void TComDataCU::copyInterPredInfoFrom    ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList   , Bool bNBDV )
 #else
@@ -1141,11 +1013,7 @@
   m_pCtuLeft           = pcCU->getCtuLeft();
 
-  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
-  {
-    m_apcCUColocated[i]  = pcCU->getCUColocated(RefPicList(i));
-  }
 
   m_skipFlag           = pcCU->getSkipFlag ()             + uiAbsPartIdx;
-#if NH_3D_DIS
+#if NH_3D
   m_bDISFlag           = pcCU->getDISFlag ()              + uiAbsPartIdx;
   m_ucDISType          = pcCU->getDISType()               + uiAbsPartIdx;
@@ -1153,5 +1021,5 @@
 
   m_pePartSize         = pcCU->getPartitionSize ()        + uiAbsPartIdx;
-#if NH_3D_NBDV
+#if NH_3D
   if(bNBDV == true)
   {
@@ -1163,37 +1031,30 @@
   {
 #endif
-  m_pePredMode         = pcCU->getPredictionMode()        + uiAbsPartIdx;
-  m_ChromaQpAdj        = pcCU->getChromaQpAdj()           + uiAbsPartIdx;
-  m_CUTransquantBypass = pcCU->getCUTransquantBypass()    + uiAbsPartIdx;
-  m_puhInterDir        = pcCU->getInterDir      ()        + uiAbsPartIdx;
-
-  m_puhDepth           = pcCU->getDepth ()                + uiAbsPartIdx;
-  m_puhWidth           = pcCU->getWidth ()                + uiAbsPartIdx;
-  m_puhHeight          = pcCU->getHeight()                + uiAbsPartIdx;
-
-  m_pbMergeFlag        = pcCU->getMergeFlag()             + uiAbsPartIdx;
-  m_puhMergeIndex      = pcCU->getMergeIndex()            + uiAbsPartIdx;
-#if NH_3D_VSP
-  m_piVSPFlag          = pcCU->getVSPFlag()               + uiAbsPartIdx;
-  m_pDvInfo            = pcCU->getDvInfo()                + uiAbsPartIdx;
-#endif
-#if NH_3D_SPIVMP
-  m_pbSPIVMPFlag       = pcCU->getSPIVMPFlag()            + uiAbsPartIdx;
-#endif
-
-  m_apiMVPIdx[eRefPicList] = pcCU->getMVPIdx(eRefPicList) + uiAbsPartIdx;
-  m_apiMVPNum[eRefPicList] = pcCU->getMVPNum(eRefPicList) + uiAbsPartIdx;
-#if NH_3D_ARP
-  m_puhARPW            = pcCU->getARPW()                  + uiAbsPartIdx;
-#endif    
-#if NH_3D_DBBP
-  m_pbDBBPFlag       = pcCU->getDBBPFlag()              + uiAbsPartIdx;
-#endif
-
-  m_acCUMvField[ eRefPicList ].linkToWithOffset( pcCU->getCUMvField(eRefPicList), uiAbsPartIdx );
-#if NH_3D_NBDV
-  }
-#endif
-#if NH_3D_IC
+    m_pePredMode         = pcCU->getPredictionMode()        + uiAbsPartIdx;
+    m_ChromaQpAdj        = pcCU->getChromaQpAdj()           + uiAbsPartIdx;
+    m_CUTransquantBypass = pcCU->getCUTransquantBypass()    + uiAbsPartIdx;
+    m_puhInterDir        = pcCU->getInterDir      ()        + uiAbsPartIdx;
+
+    m_puhDepth           = pcCU->getDepth ()                + uiAbsPartIdx;
+    m_puhWidth           = pcCU->getWidth ()                + uiAbsPartIdx;
+    m_puhHeight          = pcCU->getHeight()                + uiAbsPartIdx;
+
+    m_pbMergeFlag        = pcCU->getMergeFlag()             + uiAbsPartIdx;
+    m_puhMergeIndex      = pcCU->getMergeIndex()            + uiAbsPartIdx;
+#if NH_3D
+    m_piVSPFlag          = pcCU->getVSPFlag()               + uiAbsPartIdx;
+    m_pDvInfo            = pcCU->getDvInfo()                + uiAbsPartIdx;
+    m_pbSPIVMPFlag       = pcCU->getSPIVMPFlag()            + uiAbsPartIdx;
+#endif
+    m_apiMVPIdx[eRefPicList] = pcCU->getMVPIdx(eRefPicList) + uiAbsPartIdx;
+    m_apiMVPNum[eRefPicList] = pcCU->getMVPNum(eRefPicList) + uiAbsPartIdx;
+#if NH_3D
+    m_puhARPW            = pcCU->getARPW()                  + uiAbsPartIdx;
+    m_pbDBBPFlag       = pcCU->getDBBPFlag()              + uiAbsPartIdx;
+#endif
+
+    m_acCUMvField[ eRefPicList ].linkToWithOffset( pcCU->getCUMvField(eRefPicList), uiAbsPartIdx );
+#if NH_3D
+  }
   m_pbICFlag           = pcCU->getICFlag()                + uiAbsPartIdx;
 #endif
@@ -1221,5 +1082,5 @@
   Int sizeInChar  = sizeof( SChar ) * uiNumPartition;
   memcpy( m_skipFlag   + uiOffset, pcCU->getSkipFlag(),       sizeof( *m_skipFlag )   * uiNumPartition );
-#if NH_3D_DIS
+#if NH_3D
   memcpy( m_bDISFlag   + uiOffset, pcCU->getDISFlag(),        sizeof( *m_bDISFlag )   * uiNumPartition );
   memcpy( m_ucDISType  + uiOffset, pcCU->getDISType(),        sizeof( *m_ucDISType )  * uiNumPartition);
@@ -1232,9 +1093,7 @@
   memcpy( m_pbMergeFlag         + uiOffset, pcCU->getMergeFlag(),         iSizeInBool  );
   memcpy( m_puhMergeIndex       + uiOffset, pcCU->getMergeIndex(),        iSizeInUchar );
-#if NH_3D_VSP
+#if NH_3D
   memcpy( m_piVSPFlag           + uiOffset, pcCU->getVSPFlag(),           sizeof( SChar ) * uiNumPartition );
   memcpy( m_pDvInfo             + uiOffset, pcCU->getDvInfo(),            sizeof( *m_pDvInfo ) * uiNumPartition );
-#endif
-#if NH_3D_SPIVMP  || NH_3D_DBBP
   memcpy( m_pbSPIVMPFlag        + uiOffset, pcCU->getSPIVMPFlag(),        sizeof( Bool ) * uiNumPartition );
 #endif
@@ -1255,5 +1114,5 @@
     memcpy( m_explicitRdpcmMode[comp]             + uiOffset, pcCU->getExplicitRdpcmMode(ComponentID(comp))            , iSizeInUchar );
   }
-#if NH_3D_DMM
+#if NH_3D
   for( Int i = 0; i < NUM_DMM; i++ )
   {
@@ -1262,14 +1121,8 @@
   }
   memcpy( m_dmm1WedgeTabIdx    + uiOffset, pcCU->getDmm1WedgeTabIdx(),         sizeof(UInt) * uiNumPartition );
-#endif
-#if NH_3D_SDC_INTRA
   memcpy( m_pbSDCFlag             + uiOffset, pcCU->getSDCFlag(), sizeof( *m_pbSDCFlag ) * uiNumPartition  );
   memcpy( m_apSegmentDCOffset[0]  + uiOffset, pcCU->getSDCSegmentDCOffset(0), sizeof( Pel ) * uiNumPartition);
   memcpy( m_apSegmentDCOffset[1]  + uiOffset, pcCU->getSDCSegmentDCOffset(1), sizeof( Pel ) * uiNumPartition);
-#endif
-#if NH_3D_DBBP
   memcpy( m_pbDBBPFlag          + uiOffset, pcCU->getDBBPFlag(),          iSizeInBool  );
-#endif
-#if NH_3D_ARP
   memcpy( m_puhARPW             + uiOffset, pcCU->getARPW(),              iSizeInUchar );
 #endif
@@ -1291,5 +1144,4 @@
     memcpy( m_apiMVPIdx[rpl] + uiOffset, pcCU->getMVPIdx(rpl), iSizeInUchar );
     memcpy( m_apiMVPNum[rpl] + uiOffset, pcCU->getMVPNum(rpl), iSizeInUchar );
-    m_apcCUColocated[rpl] = pcCU->getCUColocated(rpl);
   }
 
@@ -1314,5 +1166,5 @@
   }
 
-#if NH_3D_IC
+#if NH_3D
   memcpy( m_pbICFlag            + uiOffset, pcCU->getICFlag(),            iSizeInBool );
 #endif
@@ -1338,5 +1190,5 @@
 
   memcpy( pCtu->getSkipFlag() + m_absZIdxInCtu, m_skipFlag, sizeof( *m_skipFlag ) * m_uiNumPartition );
-#if NH_3D_DIS
+#if NH_3D
   memcpy( pCtu->getDISFlag()  + m_absZIdxInCtu, m_bDISFlag, sizeof( *m_bDISFlag )  * m_uiNumPartition );
   memcpy( pCtu->getDISType()  + m_absZIdxInCtu, m_ucDISType, sizeof( *m_ucDISType ) * m_uiNumPartition );
@@ -1344,5 +1196,5 @@
 
   memcpy( pCtu->getQP() + m_absZIdxInCtu, m_phQP, sizeInChar  );
-#if NH_3D_NBDV
+#if NH_3D
   memcpy( pCtu->getDvInfo() + m_absZIdxInCtu, m_pDvInfo, sizeof(* m_pDvInfo) * m_uiNumPartition );
 #endif
@@ -1354,15 +1206,11 @@
   memcpy( pCtu->getMergeFlag()         + m_absZIdxInCtu, m_pbMergeFlag,         iSizeInBool  );
   memcpy( pCtu->getMergeIndex()        + m_absZIdxInCtu, m_puhMergeIndex,       iSizeInUchar );
-#if NH_3D_VSP
+#if NH_3D
   memcpy( pCtu->getVSPFlag()           + m_absZIdxInCtu, m_piVSPFlag,           sizeof( SChar ) * m_uiNumPartition );
-#endif
-#if NH_3D_DBBP
   memcpy( pCtu->getDvInfo()            + m_absZIdxInCtu, m_pDvInfo,             sizeof( *m_pDvInfo ) * m_uiNumPartition );
-#endif
-#if NH_3D_SPIVMP
   memcpy( pCtu->getSPIVMPFlag()        + m_absZIdxInCtu, m_pbSPIVMPFlag,        sizeof( Bool ) * m_uiNumPartition );
 #endif
 
-for (UInt ch=0; ch<numValidChan; ch++)
+  for (UInt ch=0; ch<numValidChan; ch++)
   {
     memcpy( pCtu->getIntraDir(ChannelType(ch)) + m_absZIdxInCtu, m_puhIntraDir[ch], iSizeInUchar);
@@ -1380,5 +1228,5 @@
   }
 
-#if NH_3D_DMM
+#if NH_3D
   for( Int i = 0; i < NUM_DMM; i++ )
   {
@@ -1386,15 +1234,10 @@
     memcpy( pCtu->getDmmDeltaDC( (DmmID)i, 1 ) + m_absZIdxInCtu, m_dmmDeltaDC[i][1], sizeof(Pel ) * m_uiNumPartition );
   }
+
   memcpy( pCtu->getDmm1WedgeTabIdx()           + m_absZIdxInCtu, m_dmm1WedgeTabIdx,  sizeof(UInt) * m_uiNumPartition );
-#endif
-#if NH_3D_SDC_INTRA
   memcpy( pCtu->getSDCFlag()             + m_absZIdxInCtu, m_pbSDCFlag, sizeof(Bool) * m_uiNumPartition );
   memcpy( pCtu->getSDCSegmentDCOffset(0) + m_absZIdxInCtu, m_apSegmentDCOffset[0], sizeof( Pel ) * m_uiNumPartition);
   memcpy( pCtu->getSDCSegmentDCOffset(1) + m_absZIdxInCtu, m_apSegmentDCOffset[1], sizeof( Pel ) * m_uiNumPartition);
-#endif
-#if NH_3D_DBBP
   memcpy( pCtu->getDBBPFlag()          + m_absZIdxInCtu, m_pbDBBPFlag,          iSizeInBool  );
-#endif
-#if NH_3D_ARP
   memcpy( pCtu->getARPW()              + m_absZIdxInCtu, m_puhARPW,             iSizeInUchar );
 #endif
@@ -1432,14 +1275,9 @@
   }
 
-#if NH_3D_IC
+#if NH_3D
   memcpy( pCtu->getICFlag() + m_absZIdxInCtu, m_pbICFlag, sizeof( *m_pbICFlag ) * m_uiNumPartition );
 #endif
   pCtu->getTotalBins() = m_uiTotalBins;
 }
-#if H_3D_SPIVMP
-  memcpy( rpcCU->getSPIVMPFlag()        + uiPartOffset, m_pbSPIVMPFlag,        sizeof(Bool) * uiQNumPart );
-#endif
-
-
 
 // --------------------------------------------------------------------------------------------------------------------
@@ -1786,5 +1624,5 @@
 Bool TComDataCU::isLosslessCoded(UInt absPartIdx) const
 {
-  return (getSlice()->getPPS()->getTransquantBypassEnableFlag() && getCUTransquantBypass (absPartIdx));
+  return (getSlice()->getPPS()->getTransquantBypassEnabledFlag() && getCUTransquantBypass (absPartIdx));
 }
 
@@ -1842,5 +1680,5 @@
   }
   iLeftIntraDir  = pcCULeft ? ( pcCULeft->isIntra( LeftPartIdx ) ? pcCULeft->getIntraDir( chType, LeftPartIdx ) : DC_IDX ) : DC_IDX;
-#if NH_3D_DMM
+#if NH_3D
   mapDmmToIntraDir( iLeftIntraDir );
 #endif
@@ -1854,5 +1692,5 @@
   }
   iAboveIntraDir = pcCUAbove ? ( pcCUAbove->isIntra( AbovePartIdx ) ? pcCUAbove->getIntraDir( chType, AbovePartIdx ) : DC_IDX ) : DC_IDX;
-#if NH_3D_DMM
+#if NH_3D
   mapDmmToIntraDir( iAboveIntraDir );
 #endif
@@ -1990,5 +1828,5 @@
   return uiCtx;
 }
-#if NH_3D_ARP
+#if NH_3D
 UInt TComDataCU::getCTXARPWFlag( UInt uiAbsPartIdx )
 {
@@ -2001,6 +1839,5 @@
   return uiCtx;
 }
-#endif
-#if NH_3D_DBBP
+
 Pel* TComDataCU::getVirtualDepthBlock(UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt& uiDepthStride)
 {
@@ -2016,18 +1853,4 @@
   assert( !getSlice()->getIsDepth() );
   
-#if H_3D_FCO
-  TComPic* depthPic = getSlice()->getIvPic(true, getSlice()->getViewIndex() );
-  
-  if( depthPic && depthPic->getPicYuvRec() != NULL && depthPic->getIsDepth() )  // depth first
-  {
-    depthPicYuv = depthPic->getPicYuvRec();
-    depthPicYuv->extendPicBorder();
-    
-    // get collocated depth block for current CU
-    uiDepthStride = depthPicYuv->getStride();
-    pDepthPels    = depthPicYuv->getLumaAddr( getAddr(), uiAbsPartIdx );
-  }
-  else  // texture first
-#else
   {
     DisInfo DvInfo = getDvInfo(uiAbsPartIdx);
@@ -2052,7 +1875,5 @@
     
     Bool depthRefineFlag = false;
-#if NH_3D_NBDV_REF
     depthRefineFlag = m_pcSlice->getDepthRefinementFlag();
-#endif // NH_3D_NBDV_REF
     
     TComMv cDv = depthRefineFlag ? DvInfo.m_acDoNBDV : DvInfo.m_acNBDV;
@@ -2067,5 +1888,4 @@
     pDepthPels = depthPicYuv->getAddr(COMPONENT_Y) + depthPosX + depthPosY * uiDepthStride;
   }
-#endif
   
   AOF( depthPicYuv != NULL );
@@ -2075,7 +1895,5 @@
   return pDepthPels;
 }
-#endif
-
-#if NH_3D_DBBP
+
 Void TComDataCU::setDBBPFlagSubParts ( Bool bDBBPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
 {
@@ -2170,5 +1988,5 @@
 }
 
-#if NH_3D_DIS
+#if NH_3D
 Void TComDataCU::setDISFlagSubParts( Bool bDIS, UInt uiAbsPartIdx, UInt uiDepth )
 {
@@ -2336,5 +2154,5 @@
 }
 
-#if NH_3D_SDC_INTRA
+#if NH_3D
 Void TComDataCU::setSDCFlagSubParts ( Bool bSDCFlag, UInt absPartIdx, UInt depth )
 {
@@ -2349,7 +2167,5 @@
     UInt lumaPredMode = getIntraDir( CHANNEL_TYPE_LUMA, uiAbsPartIdx );
     if( lumaPredMode < NUM_INTRA_MODE ) { return true; }
-#if NH_3D_DMM
     if( isDmmMode( lumaPredMode )     ) { return true; }
-#endif
   }
   return false;
@@ -2367,12 +2183,10 @@
 }
 
-#if NH_3D_SPIVMP
+#if NH_3D
 Void TComDataCU::setSPIVMPFlagSubParts( Bool bSPIVMPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
 {
   setSubPart<Bool>( bSPIVMPFlag, m_pbSPIVMPFlag, uiAbsPartIdx, uiDepth, uiPartIdx );
 }
-#endif
-
-#if NH_3D_VSP
+
 Void TComDataCU::setVSPFlagSubParts( SChar iVSPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
 {
@@ -2599,5 +2413,5 @@
 
 // This is for use by a leaf/sub CU object only, with no additional AbsPartIdx
-#if NH_3D_IC || NH_3D_VSP
+#if NH_3D
 Void TComDataCU::getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight, UInt uiAbsPartIdx, Bool bLCU) const
 {
@@ -2941,7 +2755,5 @@
     );
 }
-#endif
-
-#if NH_3D_VSP
+
 /** Add a VSP merging candidate
  * \Inputs
@@ -2997,7 +2809,5 @@
         predFlag[iRefListIdX] = 1;
         mvVSP[0+iRefListIdX].setMvField( pDInfo->m_acNBDV, i );
-#if NH_3D_NBDV
         mvVSP[0+iRefListIdX].getMv().setIDVFlag (false);
-#endif
       }
     }
@@ -3005,9 +2815,5 @@
 
   dirVSP = (predFlag[0] | (predFlag[1] << 1));
-  m_mergCands[MRG_VSP].setCand( mvVSP, dirVSP, true
-#if NH_3D_SPIVMP
-    , false
-#endif
-    );
+  m_mergCands[MRG_VSP].setCand( mvVSP, dirVSP, true    , false);
   if ( mrgCandIdx == iCount )
   {
@@ -3019,7 +2825,5 @@
   return false;
 }
-#endif
-
-#if NH_3D_IV_MERGE
+
 inline Bool TComDataCU::xAddIvMRGCand( Int mrgCandIdx, Int& iCount, Int* ivCandDir, TComMv* ivCandMv, Int* ivCandRefIdx )
 {
@@ -3052,5 +2856,4 @@
       if(!bRemove)
       {
-#if NH_3D_NBDV
         if(iLoop) // For IvMcShift candidate
         {
@@ -3058,5 +2861,4 @@
           tmpMV[1].getMv().setIDVFlag (false);
         }
-#endif
         m_mergCands[MRG_IVSHIFT].setCand(tmpMV, tmpDir, false, false);
         if( mrgCandIdx == iCount )
@@ -3072,6 +2874,4 @@
 } 
 
-#endif
-#if NH_3D_MLC
 /** Construct a extended list of merging candidates
  * \param pcMvFieldNeighbours
@@ -3081,13 +2881,5 @@
  * \param numValidMergeCand
  */
-Void TComDataCU::buildMCL(TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours
-#if NH_3D_VSP
-  , Int* vspFlag
-#endif
-#if NH_3D_SPIVMP
-  , Bool* pbSPIVMPFlag
-#endif
-  , Int& numValidMergeCand
-  )
+Void TComDataCU::buildMCL(TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, Int* vspFlag  , Bool* pbSPIVMPFlag  , Int& numValidMergeCand  )
 {
   if (!( getSlice()->getIsDepth() || getSlice()->getViewIndex()>0))
@@ -3095,5 +2887,4 @@
     return;
   }
-
 
 #if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC
@@ -3119,7 +2910,5 @@
     extMergeCandList[ui<<1].setMvField(cZeroMv, NOT_VALID);
     extMergeCandList[(ui<<1)+1].setMvField(cZeroMv, NOT_VALID);
-#if NH_3D_VSP
     vspFlag[ui] = 0;
-#endif
   }
 
@@ -3129,12 +2918,5 @@
     if (m_mergCands[i].m_bAvailable)
     {
-      m_mergCands[i].getCand(iCount, extMergeCandList, uhInterDirNeighboursExt
-#if NH_3D_VSP
-        , vspFlag
-#endif
-#if NH_3D_SPIVMP
-        , pbSPIVMPFlag
-#endif
-        );
+      m_mergCands[i].getCand(iCount, extMergeCandList, uhInterDirNeighboursExt, vspFlag, pbSPIVMPFlag );
       iCount++;
       if (iCount >= getSlice()->getMaxNumMergeCand())
@@ -3229,26 +3011,15 @@
  * \param numValidMergeCand
  */
-Void TComDataCU::xGetInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours
-#if NH_3D_SPIVMP
-      , TComMvField* pcMvFieldSP, UChar* puhInterDirSP
-#endif
-      , Int& numValidMergeCand, Int mrgCandIdx
-)
-{
-#if NH_3D_IV_MERGE
+
+Void TComDataCU::xGetInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours, TComMvField* pcMvFieldSP, UChar* puhInterDirSP, Int& numValidMergeCand, Int mrgCandIdx )
+{
   TComMv cZeroMv;
   TComMvField tmpMV[2];  
-#endif
 
   //////////////////////////////////
   //////// GET DISPARITIES  ////////
   //////////////////////////////////
-#if NH_3D_IV_MERGE
   DisInfo cDisInfo = getDvInfo(uiAbsPartIdx);
   m_cDefaultDisInfo = cDisInfo;
-#elif NH_3D_VSP
-  // for xAddVspCand()
-  DisInfo cDisInfo = getDvInfo(uiAbsPartIdx);
-#endif
 
   if (!( getSlice()->getIsDepth() || getSlice()->getViewIndex()>0))
@@ -3268,24 +3039,13 @@
   deriveLeftRightTopIdxGeneral( uiAbsPartIdx, uiPUIdx, uiPartIdxLT, uiPartIdxRT );
   deriveLeftBottomIdxGeneral  ( uiAbsPartIdx, uiPUIdx, uiPartIdxLB );
-#if NH_3D_TEXT_MERGE
   Bool bMPIFlag   = getSlice()->getMpiFlag(); 
   Int  tmpDir;
-#endif 
-#if NH_3D_IV_MERGE || NH_3D_TEXT_MERGE
   Bool bIsDepth = getSlice()->getIsDepth();
-#endif
-
-#if NH_3D_IC
+
   Bool bICFlag = getICFlag(uiAbsPartIdx);
-#endif
-#if NH_3D_ARP
   Bool bARPFlag = getARPW(uiAbsPartIdx) > 0;
-#endif
-#if NH_3D_DBBP
   Bool bDBBPFlag = getDBBPFlag(uiAbsPartIdx);
   assert(bDBBPFlag == getDBBPFlag(0));  
-#endif
-
-#if NH_3D_NBDV
+
   for(Int i = 0; i < MRG_MAX_NUM_CANDS_MEM; i++)  
   {
@@ -3293,5 +3053,4 @@
     pcMFieldNeighbours[(i<<1)+1].getMv().setIDVFlag (false);
   }
-#endif
   // init containers
   for (Int i = 0; i<MRG_IVSHIFT+1; i++)
@@ -3310,22 +3069,5 @@
   if (getAvailableFlagA1())
   {
-    m_mergCands[MRG_A1].setCand( &pcMFieldNeighbours[m_numSpatialCands<<1], puhInterDirNeighbours[m_numSpatialCands]
-#if NH_3D_VSP
-    , (pcCULeft->getVSPFlag(uiLeftPartIdx) != 0
-#if NH_3D_IC
-      && !bICFlag
-#endif
-#if NH_3D_ARP
-      && !bARPFlag
-#endif
-#if NH_3D_DBBP
-      && !bDBBPFlag
-#endif
-      )
-#endif
-#if NH_3D_SPIVMP
-      , false
-#endif
-      ); 
+    m_mergCands[MRG_A1].setCand( &pcMFieldNeighbours[m_numSpatialCands<<1], puhInterDirNeighbours[m_numSpatialCands], (pcCULeft->getVSPFlag(uiLeftPartIdx) != 0 && !bICFlag && !bARPFlag&& !bDBBPFlag), false ); 
     m_numSpatialCands++;
   }
@@ -3334,12 +3076,5 @@
   if (getAvailableFlagB1())
   {
-    m_mergCands[MRG_B1].setCand( &pcMFieldNeighbours[m_numSpatialCands<<1], puhInterDirNeighbours[m_numSpatialCands]
-#if NH_3D_VSP
-    , false
-#endif
-#if NH_3D_SPIVMP
-      , false
-#endif
-      ); 
+    m_mergCands[MRG_B1].setCand( &pcMFieldNeighbours[m_numSpatialCands<<1], puhInterDirNeighbours[m_numSpatialCands], false, false ); 
     m_numSpatialCands++;
   }
@@ -3348,12 +3083,5 @@
   if (getAvailableFlagB0())
   {
-    m_mergCands[MRG_B0].setCand( &pcMFieldNeighbours[m_numSpatialCands<<1], puhInterDirNeighbours[m_numSpatialCands]
-#if NH_3D_VSP
-    , false
-#endif
-#if NH_3D_SPIVMP
-      , false
-#endif
-      ); 
+    m_mergCands[MRG_B0].setCand( &pcMFieldNeighbours[m_numSpatialCands<<1], puhInterDirNeighbours[m_numSpatialCands], false, false ); 
     m_numSpatialCands++;
   }
@@ -3362,12 +3090,5 @@
   if (getAvailableFlagA0())
   {
-    m_mergCands[MRG_A0].setCand( &pcMFieldNeighbours[m_numSpatialCands<<1], puhInterDirNeighbours[m_numSpatialCands]
-#if NH_3D_VSP
-    , false
-#endif
-#if NH_3D_SPIVMP
-      , false
-#endif
-      ); 
+    m_mergCands[MRG_A0].setCand( &pcMFieldNeighbours[m_numSpatialCands<<1], puhInterDirNeighbours[m_numSpatialCands], false, false ); 
     m_numSpatialCands++;
   }
@@ -3376,17 +3097,8 @@
   if (getAvailableFlagB2())
   {
-    m_mergCands[MRG_B2].setCand( &pcMFieldNeighbours[m_numSpatialCands<<1], puhInterDirNeighbours[m_numSpatialCands]
-#if NH_3D_VSP
-    , false
-#endif
-#if NH_3D_SPIVMP
-      , false
-#endif
-      ); 
+    m_mergCands[MRG_B2].setCand( &pcMFieldNeighbours[m_numSpatialCands<<1], puhInterDirNeighbours[m_numSpatialCands], false, false ); 
     m_numSpatialCands++;
   }
 
-
-#if NH_3D_TEXT_MERGE
 
   /////////////////////////////////////////////
@@ -3404,8 +3116,4 @@
 
     TComPic * pcTexPic = m_pcSlice->getTexturePic();
-#if H_3D_FCO
-    if (pcTexPic && pcTexPic->getReconMark())
-    {
-#endif    
       TComPicYuv*   pcTexRec = pcTexPic->getPicYuvRec  ();
       UInt          uiPartAddr;
@@ -3439,7 +3147,6 @@
 
       Int         iTexPosX, iTexPosY;
-#if NH_3D_INTEGER_MV_DEPTH
       const TComMv cMvRounding( 1 << ( 2 - 1 ), 1 << ( 2 - 1 ) );
-#endif
+
       Int         iCenterPosX = iCurrPosX + ( ( iWidth /  iPUWidth ) >> 1 )  * iPUWidth + ( iPUWidth >> 1 );
       Int         iCenterPosY = iCurrPosY + ( ( iHeight /  iPUHeight ) >> 1 )  * iPUHeight + (iPUHeight >> 1);
@@ -3474,10 +3181,6 @@
               {
                 bSPIVMPFlag = true;
-#if NH_3D_INTEGER_MV_DEPTH
                 TComMv cMv = cDefaultMvField.getMv() + cMvRounding;
                 cMv >>= 2;
-#else
-                TComMv cMv = cDefaultMvField.getMv();
-#endif
                 cMvFieldSaved[eCurrRefPicList].setMvField(cMv, iRefPicList) ;
                 break;
@@ -3516,10 +3219,6 @@
                 if( (cTexMvField.getRefIdx()>=0) && ( iValidDepRef >= 0 ) )
                 {
-#if NH_3D_INTEGER_MV_DEPTH
                   TComMv cMv = cTexMvField.getMv() + cMvRounding;
                   cMv >>=2;          
-#else
-                  TComMv cMv = cTexMvField.getMv();
-#endif         
                   pcMvFieldSP[2*iPartition + uiCurrRefListId].setMvField(cMv, iValidDepRef);
                 }
@@ -3541,7 +3240,5 @@
         }
       }
-#if H_3D_FCO
-    }
-#endif
+
     if( tmpDir != 0 )
     {
@@ -3568,7 +3265,5 @@
     }
   }
-#endif
-
-#if NH_3D_IV_MERGE
+
   /////////////////////////////////////////////////////////////////
   //////// DERIVE IvMC, IvMCShift,IvDCShift, IvDC  Candidates /////
@@ -3588,9 +3283,5 @@
   if ( ivMvPredFlag && cDisInfo.m_aVIdxCan!=-1)
   {
-#if NH_3D_IC
     getInterViewMergeCands(uiPUIdx, ivCandRefIdx, ivCandMv, &cDisInfo, ivCandDir , bIsDepth, pcMvFieldSP, puhInterDirSP, bICFlag );
-#else
-    getInterViewMergeCands(uiPUIdx, ivCandRefIdx, ivCandMv, &cDisInfo, ivCandDir , bIsDepth, pcMvFieldSP, puhInterDirSP, false );
-#endif
   }  
 
@@ -3648,7 +3339,5 @@
         spiMvpFlag = true;
       }
-#if NH_3D_DBBP
       spiMvpFlag &= !bDBBPFlag;
-#endif
 
       m_mergCands[MRG_IVMC].setCand( tmpMV, ivCandDir[0], false, spiMvpFlag);
@@ -3667,9 +3356,8 @@
     return;
   }
-#endif
+
 
   iCount += m_mergCands[MRG_A1].m_bAvailable + m_mergCands[MRG_B1].m_bAvailable;
 
-#if NH_3D_VSP
   /////////////////////////////////////////////////
   //////// VIEW SYNTHESIS PREDICTION (VSP) ////////
@@ -3677,18 +3365,9 @@
   if (iCount<getSlice()->getMaxNumMergeCand())
   {
-    if (
-      (!getAvailableFlagA1() || !(pcCULeft->getVSPFlag(uiLeftPartIdx) != 0)) &&
-#if NH_3D_IC
-      !bICFlag &&
-#endif
-#if NH_3D_ARP
-      !bARPFlag &&
-#endif
-#if NH_3D
+    if ( ( !getAvailableFlagA1() || !(pcCULeft->getVSPFlag(uiLeftPartIdx) != 0) ) &&
+      !bICFlag           &&
+      !bARPFlag          &&
       (nPSW + nPSH > 12) &&
-#endif
-#if NH_3D_DBBP
-      !bDBBPFlag &&
-#endif
+      !bDBBPFlag         &&
       xAddVspCand( mrgCandIdx, &cDisInfo, iCount ) )
     {
@@ -3702,9 +3381,7 @@
     }
   }
-#endif
 
   iCount += m_mergCands[MRG_B0].m_bAvailable;
 
-#if NH_3D_IV_MERGE 
   /////////////////////////////////////////////
   //////// INTER VIEW DISP COMP (IvDC) ////////
@@ -3740,8 +3417,6 @@
     if(!bRemoveSpa)
     {
-#if NH_3D_NBDV
       tmpMV[0].getMv().setIDVFlag (false);
       tmpMV[1].getMv().setIDVFlag (false);
-#endif
       m_mergCands[MRG_IVDC].setCand( tmpMV, ivCandDir[1], false, false);
 
@@ -3757,9 +3432,8 @@
     }
   } 
-#endif // H_3D_IV_MERGE 
+
 
   iCount += m_mergCands[MRG_A0].m_bAvailable + m_mergCands[MRG_B2].m_bAvailable;
 
-#if NH_3D_IV_MERGE
   ////////////////////////////////////////////////////
   //////// SHIFTED IV (IvMCShift + IvDCShift) ////////
@@ -3777,17 +3451,21 @@
     }
   }
-#endif
 }
 #endif
 
 //! Construct a list of merging candidates
-#if NH_3D
+
+
+#if MCTS_ENC_CHECK
+Void TComDataCU::getInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, UInt &numSpatialMergeCandidates, Int mrgCandIdx ) 
+#else
 Void TComDataCU::getInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx )
-#else
-Void TComDataCU::getInterMergeCandidates( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx ) const
+#endif
+#if !NH_3D  
+  const
 #endif
 {
   UInt uiAbsPartAddr = m_absZIdxInCtu + uiAbsPartIdx;
-#if NH_3D_MLC
+#if NH_3D
   Bool abCandIsInter[ MRG_MAX_NUM_CANDS_MEM ];
 #else
@@ -3823,5 +3501,5 @@
   if ( isAvailableA1 )
   {
-#if NH_3D_MLC
+#if NH_3D
     m_bAvailableFlagA1 = 1;
 #endif
@@ -3837,4 +3515,7 @@
     if ( mrgCandIdx == iCount )
     {
+#if MCTS_ENC_CHECK
+      numSpatialMergeCandidates = iCount + 1;
+#endif
       return;
     }
@@ -3845,4 +3526,7 @@
   if (iCount == getSlice()->getMaxNumMergeCand())
   {
+#if MCTS_ENC_CHECK
+    numSpatialMergeCandidates = iCount;
+#endif
     return;
   }
@@ -3858,5 +3542,5 @@
   if ( isAvailableB1 && (!isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCUAbove, uiAbovePartIdx ) ) )
   {
-#if NH_3D_MLC
+#if NH_3D
     m_bAvailableFlagB1 = 1;
 #endif
@@ -3872,4 +3556,7 @@
     if ( mrgCandIdx == iCount )
     {
+#if MCTS_ENC_CHECK
+      numSpatialMergeCandidates = iCount + 1;
+#endif
       return;
     }
@@ -3879,4 +3566,7 @@
   if (iCount == getSlice()->getMaxNumMergeCand())
   {
+#if MCTS_ENC_CHECK
+    numSpatialMergeCandidates = iCount;
+#endif
     return;
   }
@@ -3892,5 +3582,5 @@
   if ( isAvailableB0 && ( !isAvailableB1 || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveRight, uiAboveRightPartIdx ) ) )
   {
-#if NH_3D_MLC
+#if NH_3D
     m_bAvailableFlagB0 = 1;
 #endif
@@ -3906,4 +3596,7 @@
     if ( mrgCandIdx == iCount )
     {
+#if MCTS_ENC_CHECK
+      numSpatialMergeCandidates = iCount + 1;
+#endif
       return;
     }
@@ -3913,4 +3606,7 @@
   if (iCount == getSlice()->getMaxNumMergeCand())
   {
+#if MCTS_ENC_CHECK
+    numSpatialMergeCandidates = iCount;
+#endif
     return;
   }
@@ -3926,5 +3622,5 @@
   if ( isAvailableA0 && ( !isAvailableA1 || !pcCULeft->hasEqualMotion( uiLeftPartIdx, pcCULeftBottom, uiLeftBottomPartIdx ) ) )
   {
-#if NH_3D_MLC
+#if NH_3D
     m_bAvailableFlagA0 = 1;
 #endif
@@ -3940,4 +3636,7 @@
     if ( mrgCandIdx == iCount )
     {
+#if MCTS_ENC_CHECK
+      numSpatialMergeCandidates = iCount + 1;
+#endif
       return;
     }
@@ -3947,4 +3646,7 @@
   if (iCount == getSlice()->getMaxNumMergeCand())
   {
+#if MCTS_ENC_CHECK
+    numSpatialMergeCandidates = iCount;
+#endif
     return;
   }
@@ -3963,5 +3665,5 @@
         && ( !isAvailableB1 || !pcCUAbove->hasEqualMotion( uiAbovePartIdx, pcCUAboveLeft, uiAboveLeftPartIdx ) ) )
     {
-#if NH_3D_MLC
+#if NH_3D
       m_bAvailableFlagB2 = 1;
 #endif
@@ -3977,4 +3679,7 @@
       if ( mrgCandIdx == iCount )
       {
+#if MCTS_ENC_CHECK
+        numSpatialMergeCandidates = iCount + 1;
+#endif
         return;
       }
@@ -3985,7 +3690,13 @@
   if (iCount == getSlice()->getMaxNumMergeCand())
   {
+#if MCTS_ENC_CHECK
+    numSpatialMergeCandidates = iCount;
+#endif
     return;
   }
 
+#if MCTS_ENC_CHECK
+  numSpatialMergeCandidates = iCount;
+#endif
   if ( getSlice()->getEnableTMVPFlag() )
   {
@@ -4047,5 +3758,5 @@
     if ( getSlice()->isInterB() )
     {
-#if NH_3D_TMVP
+#if NH_3D
       iRefIdx = 0;
 #endif
@@ -4066,5 +3777,5 @@
       puhInterDirNeighbours[uiArrayAddr] = dir;
       abCandIsInter[uiArrayAddr] = true;
-#if NH_3D_NBDV
+#if NH_3D
       pcMvFieldNeighbours[iCount<<1    ].getMv().setIDVFlag (false);
       pcMvFieldNeighbours[(iCount<<1)+1].getMv().setIDVFlag (false);
@@ -4087,5 +3798,5 @@
   UInt uiCutoff = uiArrayAddr;
 
-#if NH_3D_MLC
+#if NH_3D
   if ( getSlice()->isInterB() && iCount<5)
 #else
@@ -4257,4 +3968,7 @@
   if (refIdx < 0)
   {
+#if MCTS_ENC_CHECK
+    pInfo->numSpatialMVPCandidates = 0;
+#endif
     return;
   }
@@ -4329,4 +4043,7 @@
   }
 
+#if MCTS_ENC_CHECK
+  pInfo->numSpatialMVPCandidates = pInfo->iN;
+#endif
   if (pInfo->iN < AMVP_MAX_NUM_CANDS && getSlice()->getEnableTMVPFlag() )
   {
@@ -4334,5 +4051,5 @@
     const UInt numPartInCtuWidth  = m_pcPic->getNumPartInCtuWidth();
     const UInt numPartInCtuHeight = m_pcPic->getNumPartInCtuHeight();
-#if NH_3D_TMVP
+#if NH_3D
     Int refIdx_Col = refIdx;
 #else
@@ -4372,5 +4089,5 @@
       }
     }
-#if NH_3D_TMVP
+#if NH_3D
         if ( ctuRsAddr >= 0 && xGetColMVP( eRefPicList, ctuRsAddr, absPartAddr, cColMv, refIdx_Col  , 0 ) )
 #else
@@ -4384,5 +4101,5 @@
       UInt uiPartIdxCenter;
       xDeriveCenterIdx( partIdx, uiPartIdxCenter );
-#if NH_3D_TMVP
+#if NH_3D
       if (xGetColMVP( eRefPicList, getCtuRsAddr(), uiPartIdxCenter,  cColMv, refIdx_Col , 0 )) 
 #else
@@ -4411,5 +4128,5 @@
   UInt partAddr;
 
-#if NH_3D_DBBP
+#if NH_3D
   if( getDBBPFlag(0) )
   {
@@ -4431,5 +4148,5 @@
   const TComSPS &sps=*(m_pcSlice->getSPS());
   Int  iMvShift = 2;
-#if NH_3D_INTEGER_MV_DEPTH
+#if NH_3D
   if( getSlice()->getIsDepth() )
     iMvShift = 0;
@@ -4663,5 +4380,5 @@
 }
 
-#if NH_3D_TMVP
+#if NH_3D
 Bool TComDataCU::xGetColMVP( const RefPicList eRefPicList, const Int ctuRsAddr, const Int partUnitIdx, TComMv& rcMv, Int& refIdx, Bool bMRG  ) const
 #else
@@ -4673,11 +4390,25 @@
   // use coldir.
   const TComPic    * const pColPic = getSlice()->getRefPic( RefPicList(getSlice()->isInterB() ? 1-getSlice()->getColFromL0Flag() : 0), getSlice()->getColRefIdx());
+#if REDUCED_ENCODER_MEMORY
+  if (!pColPic->getPicSym()->hasDPBPerCtuData())
+  {
+    return false;
+  }
+  const TComPicSym::DPBPerCtuData * const pColDpbCtu = &(pColPic->getPicSym()->getDPBPerCtuData(ctuRsAddr));
+  const TComSlice * const pColSlice = pColDpbCtu->getSlice();
+  if(pColDpbCtu->getPartitionSize(partUnitIdx)==NUMBER_OF_PART_SIZES)
+#else
   const TComDataCU * const pColCtu = pColPic->getCtu( ctuRsAddr );
   if(pColCtu->getPic()==0 || pColCtu->getPartitionSize(partUnitIdx)==NUMBER_OF_PART_SIZES)
+#endif
   {
     return false;
   }
 
+#if REDUCED_ENCODER_MEMORY
+  if (!pColDpbCtu->isInter(absPartAddr))
+#else
   if (!pColCtu->isInter(absPartAddr))
+#endif
   {
     return false;
@@ -4685,10 +4416,18 @@
 
   RefPicList eColRefPicList = getSlice()->getCheckLDC() ? eRefPicList : RefPicList(getSlice()->getColFromL0Flag());
+#if REDUCED_ENCODER_MEMORY
+  Int iColRefIdx            = pColDpbCtu->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(absPartAddr);
+#else
   Int iColRefIdx            = pColCtu->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(absPartAddr);
+#endif
 
   if (iColRefIdx < 0 )
   {
     eColRefPicList = RefPicList(1 - eColRefPicList);
+#if REDUCED_ENCODER_MEMORY
+    iColRefIdx = pColDpbCtu->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(absPartAddr);
+#else
     iColRefIdx = pColCtu->getCUMvField(RefPicList(eColRefPicList))->getRefIdx(absPartAddr);
+#endif
 
     if (iColRefIdx < 0 )
@@ -4698,14 +4437,17 @@
   }
 
-#if NH_3D_TMVP
+#if NH_3D
   Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic(eRefPicList, refIdx)->getIsLongTerm();
 #else
   const Bool bIsCurrRefLongTerm = m_pcSlice->getRefPic(eRefPicList, refIdx)->getIsLongTerm();
 #endif
+#if REDUCED_ENCODER_MEMORY
+  const Bool bIsColRefLongTerm  = pColSlice->getIsUsedAsLongTerm(eColRefPicList, iColRefIdx);
+#else
   const Bool bIsColRefLongTerm  = pColCtu->getSlice()->getIsUsedAsLongTerm(eColRefPicList, iColRefIdx);
-
+#endif
   if ( bIsCurrRefLongTerm != bIsColRefLongTerm )
   {
-#if NH_3D_TMVP
+#if NH_3D
     Int iAlterRefIdx  = m_pcSlice->getAlterRefIdx(eRefPicList);
     if(bMRG && iAlterRefIdx > 0)
@@ -4719,12 +4461,16 @@
 #endif
       return false;
-#if NH_3D_TMVP
+#if NH_3D
     }
 #endif
   }
   // Scale the vector.
+#if REDUCED_ENCODER_MEMORY
+  const TComMv &cColMv = pColDpbCtu->getCUMvField(eColRefPicList)->getMv(absPartAddr);
+#else
   const TComMv &cColMv = pColCtu->getCUMvField(eColRefPicList)->getMv(absPartAddr);
-
-#if NH_3D_TMVP
+#endif
+
+#if NH_3D
   if ( bIsCurrRefLongTerm || bIsColRefLongTerm )
 #else
@@ -4732,5 +4478,5 @@
 #endif
   {
-#if NH_3D_TMVP
+#if NH_3D
     const Int iCurrViewId    = m_pcSlice->getViewId (); 
     const Int iCurrRefViewId = m_pcSlice->getRefPic(eRefPicList, refIdx)->getViewId (); 
@@ -4750,5 +4496,5 @@
 #endif
       rcMv = cColMv;
-#if NH_3D_TMVP
+#if NH_3D
     }
 #endif
@@ -4757,6 +4503,11 @@
   {
     const Int currPOC    = m_pcSlice->getPOC();
+#if REDUCED_ENCODER_MEMORY
+    const Int colPOC     = pColSlice->getPOC();
+    const Int colRefPOC  = pColSlice->getRefPOC(eColRefPicList, iColRefIdx);
+#else
     const Int colPOC     = pColCtu->getSlice()->getPOC();
     const Int colRefPOC  = pColCtu->getSlice()->getRefPOC(eColRefPicList, iColRefIdx);
+#endif
     const Int currRefPOC = m_pcSlice->getRefPic(eRefPicList, refIdx)->getPOC();
     const Int scale      = xGetDistScaleFactor(currPOC, currRefPOC, colPOC, colRefPOC);
@@ -4811,9 +4562,27 @@
 {
    Int scaleFactor = (4 / scale ) * AMVP_DECIMATION_FACTOR / m_unitSize;
+  if (scaleFactor > 0)
+  {
+    for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+    {
+      m_acCUMvField[i].compress(m_pePredMode, scaleFactor);
+    }
+  }
 #else
 Void TComDataCU::compressMV()
 {
+#if REDUCED_ENCODER_MEMORY
+  const Int scaleFactor = std::max<Int>(1,4 * AMVP_DECIMATION_FACTOR / m_unitSize);
+  TComPicSym &picSym=*(getPic()->getPicSym());
+  TComPicSym::DPBPerCtuData &dpbForCtu=picSym.getDPBPerCtuData(getCtuRsAddr());
+
+  for(UInt i=0; i<NUM_REF_PIC_LIST_01; i++)
+  {
+    dpbForCtu.m_CUMvField[i].compress(dpbForCtu.m_pePredMode, m_pePredMode, scaleFactor,m_acCUMvField[i]);
+    memcpy(dpbForCtu.m_pePartSize, m_pePartSize, sizeof(*m_pePartSize)*m_uiNumPartition);
+    dpbForCtu.m_pSlice = getSlice();
+  }
+#else
   Int scaleFactor = 4 * AMVP_DECIMATION_FACTOR / m_unitSize;
-#endif
   if (scaleFactor > 0)
   {
@@ -4823,4 +4592,6 @@
     }
   }
+#endif
+#endif
 }
 #if NH_3D
@@ -4867,5 +4638,5 @@
 
   UInt uiDirMode  = getIntraDir(toChannelType(compID), uiAbsPartIdx);
-#if NH_3D_DMM
+#if NH_3D
   mapDmmToIntraDir( uiDirMode );
 #endif
@@ -4876,5 +4647,5 @@
     const UInt partsPerMinCU = 1<<(2*(sps->getMaxTotalCUDepth() - sps->getLog2DiffMaxMinCodingBlockSize()));
     uiDirMode = getIntraDir(CHANNEL_TYPE_LUMA, getChromasCorrespondingPULumaIdx(uiAbsPartIdx, getPic()->getChromaFormat(), partsPerMinCU));
-#if NH_3D_DMM
+#if NH_3D
     mapDmmToIntraDir( uiDirMode );
 #endif
@@ -4901,4 +4672,17 @@
   }
 }
+
+#if MCTS_ENC_CHECK
+Bool TComDataCU::isLastColumnCTUInTile() const
+{
+  UInt      currentTileIdx               = this->getPic()->getPicSym()->getTileIdxMap(this->getCtuRsAddr());
+  TComTile *pCurrentTile                 = m_pcPic->getPicSym()->getTComTile(currentTileIdx);
+  UInt      frameWidthInCtus             = m_pcPic->getPicSym()->getFrameWidthInCtus();
+  UInt      rightEdgeCTUPosInCurrentTile = pCurrentTile->getRightEdgePosInCtus();
+  UInt      ctuXPosInCtus                = this->getCtuRsAddr() % frameWidthInCtus;
+  
+  return (rightEdgeCTUPosInCurrentTile == ctuXPosInCtus);
+}
+#endif
 
 #if NH_3D_VSO
@@ -4910,5 +4694,5 @@
 #endif
 
-#if NH_3D_IV_MERGE
+#if NH_3D
 Void TComDataCU::getDispforDepth (UInt uiPartIdx, UInt uiPartAddr, DisInfo* pDisp)
 {
@@ -4928,7 +4712,5 @@
   }
 }
-#endif
-
-#if NH_3D_DIS
+
 Bool TComDataCU::getNeighDepth ( UInt uiPartIdx, UInt uiPartAddr, Pel* pNeighDepth, Int index )
 {
@@ -4988,15 +4770,6 @@
   return bDepAvail;
 }
-#endif
-#if NH_3D_NBDV 
-//Notes from QC:
-//TBD#1: DoNBDV related contributions are just partially integrated under the marco of NH_3D_NBDV_REF, remove this comment once DoNBDV and BVSP are done
-//TBD#2: set of DvMCP values need to be done as part of inter-view motion prediction process. Remove this comment once merge related integration is done
-//To be checked: Parallel Merge features for NBDV, related to DV_DERIVATION_PARALLEL_B0096 and LGE_IVMP_PARALLEL_MERGE_B0136 are not integrated. The need of these features due to the adoption of CU-based NBDV is not clear. We need confirmation on this, especially by proponents
-Void TComDataCU::getDisMvpCandNBDV( DisInfo* pDInfo
-#if NH_3D_NBDV_REF
-, Bool bDepthRefine
-#endif
-)
+
+Void TComDataCU::getDisMvpCandNBDV( DisInfo* pDInfo, Bool bDepthRefine )
 {
   //// ******* Init variables ******* /////
@@ -5018,10 +4791,10 @@
     }
   }
-#if NH_3D_NBDV_REF
+
   if( !m_pcSlice->getDepthRefinementFlag( ) )
   {
     bDepthRefine = false;
   }
-#endif
+
   // Get Positions  
   PartSize eCUMode    = getPartitionSize( uiPartAddr );    
@@ -5068,21 +4841,6 @@
         pDInfo->m_aVIdxCan  = iTargetViewIdx;
 
-#if NH_3D_NBDV_REF
         TComPic* picDepth = NULL;   
-#if H_3D_FCO
-        picDepth  = getSlice()->getIvPic(true, getSlice()->getViewIndex() );
-        if ( picDepth->getPicYuvRec() != NULL  )  
-        {
-          cColMv.setZero();
-        }
-        else // Go back with virtual depth
-        {
-          picDepth = getSlice()->getIvPic( true, iTargetViewIdx );
-        }
-
-        assert(picDepth != NULL);
-#else
         picDepth = getSlice()->getIvPic( true, iTargetViewIdx );
-#endif
         if (picDepth && bDepthRefine)
         {
@@ -5090,5 +4848,4 @@
         }
         pDInfo->m_acDoNBDV  = cColMv;
-#endif //NH_3D_NBDV_REF
         return;
       }
@@ -5103,9 +4860,5 @@
     pcTmpCU = getPULeft(uiIdx, uiPartIdxLB);
   bCheckMcpDv = true; 
-  if ( xCheckSpatialNBDV( pcTmpCU, uiIdx, pDInfo, bCheckMcpDv, &cIDVInfo, DVFROM_LEFT
-#if NH_3D_NBDV_REF
-    , bDepthRefine 
-#endif
-    ) )
+  if ( xCheckSpatialNBDV( pcTmpCU, uiIdx, pDInfo, bCheckMcpDv, &cIDVInfo, DVFROM_LEFT, bDepthRefine ) )
     return;
 
@@ -5115,9 +4868,5 @@
   {
     bCheckMcpDv = ( ( getCtuRsAddr() - pcTmpCU->getCtuRsAddr() ) == 0);
-    if ( xCheckSpatialNBDV( pcTmpCU, uiIdx, pDInfo, bCheckMcpDv, &cIDVInfo, DVFROM_ABOVE
-#if NH_3D_NBDV_REF
-      , bDepthRefine 
-#endif
-      ) )
+    if ( xCheckSpatialNBDV( pcTmpCU, uiIdx, pDInfo, bCheckMcpDv, &cIDVInfo, DVFROM_ABOVE , bDepthRefine ) )
       return;
   }
@@ -5135,22 +4884,5 @@
           pDInfo->m_acNBDV = cDispVec;
           pDInfo->m_aVIdxCan = cIDVInfo.m_aVIdxCan[iList][ curPos ];
-#if NH_3D_NBDV_REF
-#if H_3D_FCO
-          TComPic* picDepth  = NULL;
-
-          picDepth  = getSlice()->getIvPic(true, getSlice()->getViewIndex() );
-          if ( picDepth->getPicYuvRec() != NULL )  
-          {
-            cDispVec.setZero();
-          }
-          else // Go back with virtual depth
-          {
-            picDepth = getSlice()->getIvPic( true, pDInfo->m_aVIdxCan );
-          }
-
-          assert(picDepth != NULL);
-#else
           TComPic* picDepth = getSlice()->getIvPic( true, pDInfo->m_aVIdxCan );
-#endif
 
           if (picDepth && bDepthRefine)
@@ -5159,5 +4891,4 @@
           }
           pDInfo->m_acDoNBDV = cDispVec;
-#endif
           return;
         }
@@ -5173,21 +4904,6 @@
     pDInfo->m_aVIdxCan = getSlice()->getDefaultRefViewIdx();
 
-#if NH_3D_NBDV_REF
     TComPic* picDepth = NULL;
-#if H_3D_FCO
-    picDepth  = getSlice()->getIvPic(true, getSlice()->getViewIndex() );
-    if ( picDepth->getPicYuvRec() != NULL )  
-    {
-      defaultDV.setZero();
-    }
-    else // Go back with virtual depth
-    {
-      picDepth = getSlice()->getIvPic( true, getSlice()->getDefaultRefViewIdx());
-    }
-
-    assert(picDepth != NULL);
-#else
     picDepth = getSlice()->getIvPic( true, getSlice()->getDefaultRefViewIdx());
-#endif
     if (picDepth && bDepthRefine)
     {
@@ -5195,9 +4911,7 @@
     }
     pDInfo->m_acDoNBDV = defaultDV;
-#endif
-  }
-}
-
-#if NH_3D_NBDV_REF
+  }
+}
+
 Pel TComDataCU::getMcpFromDM(TComPicYuv* pcBaseViewDepthPicYuv, TComMv* mv, Int iBlkX, Int iBlkY, Int iBlkWidth, Int iBlkHeight, Int* aiShiftLUT )
 {
@@ -5241,12 +4955,8 @@
   }
 }
-#endif //NH_3D_NBDV_REF
-
-
-Bool TComDataCU::xCheckSpatialNBDV( const TComDataCU* pcTmpCU, UInt uiIdx, DisInfo* pNbDvInfo, Bool bSearchForMvpDv, IDVInfo* paIDVInfo, UInt uiMvpDvPos
-#if NH_3D_NBDV_REF
-, Bool bDepthRefine 
-#endif
-)
+
+
+
+Bool TComDataCU::xCheckSpatialNBDV( const TComDataCU* pcTmpCU, UInt uiIdx, DisInfo* pNbDvInfo, Bool bSearchForMvpDv, IDVInfo* paIDVInfo, UInt uiMvpDvPos, Bool bDepthRefine )
 {
   if( pcTmpCU != NULL && !pcTmpCU->isIntra( uiIdx ) )
@@ -5266,21 +4976,8 @@
           pNbDvInfo->m_acNBDV = cMvPred;
           pNbDvInfo->m_aVIdxCan = refViewIdx;
-#if NH_3D_NBDV_REF
+
           TComPic* picDepth = NULL;
           assert(getSlice()->getRefPic(eRefPicList, refId)->getPOC() == getSlice()->getPOC());            
-#if H_3D_FCO
-          picDepth  = getSlice()->getIvPic(true, getSlice()->getViewIndex() );
-          if ( picDepth->getPicYuvRec() != NULL )  
-          {
-            cMvPred.setZero();
-          }
-          else// Go back with virtual depth
-          {
-            picDepth = getSlice()->getIvPic (true, refViewIdx );
-          }
-          assert(picDepth != NULL);
-#else
           picDepth   = getSlice()->getIvPic (true, refViewIdx );
-#endif
           UInt uiPartIdx = 0;   //Notes from MTK: Please confirm that using 0 as partition index and partition address is correct for CU-level DoNBDV
           UInt uiPartAddr = 0;  //QC: confirmed
@@ -5291,5 +4988,4 @@
           }
           pNbDvInfo->m_acDoNBDV = cMvPred;
-#endif
           return true;
         }
@@ -5355,14 +5051,9 @@
 }
 
-
 Void TComDataCU::setDvInfoSubParts( DisInfo cDvInfo, UInt uiAbsPartIdx, UInt uiDepth )
 {
-#if NH_3D_VSP // bug fix
   UInt uiCurrPartNumb = m_pcPic->getNumPartitionsInCtu() >> (uiDepth << 1);
   assert(m_pcPic->getNumPartitionsInCtu() ==m_pcPic->getNumPartInCtuWidth()*m_pcPic->getNumPartInCtuHeight());
 
-#else
-  UInt uiCurrPartNumb = m_pcPic->getNumPartInCtuWidth() >> (uiDepth << 1);
-#endif
   for (UInt ui = 0; ui < uiCurrPartNumb; ui++ )
   {
@@ -5370,10 +5061,9 @@
   }
 }
-#if NH_3D_VSP  || NH_3D_DBBP
+
 Void TComDataCU::setDvInfoSubParts( DisInfo cDvInfo, UInt uiAbsPartIdx, UInt uiPUIdx, UInt uiDepth )
 {
   setSubPartT<DisInfo>( cDvInfo, m_pDvInfo, uiAbsPartIdx, uiDepth, uiPUIdx );
 }
-#endif
 
 Bool TComDataCU::xGetColDisMV( Int currCandPic, RefPicList eRefPicList, Int refidx, Int uiCUAddr, Int uiPartUnitIdx, TComMv& rcMv , Int & iTargetViewIdx, Int & iStartViewIdx )
@@ -5449,8 +5139,5 @@
   iCurrPosY  += ( ( iHeight - 1 ) >> 1 );
 
-  Bool depthRefineFlag = false; 
-#if NH_3D_NBDV_REF
-  depthRefineFlag = m_pcSlice->getDepthRefinementFlag( ); 
-#endif // NH_3D_NBDV_REF
+  Bool depthRefineFlag = m_pcSlice->getDepthRefinementFlag( ); 
 
   TComMv      cDv = depthRefineFlag ? pDInfo->m_acDoNBDV : pDInfo->m_acNBDV; 
@@ -5506,5 +5193,5 @@
 #endif
 
-#if NH_3D_SPIVMP
+#if NH_3D
 Void TComDataCU::getSPPara(Int iPUWidth, Int iPUHeight, Int& iNumSP, Int& iNumSPInOneLine, Int& iSPWidth, Int& iSPHeight)
 {
@@ -5555,14 +5242,6 @@
   }
 }
-#endif
-
-#if NH_3D_IV_MERGE
-Bool
-TComDataCU::getInterViewMergeCands(UInt uiPartIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv, DisInfo* pDInfo, Int* availableMcDc , Bool bIsDepth           
-#if NH_3D_SPIVMP
-, TComMvField* pcMvFieldSP, UChar* puhInterDirSP
-#endif
-, Bool bICFlag
-)
+
+Bool TComDataCU::getInterViewMergeCands(UInt uiPartIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv, DisInfo* pDInfo, Int* availableMcDc , Bool bIsDepth , TComMvField* pcMvFieldSP, UChar* puhInterDirSP, Bool bICFlag )
 {
   TComSlice*    pcSlice = getSlice ();  
@@ -5581,13 +5260,5 @@
   pcBaseRec->getTopLeftSamplePos( getCtuRsAddr(), getZorderIdxInCtu() + uiPartAddr, iCurrPosX, iCurrPosY );
 
-#if !NH_3D_SPIVMP
-  iCurrPosX  += ( iWidth  >> 1 );
-  iCurrPosY  += ( iHeight >> 1 );
-#endif
-
-  Bool depthRefineFlag = false; 
-#if NH_3D_NBDV_REF
-  depthRefineFlag = m_pcSlice->getDepthRefinementFlag( ); 
-#endif // NH_3D_NBDV_REF
+  Bool depthRefineFlag =  m_pcSlice->getDepthRefinementFlag( ); 
 
   TComMv      cDv = depthRefineFlag ? pDInfo->m_acDoNBDV : pDInfo->m_acNBDV; 
@@ -5598,15 +5269,12 @@
 
   Bool abPdmAvailable[8] =  {false, false, false, false, false, false, false, false};
-#if NH_3D_NBDV
+
   for( Int i = 0; i < 8; i++)
   {
     pacPdmMv[i].setIDVFlag   (false);
   }
-#endif
 
   if(!bICFlag)
   {
-
-#if NH_3D_SPIVMP
     ////////////////////////////////
     //////////sub-PU IvMC///////////
@@ -5614,9 +5282,5 @@
     if(!m_pcSlice->getIsDepth())
     {
-#if NH_3D_DBBP
       if (!getDBBPFlag(0))
-#else
-      if (1)
-#endif
       {
         Int iNumSPInOneLine, iNumSP, iSPWidth, iSPHeight;
@@ -5678,17 +5342,11 @@
                       abPdmAvailable[ uiCurrRefListId ] = true;
                       TComMv cMv(cDefaultMvField.getHor(), cDefaultMvField.getVer());
-#if NH_3D_NBDV 
-#if NH_3D_IV_MERGE
                       if( !bIsDepth )
                       {
-#endif
                         cMv.setIDVFlag   (true);
                         cMv.setIDVHor    (cDv.getHor());                  
                         cMv.setIDVVer    (cDv.getVer());  
                         cMv.setIDVVId    (iViewIndex); 
-#if NH_3D_IV_MERGE
                       }
-#endif
-#endif
                       paiPdmRefIdx  [ uiCurrRefListId ] = iPdmRefIdx;
                       pacPdmMv      [ uiCurrRefListId ] = cMv;
@@ -5778,5 +5436,5 @@
       iCurrPosY  += ( iHeight >> 1 );
     }
-#endif
+
 
     ////////////////////////////////
@@ -5784,5 +5442,4 @@
     ////////////////////////////////
 
-#if NH_3D_SPIVMP
     if(m_pcSlice->getIsDepth())
     {
@@ -5790,12 +5447,6 @@
       iCurrPosY  += ( iHeight >> 1 );
     }
-#if NH_3D_DBBP
+
     for(Int iLoopCan = ( (m_pcSlice->getIsDepth() || getDBBPFlag(0)) ? 0 : 1 ); iLoopCan < ( 2 - m_pcSlice->getIsDepth() ); iLoopCan ++) 
-#else
-    for(Int iLoopCan = ( m_pcSlice->getIsDepth() ? 0 : 1 ); iLoopCan < ( 2 - m_pcSlice->getIsDepth() ); iLoopCan ++) 
-#endif
-#else
-    for(Int iLoopCan = 0; iLoopCan < 2; iLoopCan ++)
-#endif
     {
       // iLoopCan == 0 --> IvMC
@@ -5839,17 +5490,11 @@
                     abPdmAvailable[ (uiCurrRefListId + (iLoopCan<<2)) ] = true;
                     TComMv cMv(cBaseMvField.getHor(), cBaseMvField.getVer());
-#if NH_3D_NBDV 
-#if NH_3D_IV_MERGE
                     if( !bIsDepth )
                     {
-#endif
                       cMv.setIDVFlag   (true);
                       cMv.setIDVHor    (cDv.getHor());                  
                       cMv.setIDVVer    (cDv.getVer());  
                       cMv.setIDVVId    (iViewIndex); 
-#if NH_3D_IV_MERGE
                     }
-#endif
-#endif
                     paiPdmRefIdx  [ (uiCurrRefListId + (iLoopCan<<2)) ] = iPdmRefIdx;
                     pacPdmMv      [ (uiCurrRefListId + (iLoopCan<<2)) ] = cMv;
@@ -5864,13 +5509,5 @@
       }
     }
-#if NH_3D_SPIVMP
-#if NH_3D_DBBP
     for(Int iLoopCan = ( (m_pcSlice->getIsDepth() || getDBBPFlag(0)) ? 0 : 1 ); iLoopCan < ( 2 - m_pcSlice->getIsDepth() ); iLoopCan ++)
-#else
-    for(Int iLoopCan = ( m_pcSlice->getIsDepth()  ? 0 : 1 ); iLoopCan < ( 2 - m_pcSlice->getIsDepth() ); iLoopCan ++)
-#endif
-#else
-    for(Int iLoopCan = 0; iLoopCan < 2; iLoopCan ++)
-#endif
     {
       availableMcDc[(iLoopCan << 1)] = ( abPdmAvailable[(iLoopCan<<2)] ? 1 : 0 ) + ( abPdmAvailable[1 + (iLoopCan<<2)] ? 2 : 0);
@@ -5898,14 +5535,10 @@
             abPdmAvailable[ iRefListId + 2 + (iLoopCan<<2) ] = true;
             paiPdmRefIdx  [ iRefListId + 2 + (iLoopCan<<2) ] = iPdmRefIdx;
-#if NH_3D_NBDV_REF
             TComMv cMv = depthRefineFlag ? pDInfo->m_acDoNBDV : pDInfo->m_acNBDV; 
-#endif
             cMv.setHor( cMv.getHor() + ioffsetDV );
-#if NH_3D_IV_MERGE 
             if( bIsDepth )
             {
               cMv.setHor((cMv.getHor()+2)>>2); 
             }
-#endif
             cMv.setVer( 0 );
             pacPdmMv      [iRefListId + 2 + (iLoopCan<<2)] = cMv;
@@ -5922,13 +5555,10 @@
   return false;
 }
-#endif
-#if NH_3D_ARP
+
 Void TComDataCU::setARPWSubParts ( UChar w, UInt uiAbsPartIdx, UInt uiDepth )
 {
   setSubPart<UChar>( w, m_puhARPW, uiAbsPartIdx, uiDepth, 0 );
 }
-#endif
-
-#if NH_3D_IC
+
 Void TComDataCU::setICFlagSubParts( Bool bICFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth )
 {
@@ -5983,6 +5613,5 @@
   return false;
 }
-#endif
-#if NH_3D_DMM
+
 Void TComDataCU::setDmm1WedgeTabIdxSubParts( UInt tabIdx, UInt uiAbsPartIdx, UInt uiDepth )
 {
@@ -5990,7 +5619,5 @@
   for( UInt ui = 0; ui < uiCurrPartNumb; ui++ ) { m_dmm1WedgeTabIdx[uiAbsPartIdx+ui] = tabIdx; }
 }
-#endif
-
-#if NH_3D_VSP
+
 Void TComDataCU::setMvFieldPUForVSP( TComDataCU* pcCU, UInt partAddr, Int width, Int height, RefPicList eRefPicList, Int iRefIdx, Int &vspSize )
 {
@@ -5998,19 +5625,5 @@
   Int depthRefViewIdx = pcCU->getDvInfo(partAddr).m_aVIdxCan;
   
-#if H_3D_FCO
-  TComPic* pRefPicBaseDepth = 0;
-  Bool     bIsCurrDepthCoded = false;
-  pRefPicBaseDepth  = pcCU->getSlice()->getIvPic( true, pcCU->getSlice()->getViewIndex() );
-  if ( pRefPicBaseDepth->getPicYuvRec() != NULL  ) 
-  {
-    bIsCurrDepthCoded = true;
-  }
-  else 
-  {
-    pRefPicBaseDepth = pcCU->getSlice()->getIvPic (true, depthRefViewIdx );
-  }
-#else
   TComPic* pRefPicBaseDepth = pcCU->getSlice()->getIvPic (true, depthRefViewIdx );
-#endif
   assert(pRefPicBaseDepth != NULL);
   TComPicYuv* pcBaseViewDepthPicYuv = pRefPicBaseDepth->getPicYuvRec();
@@ -6032,11 +5645,4 @@
   TComMv cDv  = pcCU->getDvInfo(partAddr).m_acNBDV;
   pcCU->clipMv(cDv);
-
-#if H_3D_FCO
-  if ( bIsCurrDepthCoded )
-  {
-      cDv.setZero();
-  }
-#endif
 
   // fetch virtual depth map & convert depth to motion vector, which are stored in the motion memory
Index: /trunk/source/Lib/TLibCommon/TComDataCU.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComDataCU.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComDataCU.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -60,5 +60,5 @@
 static const UInt NUM_MOST_PROBABLE_MODES=3;
 
-#if NH_3D_DBBP
+#if NH_3D
 typedef struct _DBBPTmpData
 {
@@ -111,5 +111,5 @@
 
   Bool*          m_skipFlag;           ///< array of skip flags
-#if NH_3D_DIS
+#if NH_3D
   Bool*          m_bDISFlag;         
   UChar*         m_ucDISType;
@@ -142,5 +142,4 @@
   TComDataCU*   m_pCtuAbove;          ///< pointer of above CTU.
   TComDataCU*   m_pCtuLeft;           ///< pointer of left CTU
-  TComDataCU*   m_apcCUColocated[NUM_REF_PIC_LIST_01];  ///< pointer of temporally colocated CU's for both directions
   TComMvField   m_cMvFieldA;          ///< motion vector of position A
   TComMvField   m_cMvFieldB;          ///< motion vector of position B
@@ -162,32 +161,20 @@
   SChar*        m_apiMVPNum[NUM_REF_PIC_LIST_01];       ///< array of number of possible motion vectors predictors
   Bool*         m_pbIPCMFlag;         ///< array of intra_pcm flags
-#if NH_3D_NBDV
+#if MCTS_ENC_CHECK
+  Bool          m_tMctsMvpIsValid;
+#endif
+#if NH_3D
   DisInfo*      m_pDvInfo;
-#endif
-#if NH_3D_VSP
   SChar*        m_piVSPFlag;          ///< array of VSP flags to indicate whehter a block uses VSP or not  ///< 0: non-VSP; 1: VSP
-#endif
-#if NH_3D_SPIVMP
   Bool*         m_pbSPIVMPFlag;       ///< array of sub-PU IVMP flags to indicate whehter a block uses sub-PU IVMP ///< 0: non-SPIVMP; 1: SPIVMP
-#endif
-#if NH_3D_ARP
   UChar*        m_puhARPW;
-#endif
-#if NH_3D_IC
   Bool*         m_pbICFlag;           ///< array of IC flags
-#endif
-#if NH_3D_DMM
   Pel*          m_dmmDeltaDC[NUM_DMM][2];
   UInt*         m_dmm1WedgeTabIdx;
-#endif
-#if NH_3D_SDC_INTRA
   Bool*         m_pbSDCFlag;
   Pel*          m_apSegmentDCOffset[2];
-#endif
-#if NH_3D_DBBP
   Bool*         m_pbDBBPFlag;        ///< array of DBBP flags
   DbbpTmpData   m_sDBBPTmpData;
-#endif
-#if NH_3D_MLC
+
   Bool          m_bAvailableFlagA1;    ///< A1 available flag
   Bool          m_bAvailableFlagB1;    ///< B1 available flag
@@ -212,5 +199,5 @@
   UInt          m_uiTotalBins;        ///< sum of partition bins
   SChar         m_codedQP;
-#if NH_3D_MLC
+#if NH_3D
   DisInfo         m_cDefaultDisInfo;    ///< Default disparity information for initializing
   TComMotionCand  m_mergCands[MRG_IVSHIFT+1];   ///< Motion candidates for merge mode
@@ -226,8 +213,6 @@
   Bool          xAddMVPCandWithScaling        ( AMVPInfo &info, const RefPicList eRefPicList, const Int iRefIdx, const UInt uiPartUnitIdx, const MVP_DIR eDir ) const;
 
-#if NH_3D_VSP
+#if NH_3D
   Bool          xAddVspCand( Int mrgCandIdx, DisInfo* pDInfo, Int& iCount);
-#endif
-#if NH_3D_IV_MERGE
   Bool          xAddIvMRGCand( Int mrgCandIdx, Int& iCount, Int*   ivCandDir, TComMv* ivCandMv, Int* ivCandRefIdx ); 
 #endif
@@ -235,5 +220,5 @@
   Void          deriveRightBottomIdx          ( UInt uiPartIdx, UInt& ruiPartIdxRB ) const;
 
-#if NH_3D_TMVP
+#if NH_3D
   Bool          xGetColMVP                    ( const RefPicList eRefPicList, const Int ctuRsAddr, const Int partUnitIdx, TComMv& rcMv, Int& refIdx, Bool bMRG = true  ) const;
 #else
@@ -242,16 +227,16 @@
 
   /// compute scaling factor from POC difference
-#if !NH_3D_ARP
+#if !NH_3D
   static Int    xGetDistScaleFactor           ( Int iCurrPOC, Int iCurrRefPOC, Int iColPOC, Int iColRefPOC );
 #endif
   Void          xDeriveCenterIdx              ( UInt uiPartIdx, UInt& ruiPartIdxCenter ) const;
 
-#if NH_3D_VSP
-  Void xSetMvFieldForVSP  ( TComDataCU *cu, TComPicYuv *picRefDepth, TComMv *dv, UInt partAddr, Int width, Int height, Int *shiftLUT, RefPicList refPicList, Int refIdx, Bool isDepth, Int &vspSize );
+#if NH_3D
+  Void          xSetMvFieldForVSP  ( TComDataCU *cu, TComPicYuv *picRefDepth, TComMv *dv, UInt partAddr, Int width, Int height, Int *shiftLUT, RefPicList refPicList, Int refIdx, Bool isDepth, Int &vspSize );
 #endif
 
 public:
 
-#if NH_3D_ARP
+#if NH_3D
   static Int    xGetDistScaleFactor           ( Int iCurrPOC, Int iCurrRefPOC, Int iColPOC, Int iColRefPOC );
 #endif
@@ -274,11 +259,9 @@
   Void          initSubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx, UInt uiDepth, Int qp );
   Void          setOutsideCUPart      ( UInt uiAbsPartIdx, UInt uiDepth );
-#if NH_3D_NBDV
+
+  Void          copySubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx );
+#if NH_3D
   Void          copyDVInfoFrom        (TComDataCU* pcCU, UInt uiAbsPartIdx);
-#endif
-
-  Void          copySubCU             ( TComDataCU* pcCU, UInt uiPartUnitIdx );
-#if NH_3D_NBDV
-    Void          copyInterPredInfoFrom ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList, Bool bNBDV = false );
+  Void          copyInterPredInfoFrom ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList, Bool bNBDV = false );
 #else
   Void          copyInterPredInfoFrom ( TComDataCU* pcCU, UInt uiAbsPartIdx, RefPicList eRefPicList );
@@ -307,9 +290,13 @@
 
   Void          setDepthSubParts      ( UInt uiDepth, UInt uiAbsPartIdx );
-#if NH_3D_VSO
+
+#if MCTS_ENC_CHECK
+  Void          setTMctsMvpIsValid(Bool b)    { m_tMctsMvpIsValid = b; }
+  Bool          getTMctsMvpIsValid()          { return m_tMctsMvpIsValid; }
+  Bool          isLastColumnCTUInTile() const;
+#endif
+
+#if NH_3D
   Void          getPosInPic           ( UInt uiAbsPartIndex, Int& riPosX, Int& riPosY ) const;
-#endif
-
-#if NH_3D_ARP
   Void          setSlice              ( TComSlice* pcSlice)     { m_pcSlice = pcSlice;       }
   Void          setPic                ( TComDataCU* pcCU  )     { m_pcPic              = pcCU->getPic(); }
@@ -325,29 +312,24 @@
   Void          setCUTransquantBypassSubParts( Bool flag, UInt uiAbsPartIdx, UInt uiDepth );
 
-#if NH_3D_DBBP
+#if NH_3D
   Pel*          getVirtualDepthBlock(UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, UInt& uiDepthStride);
 #endif
   
-  Bool*         getSkipFlag            ()                        { return m_skipFlag;          }
+  Bool*         getSkipFlag           ()                        { return m_skipFlag;          }
   Bool          getSkipFlag                   ( UInt idx ) const                                           { return m_skipFlag[idx];                    }
   Void          setSkipFlag           ( UInt idx, Bool skip)     { m_skipFlag[idx] = skip;   }
   Void          setSkipFlagSubParts   ( Bool skip, UInt absPartIdx, UInt depth );
-#if NH_3D_DIS
-  Bool*        getDISFlag            ()                         { return m_bDISFlag;          }
-  Bool         getDISFlag            ( UInt idx)                { return m_bDISFlag[idx];     }
-  Void         setDISFlag            ( UInt idx, Bool bDIS)     { m_bDISFlag[idx] = bDIS;   }
-  Void         setDISFlagSubParts    ( Bool bDIS, UInt uiAbsPartIdx, UInt uiDepth );
-
-  UChar*       getDISType            ()                         { return m_ucDISType; }
-  UChar        getDISType            ( UInt idx)                { return m_ucDISType[idx];     }
-  Void         getDISType            ( UInt idx, UChar ucDISType)     { m_ucDISType[idx] = ucDISType;   }
-  Void         setDISTypeSubParts    ( UChar ucDISType, UInt uiAbsPartIdx, UInt uiDepth );
-#endif
-  SChar*        getPredictionMode             ( )                                                          { return m_pePredMode;                       }
-  PredMode      getPredictionMode             ( UInt uiIdx ) const                                         { return static_cast<PredMode>( m_pePredMode[uiIdx] ); }
-  Void          setPredictionMode     ( UInt uiIdx, PredMode uh){ m_pePredMode[uiIdx] = uh;   }
-  Void          setPredModeSubParts   ( PredMode eMode, UInt uiAbsPartIdx, UInt uiDepth );
-
-#if NH_3D_DBBP
+
+#if NH_3D
+  Bool*         getDISFlag            ()                         { return m_bDISFlag;          }
+  Bool          getDISFlag            ( UInt idx)                { return m_bDISFlag[idx];     }
+  Void          setDISFlag            ( UInt idx, Bool bDIS)     { m_bDISFlag[idx] = bDIS;   }
+  Void          setDISFlagSubParts    ( Bool bDIS, UInt uiAbsPartIdx, UInt uiDepth );
+
+  UChar*        getDISType            ()                         { return m_ucDISType; }
+  UChar         getDISType            ( UInt idx)                { return m_ucDISType[idx];     }
+  Void          getDISType            ( UInt idx, UChar ucDISType)     { m_ucDISType[idx] = ucDISType;   }
+  Void          setDISTypeSubParts    ( UChar ucDISType, UInt uiAbsPartIdx, UInt uiDepth );
+
   Bool*         getDBBPFlag           ()                        const { return m_pbDBBPFlag;               }
   Bool          getDBBPFlag           ( UInt uiIdx )            const { return m_pbDBBPFlag[uiIdx];        }
@@ -355,5 +337,12 @@
   Void          setDBBPFlagSubParts   ( Bool bDBBPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
   DbbpTmpData*  getDBBPTmpData        () { return &m_sDBBPTmpData; }
-#endif
+
+
+#endif
+  SChar*        getPredictionMode             ( )                                                          { return m_pePredMode;                       }
+  PredMode      getPredictionMode             ( UInt uiIdx ) const                                         { return static_cast<PredMode>( m_pePredMode[uiIdx] ); }
+  Void          setPredictionMode     ( UInt uiIdx, PredMode uh){ m_pePredMode[uiIdx] = uh;   }
+  Void          setPredModeSubParts   ( PredMode eMode, UInt uiAbsPartIdx, UInt uiDepth );
+
 
   SChar*        getCrossComponentPredictionAlpha( ComponentID compID )                                     { return m_crossComponentPredictionAlpha[compID];        }
@@ -451,5 +440,5 @@
   template <typename T>
   Void          setSubPart            ( T bParameter, T* pbBaseCtu, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx );
-#if H_3D_VSP || NH_3D_DBBP
+#if NH_3D
   template<typename T>
   Void          setSubPartT           ( T uiParameter, T* puhBaseLCU, UInt uiCUAddr, UInt uiCUDepth, UInt uiPUIdx );
@@ -477,63 +466,34 @@
   Void          setIPCMFlag           (UInt uiIdx, Bool b )     { m_pbIPCMFlag[uiIdx] = b;           }
   Void          setIPCMFlagSubParts   (Bool bIpcmFlag, UInt uiAbsPartIdx, UInt uiDepth);
-#if NH_3D_NBDV
+  // -------------------------------------------------------------------------------------------------------------------
+  // member functions for accessing partition information
+  // -------------------------------------------------------------------------------------------------------------------
+
+#if  NH_3D_FAST_TEXTURE_ENCODING
+  Void          getIVNStatus       ( UInt uiPartIdx,  DisInfo* pDInfo, Bool& bIVFMerge,  Int& iIVFMaxD);
+#endif
+
+#if NH_3D
   Void          setDvInfoSubParts     ( DisInfo cDvInfo, UInt uiAbsPartIdx, UInt uiDepth );
-#if H_3D_VSP || NH_3D_DBBP
   Void          setDvInfoSubParts     ( DisInfo cDvInfo, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth);
-#endif
   DisInfo*      getDvInfo             ()                        { return m_pDvInfo;                 }
   DisInfo       getDvInfo             (UInt uiIdx)              { return m_pDvInfo[uiIdx];          }
-#endif
-#if NH_3D_NBDV
-  Void          xDeriveRightBottomNbIdx(Int &uiLCUIdxRBNb, Int &uiPartIdxRBNb );
-  Bool          xCheckSpatialNBDV (const TComDataCU* pcTmpCU, UInt uiIdx, DisInfo* pNbDvInfo, Bool bSearchForMvpDv, IDVInfo* paMvpDvInfo,
-                                   UInt uiMvpDvPos
-#if NH_3D_NBDV_REF
-  , Bool bDepthRefine = false
-#endif
-  );
-  Bool          xGetColDisMV      ( Int currCandPic, RefPicList eRefPicList, Int refidx, Int uiCUAddr, Int uiPartUnitIdx, TComMv& rcMv, Int & iTargetViewIdx, Int & iStartViewIdx );
-  Void          getDisMvpCandNBDV ( DisInfo* pDInfo
-#if NH_3D_NBDV_REF
-   , Bool bDepthRefine = false
-#endif
-   ); 
-   
-#if NH_3D_IV_MERGE
-  Void          getDispforDepth  ( UInt uiPartIdx, UInt uiPartAddr, DisInfo* cDisp);
-#endif
-
-#if NH_3D_NBDV_REF
-  Pel           getMcpFromDM(TComPicYuv* pcBaseViewDepthPicYuv, TComMv* mv, Int iBlkX, Int iBlkY, Int iWidth, Int iHeight, Int* aiShiftLUT );
-  Void          estimateDVFromDM(Int refViewIdx, UInt uiPartIdx, TComPic* picDepth, UInt uiPartAddr, TComMv* cMvPred );
-#endif //NH_3D_NBDV_REF
-#endif
-#if NH_3D_DIS
-   Bool          getNeighDepth (UInt uiPartIdx, UInt uiPartAddr, Pel* pNeighDepth, Int index);
-#endif
-#if  NH_3D_FAST_TEXTURE_ENCODING
-  Void          getIVNStatus       ( UInt uiPartIdx,  DisInfo* pDInfo, Bool& bIVFMerge,  Int& iIVFMaxD);
-#endif
-#if NH_3D_SPIVMP
-  Void          getSPPara(Int iPUWidth, Int iPUHeight, Int& iNumSP, Int& iNumSPInOneLine, Int& iSPWidth, Int& iSPHeight);
-  Void          getSPAbsPartIdx(UInt uiBaseAbsPartIdx, Int iWidth, Int iHeight, Int iPartIdx, Int iNumPartLine, UInt& ruiPartAddr );
-  Void          setInterDirSP( UInt uiDir, UInt uiAbsPartIdx, Int iWidth, Int iHeight );
-#endif
-#if NH_3D_IV_MERGE
-  Bool          getInterViewMergeCands          ( UInt uiPartIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv, DisInfo* pDInfo, Int* availableMcDc, Bool bIsDepth           
-
-#if NH_3D_SPIVMP
-    , TComMvField* pcMFieldSP, UChar* puhInterDirSP
-#endif    
-    , Bool bICFlag
-    );   
-#endif
-#if NH_3D_ARP
+  
+  Void          getDisMvpCandNBDV     ( DisInfo* pDInfo, Bool bDepthRefine = false   );    
+  Void          getDispforDepth       ( UInt uiPartIdx, UInt uiPartAddr, DisInfo* cDisp);
+
+  Pel           getMcpFromDM          ( TComPicYuv* pcBaseViewDepthPicYuv, TComMv* mv, Int iBlkX, Int iBlkY, Int iWidth, Int iHeight, Int* aiShiftLUT );
+  Void          estimateDVFromDM      ( Int refViewIdx, UInt uiPartIdx, TComPic* picDepth, UInt uiPartAddr, TComMv* cMvPred );
+  Bool          getNeighDepth         ( UInt uiPartIdx, UInt uiPartAddr, Pel* pNeighDepth, Int index);
+  Void          getSPPara             ( Int iPUWidth   , Int iPUHeight, Int& iNumSP, Int& iNumSPInOneLine, Int& iSPWidth, Int& iSPHeight);
+  Void          getSPAbsPartIdx       ( UInt uiBaseAbsPartIdx, Int iWidth, Int iHeight, Int iPartIdx, Int iNumPartLine, UInt& ruiPartAddr );
+  Void          setInterDirSP         ( UInt uiDir    , UInt uiAbsPartIdx, Int iWidth, Int iHeight );
+  Bool          getInterViewMergeCands( UInt uiPartIdx, Int* paiPdmRefIdx, TComMv* pacPdmMv, DisInfo* pDInfo, Int* availableMcDc, Bool bIsDepth , TComMvField* pcMFieldSP, UChar* puhInterDirSP, Bool bICFlag );   
+
   UChar*        getARPW            ()              const          { return m_puhARPW;               }
   UChar         getARPW            ( UInt uiIdx )  const          { return m_puhARPW[uiIdx];        }
   Void          setARPW            ( UInt uiIdx, UChar w )   { m_puhARPW[uiIdx] = w;           }
   Void          setARPWSubParts    ( UChar w, UInt uiAbsPartIdx, UInt uiDepth );
-#endif
-#if NH_3D_IC
+
   Bool*         getICFlag          ()                        { return m_pbICFlag;               }
   Bool          getICFlag          ( UInt uiIdx )            { return m_pbICFlag[uiIdx];        }
@@ -541,38 +501,35 @@
   Void          setICFlagSubParts  ( Bool bICFlag,  UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
   Bool          isICFlagRequired   ( UInt uiAbsPartIdx );
-  Void          getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight, UInt uiAbsPartIdx = 0, Bool bLCU = false) const;
-#elif NH_3D_VSP
-  Void          getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight, UInt uiAbsPartIdx = 0, Bool bLCU = false) const;
-#else
-  // -------------------------------------------------------------------------------------------------------------------
-  // member functions for accessing partition information
-  // -------------------------------------------------------------------------------------------------------------------
-
-  Void          getPartIndexAndSize           ( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight ) const; // This is for use by a leaf/sub CU object only, with no additional AbsPartIdx
-#endif
-  UChar         getNumPartitions              ( const UInt uiAbsPartIdx = 0 ) const;
-  Bool          isFirstAbsZorderIdxInDepth    ( UInt uiAbsPartIdx, UInt uiDepth ) const;
-
-#if NH_3D_DMM
-  Pel*  getDmmDeltaDC                 ( DmmID dmmType, UInt segId )                      { return m_dmmDeltaDC[dmmType][segId];        } 
-  Pel   getDmmDeltaDC                 ( DmmID dmmType, UInt segId, UInt uiIdx )          { return m_dmmDeltaDC[dmmType][segId][uiIdx]; } 
-  Void  setDmmDeltaDC                 ( DmmID dmmType, UInt segId, UInt uiIdx, Pel val ) { m_dmmDeltaDC[dmmType][segId][uiIdx] = val;  }
-
-  UInt* getDmm1WedgeTabIdx            ()                                                { return m_dmm1WedgeTabIdx;          }        
-  UInt  getDmm1WedgeTabIdx            ( UInt uiIdx )                                    { return m_dmm1WedgeTabIdx[uiIdx];   }
-  Void  setDmm1WedgeTabIdx            ( UInt uiIdx, UInt tabIdx )                       { m_dmm1WedgeTabIdx[uiIdx] = tabIdx; }
-  Void  setDmm1WedgeTabIdxSubParts    ( UInt tabIdx, UInt uiAbsPartIdx, UInt uiDepth );
-#endif
-#if NH_3D_SDC_INTRA
+
+  Pel*          getDmmDeltaDC                 ( DmmID dmmType, UInt segId )                      { return m_dmmDeltaDC[dmmType][segId];        } 
+  Pel           getDmmDeltaDC                 ( DmmID dmmType, UInt segId, UInt uiIdx )          { return m_dmmDeltaDC[dmmType][segId][uiIdx]; } 
+  Void          setDmmDeltaDC                 ( DmmID dmmType, UInt segId, UInt uiIdx, Pel val ) { m_dmmDeltaDC[dmmType][segId][uiIdx] = val;  }
+
+  UInt*         getDmm1WedgeTabIdx            ()                                                { return m_dmm1WedgeTabIdx;          }        
+  UInt          getDmm1WedgeTabIdx            ( UInt uiIdx )                                    { return m_dmm1WedgeTabIdx[uiIdx];   }
+  Void          setDmm1WedgeTabIdx            ( UInt uiIdx, UInt tabIdx )                       { m_dmm1WedgeTabIdx[uiIdx] = tabIdx; }
+  Void          setDmm1WedgeTabIdxSubParts    ( UInt tabIdx, UInt uiAbsPartIdx, UInt uiDepth );
+
   Bool*         getSDCFlag          ()                        { return m_pbSDCFlag;               }
   Bool          getSDCFlag          ( UInt uiIdx )            { return m_pbSDCFlag[uiIdx];        }
   Void          setSDCFlagSubParts  ( Bool bSDCFlag, UInt uiAbsPartIdx, UInt uiDepth );
-  
+
   Bool          getSDCAvailable             ( UInt uiAbsPartIdx );
-  
+
   Pel*          getSDCSegmentDCOffset( UInt uiSeg ) { return m_apSegmentDCOffset[uiSeg]; }
   Pel           getSDCSegmentDCOffset( UInt uiSeg, UInt uiPartIdx ) { return m_apSegmentDCOffset[uiSeg][uiPartIdx]; }
   Void          setSDCSegmentDCOffset( Pel pOffset, UInt uiSeg, UInt uiPartIdx) { m_apSegmentDCOffset[uiSeg][uiPartIdx] = pOffset; }
-#endif
+
+  Void          xDeriveRightBottomNbIdx(Int &uiLCUIdxRBNb, Int &uiPartIdxRBNb );
+  Bool          xCheckSpatialNBDV (const TComDataCU* pcTmpCU, UInt uiIdx, DisInfo* pNbDvInfo, Bool bSearchForMvpDv, IDVInfo* paMvpDvInfo, UInt uiMvpDvPos  , Bool bDepthRefine = false  );
+  Bool          xGetColDisMV      ( Int currCandPic, RefPicList eRefPicList, Int refidx, Int uiCUAddr, Int uiPartUnitIdx, TComMv& rcMv, Int & iTargetViewIdx, Int & iStartViewIdx );
+
+
+  Void          getPartIndexAndSize( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight, UInt uiAbsPartIdx = 0, Bool bLCU = false) const;
+#else
+  Void          getPartIndexAndSize           ( UInt uiPartIdx, UInt& ruiPartAddr, Int& riWidth, Int& riHeight ) const; // This is for use by a leaf/sub CU object only, with no additional AbsPartIdx
+#endif
+  UChar         getNumPartitions              ( const UInt uiAbsPartIdx = 0 ) const;
+  Bool          isFirstAbsZorderIdxInDepth    ( UInt uiAbsPartIdx, UInt uiDepth ) const;
   
   // -------------------------------------------------------------------------------------------------------------------
@@ -586,23 +543,26 @@
   Void          getPartPosition               ( UInt partIdx, Int& xP, Int& yP, Int& nPSW, Int& nPSH ) const;
 
-  Void          setMVPIdx             ( RefPicList eRefPicList, UInt uiIdx, Int iMVPIdx)  { m_apiMVPIdx[eRefPicList][uiIdx] = iMVPIdx;  }
+  Void          setMVPIdx                     ( RefPicList eRefPicList, UInt uiIdx, Int iMVPIdx)  { m_apiMVPIdx[eRefPicList][uiIdx] = iMVPIdx;  }
   Int           getMVPIdx                     ( RefPicList eRefPicList, UInt uiIdx) const                  { return m_apiMVPIdx[eRefPicList][uiIdx];    }
   SChar*        getMVPIdx                     ( RefPicList eRefPicList )                                   { return m_apiMVPIdx[eRefPicList];           }
 
-  Void          setMVPNum             ( RefPicList eRefPicList, UInt uiIdx, Int iMVPNum ) { m_apiMVPNum[eRefPicList][uiIdx] = iMVPNum;  }
+  Void          setMVPNum                     ( RefPicList eRefPicList, UInt uiIdx, Int iMVPNum ) { m_apiMVPNum[eRefPicList][uiIdx] = iMVPNum;  }
   Int           getMVPNum                     ( RefPicList eRefPicList, UInt uiIdx ) const                 { return m_apiMVPNum[eRefPicList][uiIdx];    }
   SChar*        getMVPNum                     ( RefPicList eRefPicList )                                   { return m_apiMVPNum[eRefPicList];           }
 
-  Void          setMVPIdxSubParts     ( Int iMVPIdx, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
-  Void          setMVPNumSubParts     ( Int iMVPNum, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+  Void          setMVPIdxSubParts             ( Int iMVPIdx, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
+  Void          setMVPNumSubParts             ( Int iMVPNum, RefPicList eRefPicList, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
 
   Void          clipMv                        ( TComMv&     rcMv     ) const;
 
-#if NH_MV
-  Void          checkMvVertRest (TComMv&  rcMv,  RefPicList eRefPicList, int iRefIdx );
-#endif
   Void          getMvPredLeft                 ( TComMv&     rcMvPred ) const                               { rcMvPred = m_cMvFieldA.getMv();            }
   Void          getMvPredAbove                ( TComMv&     rcMvPred ) const                               { rcMvPred = m_cMvFieldB.getMv();            }
   Void          getMvPredAboveRight           ( TComMv&     rcMvPred ) const                               { rcMvPred = m_cMvFieldC.getMv();            }
+
+#if NH_MV
+  Void          checkMvVertRest (TComMv&  rcMv,  RefPicList eRefPicList, int iRefIdx );
+#endif
+
+
 #if NH_3D
   Void          compressMV            ( Int scale );
@@ -619,5 +579,4 @@
   TComDataCU*   getCtuAboveLeft             () { return m_pCtuAboveLeft;  }
   TComDataCU*   getCtuAboveRight            () { return m_pCtuAboveRight; }
-  TComDataCU*   getCUColocated              ( RefPicList eRefPicList ) { return m_apcCUColocated[eRefPicList]; }
   Bool          CUIsFromSameSlice           ( const TComDataCU *pCU /* Can be NULL */) const { return ( pCU!=NULL && pCU->getSlice()->getSliceCurStartCtuTsAddr() == getSlice()->getSliceCurStartCtuTsAddr() ); }
   Bool          CUIsFromSameTile            ( const TComDataCU *pCU /* Can be NULL */) const;
@@ -653,10 +612,8 @@
   Void          deriveLeftBottomIdx           ( UInt uiPartIdx, UInt& ruiPartIdxLB ) const;
 
+  Bool          hasEqualMotion                ( UInt uiAbsPartIdx, const TComDataCU* pcCandCU, UInt uiCandAbsPartIdx ) const;
+
 #if NH_3D
   Bool          hasEqualMotion              ( Int dirA, const TComMvField* mvFieldA,  Int dirB, const TComMvField* mvFieldB  );
-#endif
-  Bool          hasEqualMotion                ( UInt uiAbsPartIdx, const TComDataCU* pcCandCU, UInt uiCandAbsPartIdx ) const;
-
-#if NH_3D_MLC
   Bool          getAvailableFlagA1() { return m_bAvailableFlagA1;   }
   Bool          getAvailableFlagB1() { return m_bAvailableFlagB1;   }
@@ -664,33 +621,25 @@
   Bool          getAvailableFlagA0() { return m_bAvailableFlagA0;   }
   Bool          getAvailableFlagB2() { return m_bAvailableFlagB2;   }
-  Void          initAvailableFlags() { m_bAvailableFlagA1 = m_bAvailableFlagB1 = m_bAvailableFlagB0 = m_bAvailableFlagA0 = m_bAvailableFlagB2 = 0;  }
-  Void          buildMCL(TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours
-#if NH_3D_VSP
-    , Int* vspFlag
-#endif
-#if NH_3D_SPIVMP
-    , Bool* pbSPIVMPFlag
-#endif
-    , Int& numValidMergeCand
-    );
-  Void          xGetInterMergeCandidates      ( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours
-#if NH_3D_SPIVMP
-  , TComMvField* pcMvFieldSP, UChar* puhInterDirSP
-#endif
-  , Int& numValidMergeCand, Int mrgCandIdx = -1 );
-#endif
-#if NH_3D
-  Void          getInterMergeCandidates       ( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx = -1 );
+  
+  Void          initAvailableFlags() { m_bAvailableFlagA1 = m_bAvailableFlagB1 = m_bAvailableFlagB0 = m_bAvailableFlagA0 = m_bAvailableFlagB2 = 0;  }  
+  
+  Void          buildMCL(TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours, Int* vspFlag, Bool* pbSPIVMPFlag , Int& numValidMergeCand    );  
+  Void          xGetInterMergeCandidates      ( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours, TComMvField* pcMvFieldSP, UChar* puhInterDirSP, Int& numValidMergeCand, Int mrgCandIdx = -1 );
+#endif
+
+#if MCTS_ENC_CHECK
+  Void          getInterMergeCandidates       ( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, UInt& numSpatialMergeCandidates , Int mrgCandIdx = -1)
 #else
-  Void          getInterMergeCandidates       ( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx = -1 ) const;
-#endif
-
-#if NH_3D_VSP
-#if NH_3D_SPIVMP
+  Void          getInterMergeCandidates       ( UInt uiAbsPartIdx, UInt uiPUIdx, TComMvField* pcMFieldNeighbours, UChar* puhInterDirNeighbours, Int& numValidMergeCand, Int mrgCandIdx = -1 )
+#endif
+#if !NH_3D
+  const
+#endif
+;
+#if NH_3D
   Bool*         getSPIVMPFlag        ()                        const { return m_pbSPIVMPFlag;          }
   Bool          getSPIVMPFlag        ( UInt uiIdx )            const { return m_pbSPIVMPFlag[uiIdx];   }
   Void          setSPIVMPFlag        ( UInt uiIdx, Bool n )     { m_pbSPIVMPFlag[uiIdx] = n;      }
   Void          setSPIVMPFlagSubParts( Bool bSPIVMPFlag, UInt uiAbsPartIdx, UInt uiPartIdx, UInt uiDepth );
-#endif
 
   SChar*        getVSPFlag        ()                        const { return m_piVSPFlag;          }
@@ -729,5 +678,5 @@
   UInt          getCtxSkipFlag                ( UInt   uiAbsPartIdx ) const;
   UInt          getCtxInterDir                ( UInt   uiAbsPartIdx ) const;
-#if NH_3D_ARP
+#if NH_3D
   UInt          getCTXARPWFlag                  ( UInt   uiAbsPartIdx                                 );
 #endif  
Index: /trunk/source/Lib/TLibCommon/TComInterpolationFilter.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComInterpolationFilter.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -47,4 +47,7 @@
 #include "TComChromaFormat.h"
 
+#if VECTOR_CODING__INTERPOLATION_FILTER && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+#include <emmintrin.h>
+#endif
 
 //! \ingroup TLibCommon
@@ -75,5 +78,106 @@
 };
 
-#if NH_3D_ARP
+#if VECTOR_CODING__INTERPOLATION_FILTER && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+inline __m128i simdInterpolateLuma4( Short const *src , Int srcStride , __m128i *mmCoeff , const __m128i & mmOffset , Int shift )
+{
+  __m128i sumHi = _mm_setzero_si128();
+  __m128i sumLo = _mm_setzero_si128();
+  for( Int n = 0 ; n < 8 ; n++ )
+  {
+    __m128i mmPix = _mm_loadl_epi64( ( __m128i* )src );
+    __m128i hi = _mm_mulhi_epi16( mmPix , mmCoeff[n] );
+    __m128i lo = _mm_mullo_epi16( mmPix , mmCoeff[n] );
+    sumHi = _mm_add_epi32( sumHi , _mm_unpackhi_epi16( lo , hi ) );
+    sumLo = _mm_add_epi32( sumLo , _mm_unpacklo_epi16( lo , hi ) );
+    src += srcStride;
+  }
+  sumHi = _mm_srai_epi32( _mm_add_epi32( sumHi , mmOffset ) , shift );
+  sumLo = _mm_srai_epi32( _mm_add_epi32( sumLo , mmOffset ) , shift );
+  return( _mm_packs_epi32( sumLo , sumHi ) );
+}
+
+inline __m128i simdInterpolateChroma4( Short const *src , Int srcStride , __m128i *mmCoeff , const __m128i & mmOffset , Int shift )
+{
+  __m128i sumHi = _mm_setzero_si128();
+  __m128i sumLo = _mm_setzero_si128();
+  for( Int n = 0 ; n < 4 ; n++ )
+  {
+    __m128i mmPix = _mm_loadl_epi64( ( __m128i* )src );
+    __m128i hi = _mm_mulhi_epi16( mmPix , mmCoeff[n] );
+    __m128i lo = _mm_mullo_epi16( mmPix , mmCoeff[n] );
+    sumHi = _mm_add_epi32( sumHi , _mm_unpackhi_epi16( lo , hi ) );
+    sumLo = _mm_add_epi32( sumLo , _mm_unpacklo_epi16( lo , hi ) );
+    src += srcStride;
+  }
+  sumHi = _mm_srai_epi32( _mm_add_epi32( sumHi , mmOffset ) , shift );
+  sumLo = _mm_srai_epi32( _mm_add_epi32( sumLo , mmOffset ) , shift );
+  return( _mm_packs_epi32( sumLo , sumHi ) );
+}
+
+inline __m128i simdInterpolateLuma8( Short const *src , Int srcStride , __m128i *mmCoeff , const __m128i & mmOffset , Int shift )
+{
+  __m128i sumHi = _mm_setzero_si128();
+  __m128i sumLo = _mm_setzero_si128();
+  for( Int n = 0 ; n < 8 ; n++ )
+  {
+    __m128i mmPix = _mm_loadu_si128( ( __m128i* )src );
+    __m128i hi = _mm_mulhi_epi16( mmPix , mmCoeff[n] );
+    __m128i lo = _mm_mullo_epi16( mmPix , mmCoeff[n] );
+    sumHi = _mm_add_epi32( sumHi , _mm_unpackhi_epi16( lo , hi ) );
+    sumLo = _mm_add_epi32( sumLo , _mm_unpacklo_epi16( lo , hi ) );
+    src += srcStride;
+  }
+  sumHi = _mm_srai_epi32( _mm_add_epi32( sumHi , mmOffset ) , shift );
+  sumLo = _mm_srai_epi32( _mm_add_epi32( sumLo , mmOffset ) , shift );
+  return( _mm_packs_epi32( sumLo , sumHi ) );
+}
+
+inline __m128i simdInterpolateLuma2P8( Short const *src , Int srcStride , __m128i *mmCoeff , const __m128i & mmOffset , Int shift )
+{
+  __m128i sumHi = _mm_setzero_si128();
+  __m128i sumLo = _mm_setzero_si128();
+  for( Int n = 0 ; n < 2 ; n++ )
+  {
+    __m128i mmPix = _mm_loadu_si128( ( __m128i* )src );
+    __m128i hi = _mm_mulhi_epi16( mmPix , mmCoeff[n] );
+    __m128i lo = _mm_mullo_epi16( mmPix , mmCoeff[n] );
+    sumHi = _mm_add_epi32( sumHi , _mm_unpackhi_epi16( lo , hi ) );
+    sumLo = _mm_add_epi32( sumLo , _mm_unpacklo_epi16( lo , hi ) );
+    src += srcStride;
+  }
+  sumHi = _mm_srai_epi32( _mm_add_epi32( sumHi , mmOffset ) , shift );
+  sumLo = _mm_srai_epi32( _mm_add_epi32( sumLo , mmOffset ) , shift );
+  return( _mm_packs_epi32( sumLo , sumHi ) );
+}
+
+inline __m128i simdInterpolateLuma2P4( Short const *src , Int srcStride , __m128i *mmCoeff , const __m128i & mmOffset , Int shift )
+{
+  __m128i sumHi = _mm_setzero_si128();
+  __m128i sumLo = _mm_setzero_si128();
+  for( Int n = 0 ; n < 2 ; n++ )
+  {
+    __m128i mmPix = _mm_loadl_epi64( ( __m128i* )src );
+    __m128i hi = _mm_mulhi_epi16( mmPix , mmCoeff[n] );
+    __m128i lo = _mm_mullo_epi16( mmPix , mmCoeff[n] );
+    sumHi = _mm_add_epi32( sumHi , _mm_unpackhi_epi16( lo , hi ) );
+    sumLo = _mm_add_epi32( sumLo , _mm_unpacklo_epi16( lo , hi ) );
+    src += srcStride;
+  }
+  sumHi = _mm_srai_epi32( _mm_add_epi32( sumHi , mmOffset ) , shift );
+  sumLo = _mm_srai_epi32( _mm_add_epi32( sumLo , mmOffset ) , shift );
+  return( _mm_packs_epi32( sumLo , sumHi ) );
+}
+
+inline __m128i simdClip3( __m128i mmMin , __m128i mmMax , __m128i mmPix )
+{
+  __m128i mmMask = _mm_cmpgt_epi16( mmPix , mmMin );
+  mmPix = _mm_or_si128( _mm_and_si128( mmMask , mmPix ) , _mm_andnot_si128( mmMask , mmMin ) );
+  mmMask = _mm_cmplt_epi16( mmPix , mmMax );
+  mmPix = _mm_or_si128( _mm_and_si128( mmMask , mmPix ) , _mm_andnot_si128( mmMask , mmMax ) );
+  return( mmPix );
+}
+#endif
+
+#if NH_3D
 const Short TComInterpolationFilter::m_lumaFilterARP[4][NTAPS_LUMA_ARP] =
 {
@@ -240,4 +344,135 @@
   }
 
+#if VECTOR_CODING__INTERPOLATION_FILTER && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  if( bitDepth <= 10 )
+  {
+    if( N == 8 && !( width & 0x07 ) )
+    {
+      Short minVal = 0;
+      __m128i mmOffset = _mm_set1_epi32( offset );
+      __m128i mmCoeff[8];
+      __m128i mmMin = _mm_set1_epi16( minVal );
+      __m128i mmMax = _mm_set1_epi16( maxVal );
+      for( Int n = 0 ; n < 8 ; n++ )
+        mmCoeff[n] = _mm_set1_epi16( c[n] );
+      for( row = 0 ; row < height ; row++ )
+      {
+        for( col = 0 ; col < width ; col += 8 )
+        {
+          __m128i mmFiltered = simdInterpolateLuma8( src + col , cStride , mmCoeff , mmOffset , shift );
+          if( isLast )
+          {
+            mmFiltered = simdClip3( mmMin , mmMax , mmFiltered );
+          }
+          _mm_storeu_si128( ( __m128i * )( dst + col ) , mmFiltered );
+        }
+        src += srcStride;
+        dst += dstStride;
+      }
+      return;
+    }
+    else if( N == 8 && !( width & 0x03 ) )
+    {
+      Short minVal = 0;
+      __m128i mmOffset = _mm_set1_epi32( offset );
+      __m128i mmCoeff[8];
+      __m128i mmMin = _mm_set1_epi16( minVal );
+      __m128i mmMax = _mm_set1_epi16( maxVal );
+      for( Int n = 0 ; n < 8 ; n++ )
+        mmCoeff[n] = _mm_set1_epi16( c[n] );
+      for( row = 0 ; row < height ; row++ )
+      {
+        for( col = 0 ; col < width ; col += 4 )
+        {
+          __m128i mmFiltered = simdInterpolateLuma4( src + col , cStride , mmCoeff , mmOffset , shift );
+          if( isLast )
+          {
+            mmFiltered = simdClip3( mmMin , mmMax , mmFiltered );
+          }
+          _mm_storel_epi64( ( __m128i * )( dst + col ) , mmFiltered );
+        }
+        src += srcStride;
+        dst += dstStride;
+      }
+      return;
+    }
+    else if( N == 4 && !( width & 0x03 ) )
+    {
+      Short minVal = 0;
+      __m128i mmOffset = _mm_set1_epi32( offset );
+      __m128i mmCoeff[8];
+      __m128i mmMin = _mm_set1_epi16( minVal );
+      __m128i mmMax = _mm_set1_epi16( maxVal );
+      for( Int n = 0 ; n < 4 ; n++ )
+        mmCoeff[n] = _mm_set1_epi16( c[n] );
+      for( row = 0 ; row < height ; row++ )
+      {
+        for( col = 0 ; col < width ; col += 4 )
+        {
+          __m128i mmFiltered = simdInterpolateChroma4( src + col , cStride , mmCoeff , mmOffset , shift );
+          if( isLast )
+          {
+            mmFiltered = simdClip3( mmMin , mmMax , mmFiltered );
+          }
+          _mm_storel_epi64( ( __m128i * )( dst + col ) , mmFiltered );
+        }
+        src += srcStride;
+        dst += dstStride;
+      }
+      return;
+    }
+    else if( N == 2 && !( width & 0x07 ) )
+    {
+      Short minVal = 0;
+      __m128i mmOffset = _mm_set1_epi32( offset );
+      __m128i mmCoeff[2];
+      __m128i mmMin = _mm_set1_epi16( minVal );
+      __m128i mmMax = _mm_set1_epi16( maxVal );
+      for( Int n = 0 ; n < 2 ; n++ )
+        mmCoeff[n] = _mm_set1_epi16( c[n] );
+      for( row = 0 ; row < height ; row++ )
+      {
+        for( col = 0 ; col < width ; col += 8 )
+        {
+          __m128i mmFiltered = simdInterpolateLuma2P8( src + col , cStride , mmCoeff , mmOffset , shift );
+          if( isLast )
+          {
+            mmFiltered = simdClip3( mmMin , mmMax , mmFiltered );
+          }
+          _mm_storeu_si128( ( __m128i * )( dst + col ) , mmFiltered );
+        }
+        src += srcStride;
+        dst += dstStride;
+      }
+      return;
+    }
+    else if( N == 2 && !( width & 0x03 ) )
+    {
+      Short minVal = 0;
+      __m128i mmOffset = _mm_set1_epi32( offset );
+      __m128i mmCoeff[8];
+      __m128i mmMin = _mm_set1_epi16( minVal );
+      __m128i mmMax = _mm_set1_epi16( maxVal );
+      for( Int n = 0 ; n < 2 ; n++ )
+        mmCoeff[n] = _mm_set1_epi16( c[n] );
+      for( row = 0 ; row < height ; row++ )
+      {
+        for( col = 0 ; col < width ; col += 4 )
+        {
+          __m128i mmFiltered = simdInterpolateLuma2P4( src + col , cStride , mmCoeff , mmOffset , shift );
+          if( isLast )
+          {
+            mmFiltered = simdClip3( mmMin , mmMax , mmFiltered );
+          }
+          _mm_storel_epi64( ( __m128i * )( dst + col ) , mmFiltered );
+        }
+        src += srcStride;
+        dst += dstStride;
+      }
+      return;
+    }
+  }
+#endif
+
   for (row = 0; row < height; row++)
   {
@@ -360,5 +595,5 @@
  * \param  bitDepth   Bit depth
  */
-#if NH_3D_ARP
+#if NH_3D
 Void TComInterpolationFilter::filterHor(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac, Bool isLast, const ChromaFormat fmt, const Int bitDepth, Bool filterType )
 #else
@@ -374,5 +609,5 @@
   {
     assert(frac >= 0 && frac < LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS);
-#if NH_3D_ARP
+#if NH_3D
     if(filterType)
     {
@@ -383,5 +618,5 @@
 #endif
     filterHor<NTAPS_LUMA>(bitDepth, src, srcStride, dst, dstStride, width, height, isLast, m_lumaFilter[frac]);
-#if NH_3D_ARP
+#if NH_3D
     }
 #endif
@@ -392,5 +627,5 @@
     const UInt csx = getComponentScaleX(compID, fmt);
     assert(frac >=0 && csx<2 && (frac<<(1-csx)) < CHROMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS);
-#if NH_3D_ARP
+#if NH_3D
     if(filterType)
     {
@@ -401,5 +636,5 @@
 #endif
     filterHor<NTAPS_CHROMA>(bitDepth, src, srcStride, dst, dstStride, width, height, isLast, m_chromaFilter[frac<<(1-csx)]);
-#if NH_3D_ARP
+#if NH_3D
     }
 #endif
@@ -424,5 +659,5 @@
  * \param  bitDepth   Bit depth
  */
-#if NH_3D_ARP
+#if NH_3D
 Void TComInterpolationFilter::filterVer(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac, Bool isFirst, Bool isLast, const ChromaFormat fmt, const Int bitDepth, Bool filterType )
 #else
@@ -437,5 +672,5 @@
   {
     assert(frac >= 0 && frac < LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS);
-#if NH_3D_ARP
+#if NH_3D
     if(filterType)
     {
@@ -445,6 +680,6 @@
     {
 #endif
-    filterVer<NTAPS_LUMA>(bitDepth, src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_lumaFilter[frac]);
-#if NH_3D_ARP
+      filterVer<NTAPS_LUMA>(bitDepth, src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_lumaFilter[frac]);
+#if NH_3D
     }
 #endif
@@ -455,5 +690,5 @@
     const UInt csy = getComponentScaleY(compID, fmt);
     assert(frac >=0 && csy<2 && (frac<<(1-csy)) < CHROMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS);
-#if NH_3D_ARP
+#if NH_3D
     if(filterType)
     {
@@ -463,9 +698,9 @@
     {
 #endif
-    filterVer<NTAPS_CHROMA>(bitDepth, src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_chromaFilter[frac<<(1-csy)]);
-#if NH_3D_ARP
-    }
-#endif
-    }
-    }
+      filterVer<NTAPS_CHROMA>(bitDepth, src, srcStride, dst, dstStride, width, height, isFirst, isLast, m_chromaFilter[frac<<(1-csy)]);
+#if NH_3D
+    }
+#endif
+  }
+}
 //! \}
Index: /trunk/source/Lib/TLibCommon/TComInterpolationFilter.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComInterpolationFilter.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -45,5 +45,5 @@
 //! \{
 
-#if NH_3D_ARP
+#if NH_3D
 #define NTAPS_LUMA_ARP    2 ///< Number of taps for luma
 #define NTAPS_CHROMA_ARP  2 ///< Number of taps for chroma
@@ -63,5 +63,5 @@
   static const TFilterCoeff m_lumaFilter[LUMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS][NTAPS_LUMA];     ///< Luma filter taps
   static const TFilterCoeff m_chromaFilter[CHROMA_INTERPOLATION_FILTER_SUB_SAMPLE_POSITIONS][NTAPS_CHROMA]; ///< Chroma filter taps
-#if NH_3D_ARP
+#if NH_3D
   static const Short m_lumaFilterARP  [4][NTAPS_LUMA_ARP];     ///< Luma filter taps for ARP
   static const Short m_chromaFilterARP[8][NTAPS_CHROMA_ARP];   ///< Chroma filter taps for ARP
@@ -82,5 +82,5 @@
   ~TComInterpolationFilter() {}
 
-#if NH_3D_ARP
+#if NH_3D
   Void filterHor(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac,               Bool isLast, const ChromaFormat fmt, const Int bitDepth , Bool filterType = false );
 #else
@@ -88,5 +88,5 @@
 #endif
 
-#if NH_3D_ARP
+#if NH_3D
   Void filterVer(const ComponentID compID, Pel *src, Int srcStride, Pel *dst, Int dstStride, Int width, Int height, Int frac,               Bool isFirst, Bool isLast, const ChromaFormat fmt, const Int bitDepth , Bool filterType = false );
 #else
Index: /trunk/source/Lib/TLibCommon/TComList.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComList.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComList.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComLoopFilter.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComLoopFilter.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -561,5 +561,5 @@
         Pel        *piTmpSrc                      = piSrc;
   const TComSPS    &sps                           = *(pcCU->getSlice()->getSPS());
-  const Bool        ppsTransquantBypassEnableFlag = pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag();
+  const Bool        ppsTransquantBypassEnabledFlag = pcCU->getSlice()->getPPS()->getTransquantBypassEnabledFlag();
   const Int         bitDepthLuma                  = sps.getBitDepth(CHANNEL_TYPE_LUMA);
   const Bool        lfCrossSliceBoundaryFlag      = pcCU->getSlice()->getLFCrossSliceBoundaryFlag();
@@ -644,5 +644,5 @@
         Int d =  d0 + d3;
 
-        if (bPCMFilter || ppsTransquantBypassEnableFlag)
+        if (bPCMFilter || ppsTransquantBypassEnabledFlag)
         {
           // Check if each of PUs is I_PCM with LF disabling
@@ -769,5 +769,5 @@
       iQP_P = pcCUP->getQP(uiPartPIdx);
 
-      if (bPCMFilter || pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+      if (bPCMFilter || pcCU->getSlice()->getPPS()->getTransquantBypassEnabledFlag())
       {
         // Check if each of PUs is I_PCM with LF disabling
Index: /trunk/source/Lib/TLibCommon/TComLoopFilter.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComLoopFilter.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComLoopFilter.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComMotionInfo.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComMotionInfo.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -40,5 +40,5 @@
 #include "assert.h"
 #include <stdlib.h>
-#if NH_3D_SPIVMP
+#if NH_3D
 #include "TComDataCU.h"
 #include "TComPic.h"
@@ -330,5 +330,5 @@
 }
 
-#if NH_3D_SPIVMP
+#if NH_3D
 Void TComCUMvField::setMvFieldSP( TComDataCU* pcCU, UInt uiAbsPartIdx, TComMvField cMvField, Int iWidth, Int iHeight  )
 {
@@ -358,4 +358,29 @@
  * \param scale      Factor by which to subsample motion information
  */
+#if REDUCED_ENCODER_MEMORY
+Void TComCUMvField::compress(SChar *pePredMode, const SChar* pePredModeSource, const Int scale, const TComCUMvField &source)
+{
+  const Int numSubpartsWithIdenticalMotion = scale * scale;
+  assert( numSubpartsWithIdenticalMotion > 0 && numSubpartsWithIdenticalMotion <= m_uiNumPartition);
+  assert(source.m_uiNumPartition == m_uiNumPartition);
+
+  for ( Int partIdx = 0; partIdx < m_uiNumPartition; partIdx += numSubpartsWithIdenticalMotion )
+  {
+    TComMv cMv(0,0);
+    Int iRefIdx = 0;
+
+    cMv = source.m_pcMv[ partIdx ];
+    PredMode predMode = static_cast<PredMode>( pePredModeSource[ partIdx ] );
+    iRefIdx = source.m_piRefIdx[ partIdx ];
+    for ( Int i = 0; i < numSubpartsWithIdenticalMotion; i++ )
+    {
+      m_pcMv[ partIdx + i ] = cMv;
+      pePredMode[ partIdx + i ] = predMode;
+      m_piRefIdx[ partIdx + i ] = iRefIdx;
+    }
+  }
+}
+#else
+
 Void TComCUMvField::compress(SChar* pePredMode, Int scale)
 {
@@ -379,4 +404,5 @@
   }
 }
+#endif
 
 #if NH_MV
@@ -405,5 +431,5 @@
 }
 
-#if NH_3D_MLC
+#if NH_3D
 Void TComMotionCand::print( Int i )
 {
Index: /trunk/source/Lib/TLibCommon/TComMotionInfo.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComMotionInfo.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComMotionInfo.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
-* Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -51,5 +51,5 @@
 // ====================================================================================================================
 
-#if NH_3D_SPIVMP
+#if NH_3D
 class TComDataCU;
 #endif
@@ -59,13 +59,14 @@
   TComMv m_acMvCand[ AMVP_MAX_NUM_CANDS ];  ///< array of motion vector predictor candidates
   Int    iN;                                ///< number of motion vector predictor candidates
+#if MCTS_ENC_CHECK
+  UInt   numSpatialMVPCandidates;
+#endif
 } AMVPInfo;
 
-#if NH_3D_NBDV
+#if NH_3D
 typedef struct _DisCand 
 {
   TComMv m_acNBDV;              // DV from NBDV
-#if NH_3D_NBDV_REF 
   TComMv m_acDoNBDV;            // DV from DoNBDV
-#endif  
   Int    m_aVIdxCan;            // View order index (the same with the NBDV and the DoNBDV)
 } DisInfo;
@@ -108,5 +109,5 @@
   Int getHor   () const { return  m_acMv.getHor(); }
   Int getVer   () const { return  m_acMv.getVer(); }
-#if NH_3D_IV_MERGE
+#if NH_3D
   Bool operator== ( const TComMvField& rcMv ) const
   {
@@ -168,8 +169,6 @@
   Void    setAllRefIdx ( Int iRefIdx,                 PartSize eMbMode, Int iPartAddr, UInt uiDepth, Int iPartIdx=0 );
   Void    setAllMvField( TComMvField const & mvField, PartSize eMbMode, Int iPartAddr, UInt uiDepth, Int iPartIdx=0 );
-#if NH_3D_SPIVMP
+#if NH_3D
   Void    setMvFieldSP ( TComDataCU* pcCU, UInt uiAbsPartIdx, TComMvField cMvField, Int iWidth, Int iHeight  );
-#endif
-#if NH_3D_VSP
   Void    setMv         ( Int iIdx, TComMv const & rcMv ) { m_pcMv[iIdx] = rcMv; }
   Void    setRefIdx     ( Int iIdx, Int iRefIdx )         { m_piRefIdx[iIdx] = iRefIdx; }
@@ -188,5 +187,9 @@
   }
   
+#if REDUCED_ENCODER_MEMORY
+  Void compress(SChar *pePredMode, const SChar* pePredModeSource, const Int scale, const TComCUMvField &source);
+#else
   Void compress(SChar* pePredMode, Int scale);
+#endif
 #if NH_MV
   Void print   (SChar* pePredMode);
@@ -196,5 +199,5 @@
 //! \}
 
-#if NH_3D_MLC
+#if NH_3D
 /// class for container of merge candidate
 class TComMotionCand
@@ -204,10 +207,6 @@
   TComMvField           m_cMvField[2];
   UChar                 m_uDir;
-#if NH_3D_VSP
   Int                   m_iVspFlag;
-#endif
-#if NH_3D_SPIVMP
   Bool                  m_bSPIVMPFlag;
-#endif
 
 public:
@@ -216,10 +215,6 @@
     m_bAvailable = false;
     m_uDir = 0;
-#if NH_3D_VSP
     m_iVspFlag = 0;
-#endif
-#if NH_3D_SPIVMP
     m_bSPIVMPFlag = false;
-#endif
   }
 
@@ -235,22 +230,11 @@
     m_bAvailable = false;
     m_uDir = 0;
-#if NH_3D_VSP
     m_iVspFlag = 0;
-#endif
-#if NH_3D_SPIVMP
     m_bSPIVMPFlag = false;
-#endif
     m_cMvField[0].setMvField(cZeroMv, NOT_VALID);
     m_cMvField[1].setMvField(cZeroMv, NOT_VALID);
   }
 
-  Void setCand(TComMvField* pcMvFieldNeighbours, UChar uhInterDirNeighbours
-#if NH_3D_VSP
-    , Int vspFlag
-#endif
-#if NH_3D_SPIVMP
-    , Bool bSPIVMPFlag
-#endif
-    )
+  Void setCand(TComMvField* pcMvFieldNeighbours, UChar uhInterDirNeighbours, Int vspFlag, Bool bSPIVMPFlag )
   {
     m_bAvailable = true;
@@ -258,35 +242,17 @@
     m_cMvField[1] = pcMvFieldNeighbours[1];
     m_uDir = uhInterDirNeighbours;
-#if NH_3D_VSP
     m_iVspFlag = vspFlag;
-#endif
-#if NH_3D_SPIVMP
     m_bSPIVMPFlag = bSPIVMPFlag;
-#endif
-  }
-  
-  Void getCand(Int iCount, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours
-#if NH_3D_VSP
-    , Int* vspFlag
-#endif
-#if NH_3D_SPIVMP
-    , Bool* pbSPIVMPFlag
-#endif
-    )
+  }
+  
+  Void getCand(Int iCount, TComMvField* pcMvFieldNeighbours, UChar* puhInterDirNeighbours, Int* vspFlag , Bool* pbSPIVMPFlag )
   {
     pcMvFieldNeighbours[iCount<<1] = m_cMvField[0];
     pcMvFieldNeighbours[(iCount<<1) + 1] = m_cMvField[1];
     puhInterDirNeighbours[iCount] = m_uDir;
-#if NH_3D_VSP
     vspFlag[iCount] = m_iVspFlag;
-#endif
-#if NH_3D_SPIVMP
     pbSPIVMPFlag[iCount] = m_bSPIVMPFlag;
-#endif
-  }
-
-
+  }
   Void print( Int i );
-
 };
 
Index: /trunk/source/Lib/TLibCommon/TComMv.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComMv.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComMv.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -57,5 +57,5 @@
   Short m_iHor;     ///< horizontal component of motion vector
   Short m_iVer;     ///< vertical component of motion vector
-#if NH_3D_NBDV
+#if NH_3D
   Bool  m_bIDV;       
   Short m_iIDVHor;    
@@ -72,5 +72,5 @@
   m_iHor(0),
   m_iVer(0)
-#if NH_3D_NBDV
+#if NH_3D
   , m_bIDV(false)
   , m_iIDVHor(0)
@@ -84,5 +84,5 @@
   m_iHor(iHor),
   m_iVer(iVer)
- #if NH_3D_NBDV
+ #if NH_3D
   , m_bIDV(false)
   , m_iIDVHor(0)
@@ -100,5 +100,5 @@
   Void  setHor    ( Short i )                   { m_iHor = i;                               }
   Void  setVer    ( Short i )                   { m_iVer = i;                               }
-#if NH_3D_NBDV
+#if NH_3D
   Void  setZero   ()                            { m_iHor = m_iVer = 0; m_bIDV = false; m_iIDVHor = m_iIDVVer = 0; m_iIDVVId = 0;  }
   Void   setIDVHor  (Short i)                    {m_iIDVHor = i;}
@@ -117,5 +117,5 @@
   Int   getAbsHor () const { return abs( m_iHor );   }
   Int   getAbsVer () const { return abs( m_iVer );   }
-#if NH_3D_NBDV
+#if NH_3D
   Short getIDVHor () const { return m_iIDVHor;       }
   Short getIDVVer () const { return m_iIDVVer;       }
Index: /trunk/source/Lib/TLibCommon/TComPattern.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPattern.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComPattern.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -74,40 +74,43 @@
 
 // ====================================================================================================================
-// Public member functions (TComPatternParam)
-// ====================================================================================================================
-
-/** 
- \param  piTexture     pixel data
- \param  iRoiWidth     pattern width
- \param  iRoiHeight    pattern height
- \param  iStride       buffer stride
- \param  bitDepth      bit depth
- */
-Void TComPatternParam::setPatternParamPel ( Pel* piTexture,
-                                           Int iRoiWidth,
-                                           Int iRoiHeight,
-                                           Int iStride,
-                                           Int bitDepth
-                                           )
-{
-  m_piROIOrigin    = piTexture;
-  m_iROIWidth      = iRoiWidth;
-  m_iROIHeight     = iRoiHeight;
-  m_iPatternStride = iStride;
-  m_bitDepth       = bitDepth;
-}
-
-// ====================================================================================================================
 // Public member functions (TComPattern)
 // ====================================================================================================================
 
+#if MCTS_ENC_CHECK
+Void TComPattern::initPattern(Pel* piY,
+                              Int roiWidth,
+                              Int roiHeight,
+                              Int stride,
+                              Int bitDepthLuma,
+                              Int roiPosX,
+                              Int roiPosY)
+#else
 Void TComPattern::initPattern (Pel* piY,
-                               Int iRoiWidth,
-                               Int iRoiHeight,
-                               Int iStride,
+                               Int roiWidth,
+                               Int roiHeight,
+                               Int stride,
                                Int bitDepthLuma)
-{
-  m_cPatternY. setPatternParamPel( piY,  iRoiWidth, iRoiHeight, iStride, bitDepthLuma);
-}
+#endif
+{
+  m_piROIOrigin = piY;
+  m_roiWidth = roiWidth;
+  m_roiHeight = roiHeight;
+  m_patternStride = stride;
+  m_bitDepth = bitDepthLuma;
+#if MCTS_ENC_CHECK
+  m_roiPosX       = roiPosX;
+  m_roiPosY       = roiPosY;
+#endif
+}
+
+#if MCTS_ENC_CHECK
+Void TComPattern::setTileBorders(Int tileLeftTopPelPosX, Int tileLeftTopPelPosY, Int tileRightBottomPelPosX, Int tileRightBottomPelPosY)
+{
+  m_tileLeftTopPelPosX = tileLeftTopPelPosX;
+  m_tileLeftTopPelPosY = tileLeftTopPelPosY;
+  m_tileRightBottomPelPosX = tileRightBottomPelPosX;
+  m_tileRightBottomPelPosY = tileRightBottomPelPosY;
+}
+#endif
 
 
Index: /trunk/source/Lib/TLibCommon/TComPattern.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPattern.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComPattern.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -52,63 +52,75 @@
 class TComTU;
 
-/// neighbouring pixel access class for one component
-class TComPatternParam
+/// neighbouring pixel access class for all components
+class TComPattern
 {
 private:
   Pel*  m_piROIOrigin;
+  Int   m_roiWidth;
+  Int   m_roiHeight;
+  Int   m_patternStride;
+  Int   m_bitDepth;
+
+#if MCTS_ENC_CHECK  
+  Int   m_roiPosX;
+  Int   m_roiPosY;
+  Int   m_tileLeftTopPelPosX;
+  Int   m_tileLeftTopPelPosY;
+  Int   m_tileRightBottomPelPosX;
+  Int   m_tileRightBottomPelPosY;
+#endif
 
 public:
-  Int   m_iROIWidth;
-  Int   m_iROIHeight;
-  Int   m_iPatternStride;
-  Int   m_bitDepth;
+  // ROI & pattern information, (ROI = &pattern[AboveOffset][LeftOffset])
+  Int   getROIYWidth() const      { return m_roiWidth;       }
+  Int   getROIYHeight() const     { return m_roiHeight;      }
+  Int   getPatternLStride() const { return m_patternStride;  }
+  Int   getBitDepthY() const      { return m_bitDepth;       }
+#if MCTS_ENC_CHECK
+  Int   getROIYPosX() const       { return m_roiPosX; }
+  Int   getROIYPosY() const       { return m_roiPosY; }
 
-  /// return starting position of ROI (ROI = &pattern[AboveOffset][LeftOffset])
-  __inline Pel*  getROIOrigin()
+  Int   getTileLeftTopPelPosX() const { return m_tileLeftTopPelPosX; }
+  Int   getTileLeftTopPelPosY() const { return m_tileLeftTopPelPosY; }
+  Int   getTileRightBottomPelPosX() const { return m_tileRightBottomPelPosX; }
+  Int   getTileRightBottomPelPosY() const { return m_tileRightBottomPelPosY; }
+#endif
+
+  __inline Pel*  getROIY()
   {
     return  m_piROIOrigin;
   }
-  __inline const Pel*  getROIOrigin() const
+  __inline const Pel*  getROIY() const
   {
     return  m_piROIOrigin;
   }
 
-  /// set parameters from Pel buffer for accessing neighbouring pixels
-  Void setPatternParamPel( Pel* piTexture, Int iRoiWidth, Int iRoiHeight, Int iStride, Int bitDepth );
-};
+#if NH_3D
+  Bool              m_bICFlag;
+  Bool              m_bSDCMRSADFlag;
 
-/// neighbouring pixel access class for all components
-class TComPattern
-{
-private:
-  TComPatternParam  m_cPatternY;
-//  TComPatternParam  m_cPatternCb;
-  //TComPatternParam  m_cPatternCr;
-#if NH_3D_IC
-  Bool              m_bICFlag;
-#endif
-#if NH_3D_SDC_INTER
-  Bool              m_bSDCMRSADFlag;
+  Bool  getICFlag()               const { return m_bICFlag; }
+  Void  setICFlag( Bool bICFlag ) { m_bICFlag = bICFlag; }
+  Bool  getSDCMRSADFlag()         const { return m_bSDCMRSADFlag; }
+  Void  setSDCMRSADFlag( Bool bSDCMRSADFlag )    { m_bSDCMRSADFlag = bSDCMRSADFlag; }
 #endif
 
 
-public:
+  TComPattern()
+  : m_piROIOrigin(NULL)
+  , m_roiWidth(0)
+  , m_roiHeight(0)
+  , m_patternStride(0)
+  , m_bitDepth(0)
+#if MCTS_ENC_CHECK
+  , m_roiPosX(0)
+  , m_roiPosY(0)
+  , m_tileLeftTopPelPosX(0)
+  , m_tileLeftTopPelPosY(0)
+  , m_tileRightBottomPelPosX(0)
+  , m_tileRightBottomPelPosY(0)
+#endif
+  {};
 
-  // ROI & pattern information, (ROI = &pattern[AboveOffset][LeftOffset])
-  Pel*  getROIY()                 { return m_cPatternY.getROIOrigin();    }
-  const Pel*  getROIY() const     { return m_cPatternY.getROIOrigin();    }
-  Int   getROIYWidth() const      { return m_cPatternY.m_iROIWidth;       }
-  Int   getROIYHeight() const     { return m_cPatternY.m_iROIHeight;      }
-  Int   getPatternLStride() const { return m_cPatternY.m_iPatternStride;  }
-  Int   getBitDepthY() const      { return m_cPatternY.m_bitDepth;        }
-
-#if NH_3D_IC
-  Bool  getICFlag()               const { return m_bICFlag; }
-  Void  setICFlag( Bool bICFlag ) { m_bICFlag = bICFlag; }
-#endif
-#if NH_3D_SDC_INTER
-  Bool  getSDCMRSADFlag()         const { return m_bSDCMRSADFlag; }
-  Void  setSDCMRSADFlag( Bool bSDCMRSADFlag )    { m_bSDCMRSADFlag = bSDCMRSADFlag; }
-#endif
 
   // -------------------------------------------------------------------------------------------------------------------
@@ -117,5 +129,10 @@
 
   /// set parameters from Pel buffers for accessing neighbouring pixels
-  Void initPattern( Pel* piY, Int iRoiWidth, Int iRoiHeight, Int iStride, Int bitDepthLuma );
+#if MCTS_ENC_CHECK
+  Void initPattern(Pel* piY, Int roiWidth, Int roiHeight, Int stride, Int bitDepthLuma, Int roiPosX, Int roiPosY);
+  Void setTileBorders(Int tileLeftTopPelPosX, Int tileLeftTopPelPosY, Int tileRightBottomPelPosX, Int tileRightBottomPelPosY);
+#else
+  Void initPattern(Pel* piY, Int roiWidth, Int roiHeight, Int stride, Int bitDepthLuma);
+#endif
 };
 
Index: /trunk/source/Lib/TLibCommon/TComPic.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPic.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComPic.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -73,8 +73,6 @@
     m_apcPicYuv[i]      = NULL;
   }
-#if NH_3D_QTLPC
+#if NH_3D
   m_bReduceBitsQTL    = 0;
-#endif
-#if NH_3D_NBDV
   m_iNumDdvCandPics   = 0;
   m_eRapRefList       = REF_PIC_LIST_0;
@@ -100,5 +98,9 @@
 }
 
+#if REDUCED_ENCODER_MEMORY
+Void TComPic::create( const TComSPS &sps, const TComPPS &pps, const Bool bCreateEncoderSourcePicYuv, const Bool bCreateForImmediateReconstruction )
+#else
 Void TComPic::create( const TComSPS &sps, const TComPPS &pps, const Bool bIsVirtual)
+#endif
 {
   destroy();
@@ -111,11 +113,23 @@
   const UInt         uiMaxDepth      = sps.getMaxTotalCUDepth();
 
+#if REDUCED_ENCODER_MEMORY
+  m_picSym.create( sps, pps, uiMaxDepth, bCreateForImmediateReconstruction );
+  if (bCreateEncoderSourcePicYuv)
+#else
   m_picSym.create( sps, pps, uiMaxDepth );
   if (!bIsVirtual)
+#endif
   {
     m_apcPicYuv[PIC_YUV_ORG    ]   = new TComPicYuv;  m_apcPicYuv[PIC_YUV_ORG     ]->create( iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true );
     m_apcPicYuv[PIC_YUV_TRUE_ORG]  = new TComPicYuv;  m_apcPicYuv[PIC_YUV_TRUE_ORG]->create( iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true );
   }
+#if REDUCED_ENCODER_MEMORY
+  if (bCreateForImmediateReconstruction)
+  {
+#endif
   m_apcPicYuv[PIC_YUV_REC]  = new TComPicYuv;  m_apcPicYuv[PIC_YUV_REC]->create( iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true );
+#if REDUCED_ENCODER_MEMORY
+  }
+#endif
 
   // there are no SEI messages associated with this picture initially
@@ -125,17 +139,82 @@
   }
   m_bUsedByCurr = false;
-
-#if H_3D_FCO
-/* initialize the texture to depth reference status */
-  for (int j=0; j<2; j++)
-  {
-      for (int i=0; i<MAX_NUM_REF; i++)
-      {
-          m_aiTexToDepRef[j][i] = -1;
-      }
-  }
-#endif
-
-}
+}
+
+#if REDUCED_ENCODER_MEMORY
+Void TComPic::prepareForEncoderSourcePicYuv()
+{
+  const TComSPS &sps=m_picSym.getSPS();
+
+  const ChromaFormat chromaFormatIDC = sps.getChromaFormatIdc();
+  const Int          iWidth          = sps.getPicWidthInLumaSamples();
+  const Int          iHeight         = sps.getPicHeightInLumaSamples();
+  const UInt         uiMaxCuWidth    = sps.getMaxCUWidth();
+  const UInt         uiMaxCuHeight   = sps.getMaxCUHeight();
+  const UInt         uiMaxDepth      = sps.getMaxTotalCUDepth();
+
+  if (m_apcPicYuv[PIC_YUV_ORG    ]==NULL)
+  {
+    m_apcPicYuv[PIC_YUV_ORG    ]   = new TComPicYuv;  m_apcPicYuv[PIC_YUV_ORG     ]->create( iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true );
+  }
+  if (m_apcPicYuv[PIC_YUV_TRUE_ORG    ]==NULL)
+  {
+    m_apcPicYuv[PIC_YUV_TRUE_ORG]  = new TComPicYuv;  m_apcPicYuv[PIC_YUV_TRUE_ORG]->create( iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true );
+  }
+}
+
+Void TComPic::prepareForReconstruction()
+{
+  if (m_apcPicYuv[PIC_YUV_REC] == NULL)
+  {
+    const TComSPS &sps=m_picSym.getSPS();
+    const ChromaFormat chromaFormatIDC = sps.getChromaFormatIdc();
+    const Int          iWidth          = sps.getPicWidthInLumaSamples();
+    const Int          iHeight         = sps.getPicHeightInLumaSamples();
+    const UInt         uiMaxCuWidth    = sps.getMaxCUWidth();
+    const UInt         uiMaxCuHeight   = sps.getMaxCUHeight();
+    const UInt         uiMaxDepth      = sps.getMaxTotalCUDepth();
+
+    m_apcPicYuv[PIC_YUV_REC]  = new TComPicYuv;  m_apcPicYuv[PIC_YUV_REC]->create( iWidth, iHeight, chromaFormatIDC, uiMaxCuWidth, uiMaxCuHeight, uiMaxDepth, true );
+  }
+
+  // mark it should be extended
+  m_apcPicYuv[PIC_YUV_REC]->setBorderExtension(false);
+
+  m_picSym.prepareForReconstruction();
+}
+
+Void TComPic::releaseReconstructionIntermediateData()
+{
+  m_picSym.releaseReconstructionIntermediateData();
+}
+
+Void TComPic::releaseEncoderSourceImageData()
+{
+  if (m_apcPicYuv[PIC_YUV_ORG    ])
+  {
+    m_apcPicYuv[PIC_YUV_ORG]->destroy();
+    delete m_apcPicYuv[PIC_YUV_ORG];
+    m_apcPicYuv[PIC_YUV_ORG] = NULL;
+  }
+  if (m_apcPicYuv[PIC_YUV_TRUE_ORG    ])
+  {
+    m_apcPicYuv[PIC_YUV_TRUE_ORG]->destroy();
+    delete m_apcPicYuv[PIC_YUV_TRUE_ORG];
+    m_apcPicYuv[PIC_YUV_TRUE_ORG] = NULL;
+  }
+}
+
+Void TComPic::releaseAllReconstructionData()
+{
+  if (m_apcPicYuv[PIC_YUV_REC    ])
+  {
+    m_apcPicYuv[PIC_YUV_REC]->destroy();
+    delete m_apcPicYuv[PIC_YUV_REC];
+    m_apcPicYuv[PIC_YUV_REC] = NULL;
+  }
+  m_picSym.releaseAllReconstructionData();
+}
+#endif
+
 
 Void TComPic::destroy()
@@ -156,5 +235,4 @@
 }
 #if NH_3D
-#if NH_3D_ARP
 Void TComPic::getCUAddrAndPartIdx( Int iX, Int iY, Int& riCuAddr, Int& riAbsZorderIdx )
 {
@@ -180,5 +258,4 @@
   riAbsZorderIdx      = g_auiRasterToZscan[ iRastPartIdx ];
 }
-#endif
 Void TComPic::compressMotion(Int scale)
 #else
@@ -343,5 +420,4 @@
 }
 
-#if NH_3D_NBDV 
 Int TComPic::getDisCandRefPictures(Int iColPOC)
 {
@@ -486,32 +562,25 @@
   TComSlice* pcCurrSlice = getSlice(getCurrSliceIdx());
   TComPic* pcTextPic = pcCurrSlice->getIvPic(0, getViewIndex());
-#if H_3D_FCO
-  if ( pcTextPic )
-  {
-#endif
-    TComSlice* pcTextSlice = pcTextPic->getSlice(0); // currently only support single slice
-
-    for(Int iTextRefDir = 0; (iTextRefDir < (pcTextSlice->isInterB() ? 2 :1) ) && !pcTextSlice->isIntra(); iTextRefDir++)
-    {
-      for(Int iTextRefIdx =0; iTextRefIdx < pcTextSlice->getNumRefIdx((RefPicList)iTextRefDir); iTextRefIdx++)
-      {
-        Int iTextRefPOC    = pcTextSlice->getRefPOC((RefPicList)iTextRefDir, iTextRefIdx);
-        Int iTextRefViewId = pcTextSlice->getRefPic((RefPicList)iTextRefDir, iTextRefIdx)->getViewIndex();
-        m_aiTexToDepRef[iTextRefDir][iTextRefIdx] = -1;
-        Int iCurrRefDir = iTextRefDir;
-
-        for(Int iCurrRefIdx = 0; (iCurrRefIdx<pcCurrSlice->getNumRefIdx((RefPicList)iCurrRefDir)) && (m_aiTexToDepRef[iTextRefDir][iTextRefIdx] < 0); iCurrRefIdx++)
-        {
-          if(pcCurrSlice->getRefPOC((RefPicList)iCurrRefDir, iCurrRefIdx ) == iTextRefPOC && 
-            pcCurrSlice->getRefPic((RefPicList)iCurrRefDir, iCurrRefIdx)->getViewIndex() == iTextRefViewId)
-          {  
-            m_aiTexToDepRef[iTextRefDir][iTextRefIdx] = iCurrRefIdx;            
-          }
+  TComSlice* pcTextSlice = pcTextPic->getSlice(0); // currently only support single slice
+
+  for(Int iTextRefDir = 0; (iTextRefDir < (pcTextSlice->isInterB() ? 2 :1) ) && !pcTextSlice->isIntra(); iTextRefDir++)
+  {
+    for(Int iTextRefIdx =0; iTextRefIdx < pcTextSlice->getNumRefIdx((RefPicList)iTextRefDir); iTextRefIdx++)
+    {
+      Int iTextRefPOC    = pcTextSlice->getRefPOC((RefPicList)iTextRefDir, iTextRefIdx);
+      Int iTextRefViewId = pcTextSlice->getRefPic((RefPicList)iTextRefDir, iTextRefIdx)->getViewIndex();
+      m_aiTexToDepRef[iTextRefDir][iTextRefIdx] = -1;
+      Int iCurrRefDir = iTextRefDir;
+
+      for(Int iCurrRefIdx = 0; (iCurrRefIdx<pcCurrSlice->getNumRefIdx((RefPicList)iCurrRefDir)) && (m_aiTexToDepRef[iTextRefDir][iTextRefIdx] < 0); iCurrRefIdx++)
+      {
+        if(pcCurrSlice->getRefPOC((RefPicList)iCurrRefDir, iCurrRefIdx ) == iTextRefPOC && 
+          pcCurrSlice->getRefPic((RefPicList)iCurrRefDir, iCurrRefIdx)->getViewIndex() == iTextRefViewId)
+        {  
+          m_aiTexToDepRef[iTextRefDir][iTextRefIdx] = iCurrRefIdx;            
         }
       }
     }
-#if H_3D_FCO
-  }
-#endif
+  }
 }
 
@@ -520,5 +589,5 @@
   return m_aiTexToDepRef[iTextRefDir][iTextRefIdx];
 }
-#endif
+
 #endif
 
Index: /trunk/source/Lib/TLibCommon/TComPic.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPic.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComPic.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -159,8 +159,6 @@
   Int**                 m_aaiCodedScale;
   Int**                 m_aaiCodedOffset;
-#if NH_3D_QTLPC
+#if NH_3D
   Bool                  m_bReduceBitsQTL;
-#endif
-#if NH_3D_NBDV
   UInt                   m_uiRapRefIdx;
   RefPicList             m_eRapRefList;
@@ -174,5 +172,14 @@
   virtual ~TComPic();
 
+#if REDUCED_ENCODER_MEMORY
+  Void          create( const TComSPS &sps, const TComPPS &pps, const Bool bCreateEncoderSourcePicYuv, const Bool bCreateForImmediateReconstruction );
+  Void          prepareForEncoderSourcePicYuv();
+  Void          prepareForReconstruction();
+  Void          releaseReconstructionIntermediateData();
+  Void          releaseAllReconstructionData();
+  Void          releaseEncoderSourceImageData();
+#else
   Void          create( const TComSPS &sps, const TComPPS &pps, const Bool bIsVirtual /*= false*/ );
+#endif
 
   virtual Void  destroy();
@@ -245,5 +252,5 @@
    Bool              isTopField()                         {return m_isTop;}
    Void              setField(Bool b)                     {m_isField = b;}
-   Bool              isField()                            {return m_isField;}
+   Bool              isField() const                      {return m_isField;}
 
 #if NH_MV
@@ -325,12 +332,8 @@
    Void          compressMotion(Int scale); 
    Void          printMotion( );
-#if NH_3D_ARP
+#if NH_3D
    Void          getCUAddrAndPartIdx( Int iX, Int iY, Int& riCuAddr, Int& riAbsZorderIdx );
-#endif
-#if NH_3D_QTLPC
    Bool          getReduceBitsFlag ()                     { return m_bReduceBitsQTL;     }
    Void          setReduceBitsFlag ( Bool bFlag )         { m_bReduceBitsQTL = bFlag;    }
-#endif
-#if NH_3D_NBDV
   Int            getNumDdvCandPics()                      { return m_iNumDdvCandPics;    }
   Int            getDisCandRefPictures(Int iColPOC);        
Index: /trunk/source/Lib/TLibCommon/TComPicSym.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPicSym.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComPicSym.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -64,4 +64,7 @@
 ,m_puiTileIdxMap(NULL)
 ,m_ctuRsToTsAddrMap(NULL)
+#if REDUCED_ENCODER_MEMORY
+,m_dpbPerCtuData(NULL)
+#endif
 ,m_saoBlkParams(NULL)
 #if ADAPTIVE_QP_SELECTION
@@ -77,10 +80,18 @@
 
 
+#if REDUCED_ENCODER_MEMORY
+Void TComPicSym::create  ( const TComSPS &sps, const TComPPS &pps, UInt uiMaxDepth, const Bool bAllocateCtuArray )
+#else
 Void TComPicSym::create  ( const TComSPS &sps, const TComPPS &pps, UInt uiMaxDepth )
-{
+#endif
+{
+  destroy();
+
   m_sps = sps;
   m_pps = pps;
 
+#if !REDUCED_ENCODER_MEMORY
   const ChromaFormat chromaFormatIDC = sps.getChromaFormatIdc();
+#endif
   const Int iPicWidth      = sps.getPicWidthInLumaSamples();
   const Int iPicHeight     = sps.getPicHeightInLumaSamples();
@@ -101,5 +112,9 @@
 
   m_numCtusInFrame     = m_frameWidthInCtus * m_frameHeightInCtus;
+#if REDUCED_ENCODER_MEMORY
+  m_pictureCtuArray    = NULL;
+#else
   m_pictureCtuArray    = new TComDataCU*[m_numCtusInFrame];
+#endif
 
   clearSliceBuffer();
@@ -113,4 +128,10 @@
 #endif
 
+#if REDUCED_ENCODER_MEMORY
+  if (bAllocateCtuArray)
+  {
+    prepareForReconstruction();
+  }
+#else
   for (UInt i=0; i<m_numCtusInFrame ; i++ )
   {
@@ -122,4 +143,5 @@
       );
   }
+#endif
 
   m_ctuTsToRsAddrMap = new UInt[m_numCtusInFrame+1];
@@ -141,8 +163,88 @@
 }
 
+#if REDUCED_ENCODER_MEMORY
+Void TComPicSym::prepareForReconstruction()
+{
+  const ChromaFormat chromaFormatIDC = m_sps.getChromaFormatIdc();
+  const UInt uiMaxCuWidth  = m_sps.getMaxCUWidth();
+  const UInt uiMaxCuHeight = m_sps.getMaxCUHeight();
+  if (m_pictureCtuArray == NULL)
+  {
+    m_pictureCtuArray = new TComDataCU*[m_numCtusInFrame];
+
+    for (UInt i=0; i<m_numCtusInFrame ; i++ )
+    {
+      m_pictureCtuArray[i] = new TComDataCU;
+      m_pictureCtuArray[i]->create( chromaFormatIDC, m_numPartitionsInCtu, uiMaxCuWidth, uiMaxCuHeight, false, uiMaxCuWidth >> m_uhTotalDepth
+#if ADAPTIVE_QP_SELECTION
+        , m_pParentARLBuffer
+#endif
+        );
+    }
+  }
+  if (m_dpbPerCtuData == NULL)
+  {
+    m_dpbPerCtuData = new DPBPerCtuData[m_numCtusInFrame];
+    for(UInt i=0; i<m_numCtusInFrame; i++)
+    {
+      for(Int j=0; j<NUM_REF_PIC_LIST_01; j++)
+      {
+        m_dpbPerCtuData[i].m_CUMvField[j].create( m_numPartitionsInCtu );
+      }
+      m_dpbPerCtuData[i].m_pePredMode = new SChar[m_numPartitionsInCtu];
+      memset(m_dpbPerCtuData[i].m_pePredMode, NUMBER_OF_PREDICTION_MODES, m_numPartitionsInCtu);
+      m_dpbPerCtuData[i].m_pePartSize = new SChar[m_numPartitionsInCtu];
+      memset(m_dpbPerCtuData[i].m_pePartSize, NUMBER_OF_PART_SIZES, m_numPartitionsInCtu);
+      m_dpbPerCtuData[i].m_pSlice=NULL;
+    }
+  }
+}
+
+Void TComPicSym::releaseReconstructionIntermediateData()
+{
+  if (m_pictureCtuArray)
+  {
+    for (Int i = 0; i < m_numCtusInFrame; i++)
+    {
+      if (m_pictureCtuArray[i])
+      {
+        m_pictureCtuArray[i]->destroy();
+        delete m_pictureCtuArray[i];
+        m_pictureCtuArray[i] = NULL;
+      }
+    }
+    delete [] m_pictureCtuArray;
+    m_pictureCtuArray = NULL;
+  }
+}
+
+Void TComPicSym::releaseAllReconstructionData()
+{
+  releaseReconstructionIntermediateData();
+
+  if (m_dpbPerCtuData != NULL)
+  {
+    for(UInt i=0; i<m_numCtusInFrame; i++)
+    {
+      for(Int j=0; j<NUM_REF_PIC_LIST_01; j++)
+      {
+        m_dpbPerCtuData[i].m_CUMvField[j].destroy();
+      }
+      delete [] m_dpbPerCtuData[i].m_pePredMode;
+      delete [] m_dpbPerCtuData[i].m_pePartSize;
+    }
+    delete [] m_dpbPerCtuData;
+    m_dpbPerCtuData=NULL;
+  }
+}
+#endif
+
 Void TComPicSym::destroy()
 {
   clearSliceBuffer();
 
+#if REDUCED_ENCODER_MEMORY
+  releaseAllReconstructionData();
+#else
   if (m_pictureCtuArray)
   {
@@ -159,4 +261,5 @@
   m_pictureCtuArray = NULL;
   }
+#endif
 
   delete [] m_ctuTsToRsAddrMap;
@@ -497,3 +600,21 @@
 {
 }
+
+#if MCTS_ENC_CHECK
+
+Void getTilePosition(const TComDataCU* const pcCU, UInt &tileXPosInCtus, UInt &tileYPosInCtus, UInt &tileWidthtInCtus, UInt &tileHeightInCtus)
+{
+  const UInt       currentTileIdx = pcCU->getPic()->getPicSym()->getTileIdxMap(pcCU->getCtuRsAddr());
+  const TComTile    *pCurrentTile = pcCU->getPic()->getPicSym()->getTComTile(currentTileIdx);
+  const UInt     frameWidthInCtus = pcCU->getPic()->getPicSym()->getFrameWidthInCtus();
+  const UInt firstCtuRsAddrOfTile = pcCU->getPic()->getPicSym()->getTComTile(pcCU->getPic()->getPicSym()->getTileIdxMap(pcCU->getCtuRsAddr()))->getFirstCtuRsAddr();
+
+  tileXPosInCtus = firstCtuRsAddrOfTile % frameWidthInCtus;
+  tileYPosInCtus = firstCtuRsAddrOfTile / frameWidthInCtus;
+  tileWidthtInCtus = pCurrentTile->getTileWidthInCtus();
+  tileHeightInCtus = pCurrentTile->getTileHeightInCtus();
+}
+
+#endif
+
 //! \}
Index: /trunk/source/Lib/TLibCommon/TComPicSym.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPicSym.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComPicSym.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -106,4 +106,22 @@
   UInt*         m_ctuRsToTsAddrMap;    ///< for a given RS (Raster-Scan) address, returns the TS (Tile-Scan; coding order) address. cf CtbAddrRsToTs in specification.
 
+#if REDUCED_ENCODER_MEMORY
+public:
+  struct DPBPerCtuData
+  {
+    Bool isInter(const UInt absPartAddr)                const { return m_pePredMode[absPartAddr] == MODE_INTER; }
+    PartSize getPartitionSize( const UInt absPartAddr ) const { return static_cast<PartSize>( m_pePartSize[absPartAddr] ); }
+    const TComCUMvField* getCUMvField ( RefPicList e )  const { return &m_CUMvField[e];                  }
+    const TComSlice* getSlice()                         const { return m_pSlice; }
+
+    SChar        * m_pePredMode;
+    SChar        * m_pePartSize;
+    TComCUMvField  m_CUMvField[NUM_REF_PIC_LIST_01];
+    TComSlice    * m_pSlice;
+  };
+
+private:
+  DPBPerCtuData *m_dpbPerCtuData;
+#endif
   SAOBlkParam  *m_saoBlkParams;
 #if ADAPTIVE_QP_SELECTION
@@ -121,5 +139,12 @@
 
 public:
+#if REDUCED_ENCODER_MEMORY
+  Void               create  ( const TComSPS &sps, const TComPPS &pps, UInt uiMaxDepth, const Bool bAllocateCtuArray );
+  Void               prepareForReconstruction();
+  Void               releaseReconstructionIntermediateData();
+  Void               releaseAllReconstructionData();
+#else
   Void               create  ( const TComSPS &sps, const TComPPS &pps, UInt uiMaxDepth );
+#endif
   Void               destroy ();
 
@@ -138,4 +163,9 @@
   const TComSPS&     getSPS()                 const                        { return m_sps; }
   const TComPPS&     getPPS()                 const                        { return m_pps; }
+#if REDUCED_ENCODER_MEMORY
+  Bool                 hasDPBPerCtuData() const                            { return (m_dpbPerCtuData!=0); };
+  DPBPerCtuData&       getDPBPerCtuData(UInt ctuRsAddr)                    { return m_dpbPerCtuData[ctuRsAddr]; }
+  const DPBPerCtuData& getDPBPerCtuData(UInt ctuRsAddr) const              { return m_dpbPerCtuData[ctuRsAddr]; }
+#endif
 
   TComSlice *        swapSliceObject(TComSlice* p, UInt i)                 { p->setSPS(&m_sps); p->setPPS(&m_pps); TComSlice *pTmp=m_apSlices[i];m_apSlices[i] = p; pTmp->setSPS(0); pTmp->setPPS(0); return pTmp; }
@@ -166,4 +196,8 @@
 //! \}
 
+#if MCTS_ENC_CHECK
+Void getTilePosition(const TComDataCU* const pcCU, UInt &tileXPosInCtus, UInt &tileYPosInCtus, UInt &tileWidthtInCtus, UInt &tileHeightInCtus);
+#endif
+
 #endif // __TCOMPICSYM__
 
Index: /trunk/source/Lib/TLibCommon/TComPicYuv.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComPicYuv.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -93,5 +93,5 @@
   m_picHeight         = picHeight;
 
-#if NH_3D_IV_MERGE
+#if NH_3D
   m_iCuWidth        = maxCUWidth;
   m_iCuHeight       = maxCUHeight;
@@ -141,5 +141,5 @@
   createWithoutCUInfo(picWidth, picHeight, chromaFormatIDC, bUseMargin, maxCUWidth, maxCUHeight);
 
-#if NH_3D_IV_MERGE
+#if NH_3D
   m_iBaseUnitWidth  = maxCUWidth  >> maxCUDepth;
   m_iBaseUnitHeight = maxCUHeight >> maxCUDepth;
@@ -350,5 +350,5 @@
   fclose(pFile);
 }
-#if NH_3D_IV_MERGE
+#if NH_3D
 Void
 TComPicYuv::getTopLeftSamplePos( Int iCuAddr, Int iAbsZorderIdx, Int& riX, Int& riY )
Index: /trunk/source/Lib/TLibCommon/TComPicYuv.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPicYuv.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComPicYuv.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -80,5 +80,5 @@
 
   Bool  m_bIsBorderExtended;
-#if NH_3D_IV_MERGE
+#if NH_3D
   Int   m_iBaseUnitWidth;       ///< Width of Base Unit (with maximum depth or minimum size, m_iCuWidth >> Max. Depth)
   Int   m_iBaseUnitHeight;      ///< Height of Base Unit (with maximum depth or minimum size, m_iCuHeight >> Max. Depth)
@@ -189,9 +189,7 @@
 #endif
 #if NH_3D
-#if NH_3D_IV_MERGE
   // sample to block and block to sample conversion
   Void  getTopLeftSamplePos( Int iCuAddr, Int iAbsZorderIdx, Int& riX, Int& riY );
   Void  getCUAddrAndPartIdx( Int iX, Int iY, Int& riCuAddr, Int& riAbsZorderIdx );
-#endif
 #endif
 
Index: /trunk/source/Lib/TLibCommon/TComPicYuvMD5.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComPicYuvMD5.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComPrediction.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPrediction.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComPrediction.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -82,5 +82,5 @@
     }
   }
-#if NH_3D_VSP
+#if NH_3D
   m_pDepthBlock = (Int*) malloc(MAX_NUM_PART_IDXS_IN_CTU_WIDTH*MAX_NUM_PART_IDXS_IN_CTU_WIDTH*sizeof(Int));
   if (m_pDepthBlock == NULL)
@@ -94,5 +94,5 @@
 TComPrediction::~TComPrediction()
 {
-#if NH_3D_VSP
+#if NH_3D
   if (m_pDepthBlock != NULL)
   {
@@ -123,5 +123,5 @@
   m_cYuvPredTemp.destroy();
 
-#if NH_3D_ARP
+#if NH_3D
   m_acYuvPredBase[0].destroy();
   m_acYuvPredBase[1].destroy();
@@ -182,14 +182,10 @@
 
     m_cYuvPredTemp.create( MAX_CU_SIZE, MAX_CU_SIZE, chromaFormatIDC );
-#if NH_3D_ARP
+#if NH_3D
     m_acYuvPredBase[0] .create( MAX_CU_SIZE, MAX_CU_SIZE, chromaFormatIDC );
     m_acYuvPredBase[1] .create( MAX_CU_SIZE, MAX_CU_SIZE, chromaFormatIDC );
-#endif
-#if NH_3D_VSP
-    m_cYuvDepthOnVsp.create( MAX_CU_SIZE, MAX_CU_SIZE, chromaFormatIDC );
-#endif
-
-  }
-
+    m_cYuvDepthOnVsp   .create( MAX_CU_SIZE, MAX_CU_SIZE, chromaFormatIDC );
+#endif
+  }
 
   if (m_iLumaRecStride != (MAX_CU_SIZE>>1) + 1)
@@ -201,5 +197,5 @@
     }
   }
-#if NH_3D_IC
+#if NH_3D
   m_uiaShift[0] = 0;
   for( Int i = 1; i < 64; i++ )
@@ -508,12 +504,10 @@
 }
 
-#if NH_3D_DMM
+#if NH_3D
 Void TComPrediction::predIntraLumaDmm( TComDataCU* pcCU, UInt uiAbsPartIdx, DmmID dmmType, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight )
 {
   assert( iWidth == iHeight  );
   assert( iWidth >= DMM_MIN_SIZE && iWidth <= DMM_MAX_SIZE );
-#if NH_3D_SDC_INTRA
   assert( !pcCU->getSDCFlag( uiAbsPartIdx ) );
-#endif
 
   // get partition
@@ -535,11 +529,6 @@
   Pel deltaDC1 = pcCU->getDmmDeltaDC( dmmType, 0, uiAbsPartIdx );
   Pel deltaDC2 = pcCU->getDmmDeltaDC( dmmType, 1, uiAbsPartIdx );
-#if NH_3D_DLT
   segDC1 = pcCU->getSlice()->getPPS()->getDLT()->idx2DepthValue( pcCU->getSlice()->getLayerIdInVps(), pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), predDC1 ) + deltaDC1 );
   segDC2 = pcCU->getSlice()->getPPS()->getDLT()->idx2DepthValue( pcCU->getSlice()->getLayerIdInVps(), pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), predDC2 ) + deltaDC2 );
-#else
-  segDC1 = ClipBD( predDC1 + deltaDC1, pcCU->getSlice()->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) );
-  segDC2 = ClipBD( predDC2 + deltaDC2, pcCU->getSlice()->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) );
-#endif
 
   // set prediction signal
@@ -565,5 +554,5 @@
       Int layerIdL0 = pcCU->getSlice()->getRefPic(REF_PIC_LIST_0, pcCU->getCUMvField(REF_PIC_LIST_0)->getRefIdx(PartAddr))->getLayerId();
       Int layerIdL1 = pcCU->getSlice()->getRefPic(REF_PIC_LIST_1, pcCU->getCUMvField(REF_PIC_LIST_1)->getRefIdx(PartAddr))->getLayerId();
-#if NH_3D_ARP
+#if NH_3D
       if(!pcCU->getARPW(PartAddr) && RefPOCL0 == RefPOCL1 && layerIdL0 == layerIdL1 && pcCU->getCUMvField(REF_PIC_LIST_0)->getMv(PartAddr) == pcCU->getCUMvField(REF_PIC_LIST_1)->getMv(PartAddr))
 #else
@@ -581,5 +570,5 @@
 }
 
-#if NH_3D_SPIVMP
+#if NH_3D
 Void TComPrediction::xGetSubPUAddrAndMerge(TComDataCU* pcCU, UInt uiPartAddr, Int iSPWidth, Int iSPHeight, Int iNumSPInOneLine, Int iNumSP, UInt* uiMergedSPW, UInt* uiMergedSPH, UInt* uiSPAddr )
 {
@@ -590,10 +579,9 @@
     pcCU->getSPAbsPartIdx(uiPartAddr, iSPWidth, iSPHeight, i, iNumSPInOneLine, uiSPAddr[i]);
   }
-#if NH_3D_ARP
+
   if( pcCU->getARPW( uiPartAddr ) != 0 )
   {
     return;
   }
-#endif
 
   // horizontal sub-PU merge
@@ -667,7 +655,5 @@
   return true;
 }
-#endif
-
-#if NH_3D_DBBP
+
 PartSize TComPrediction::getPartitionSizeFromDepth(Pel* pDepthPels, UInt uiDepthStride, UInt uiSize, TComDataCU*& pcCU)
 {
@@ -1138,5 +1124,5 @@
   {
     pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iWidth, iHeight );
-#if NH_3D_VSP
+#if NH_3D
     if ( pcCU->getVSPFlag(uiPartAddr) == 0)
     {
@@ -1156,5 +1142,5 @@
      else
      {
-#if NH_3D_SPIVMP
+#if NH_3D
         if ( pcCU->getSPIVMPFlag(uiPartAddr)!=0)  
         {
@@ -1196,9 +1182,9 @@
             xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred );
           }
-#if NH_3D_SPIVMP
+#if NH_3D
         }
 #endif
       }
-#if NH_3D_VSP
+#if NH_3D
     }
     else
@@ -1221,5 +1207,5 @@
     pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iWidth, iHeight );
 
-#if NH_3D_VSP
+#if NH_3D
     if ( pcCU->getVSPFlag(uiPartAddr) == 0 )
     {
@@ -1239,5 +1225,5 @@
     else
     {
-#if NH_3D_SPIVMP
+#if NH_3D
       if (pcCU->getSPIVMPFlag(uiPartAddr)!=0)  
       {
@@ -1278,9 +1264,9 @@
           xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred );
         }
-#if NH_3D_SPIVMP
-      }
-#endif
-    }
-#if NH_3D_VSP
+#if NH_3D
+      }
+#endif
+    }
+#if NH_3D
     }
     else
@@ -1319,5 +1305,5 @@
   pcCU->checkMvVertRest(cMv, eRefPicList, iRefIdx );
 #endif
-#if NH_3D_ARP
+#if NH_3D
   if(  pcCU->getARPW( uiPartAddr ) > 0 )
   {
@@ -1338,21 +1324,18 @@
     {
       const ComponentID compID=ComponentID(comp);
-#if NH_3D_IC
+#if NH_3D
       Bool bICFlag = pcCU->getICFlag( uiPartAddr ) && ( pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getViewIndex() != pcCU->getSlice()->getViewIndex() ) && ( isLuma(compID) || (iWidth > 8) );
       xPredInterBlk(compID,  pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, pcYuvPred, bi, pcCU->getSlice()->getSPS()->getBitDepth(toChannelType(compID))
-#if NH_3D_ARP
-        , false
-#endif
-        , bICFlag );
+        , false, bICFlag );
 #else
       xPredInterBlk  (compID,  pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, pcYuvPred, bi, pcCU->getSlice()->getSPS()->getBitDepth(toChannelType(compID)) );
 #endif
     }
-#if NH_3D_ARP
-  }
-#endif
-}
-
-#if NH_3D_VSP
+#if NH_3D
+  }
+#endif
+}
+
+#if NH_3D
 Void TComPrediction::xPredInterUniVSP( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi )
 {
@@ -1399,5 +1382,5 @@
 #endif
 
-#if NH_3D_ARP
+#if NH_3D
 //temporal ARP
 Void TComPrediction::xPredInterUniARP( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi )
@@ -1409,11 +1392,8 @@
   TComPic* pcPicYuvBaseRef = NULL;
 
-#if NH_3D_NBDV
   DisInfo cDistparity;
   cDistparity.m_acNBDV = pcCU->getDvInfo(0).m_acNBDV;
   cDistparity.m_aVIdxCan = pcCU->getDvInfo(uiPartAddr).m_aVIdxCan;
-#else
-  assert(0); // ARP can be applied only when a DV is available
-#endif
+
   UChar dW = pcCU->getARPW ( uiPartAddr );
 
@@ -1777,5 +1757,5 @@
 }
 
-#if NH_3D_VSP
+#if NH_3D
 Void TComPrediction::xPredInterBiVSP( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv*& rpcYuvPred )
 {
@@ -1821,11 +1801,5 @@
 #if NH_3D
 Void TComPrediction::xPredInterBlk(const ComponentID compID, TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *dstPic, Bool bi, const Int bitDepth 
-#if NH_3D_ARP
-    , Bool filterType
-#endif
-#if NH_3D_IC
-    , Bool bICFlag
-#endif
-)
+    , Bool filterType , Bool bICFlag )
 #else
 Void TComPrediction::xPredInterBlk(const ComponentID compID, TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *dstPic, Bool bi, const Int bitDepth )
@@ -1849,5 +1823,5 @@
   Int     yFrac  = mv->getVer() & ((1<<shiftVer)-1);
 
-#if NH_3D_INTEGER_MV_DEPTH
+#if NH_3D
   if( cu->getSlice()->getIsDepth() )
   {
@@ -1868,12 +1842,5 @@
 #if NH_3D
     m_if.filterHor(compID, ref, refStride, dst,  dstStride, cxWidth, cxHeight, xFrac, !bi 
-#if NH_3D_IC
-     || bICFlag
-#endif
-    , chFmt, bitDepth
-#if NH_3D_ARP 
-    , filterType
-#endif 
-);
+     || bICFlag, chFmt, bitDepth, filterType );
 #else
     m_if.filterHor(compID, ref, refStride, dst,  dstStride, cxWidth, cxHeight, xFrac, !bi, chFmt, bitDepth );
@@ -1884,15 +1851,7 @@
 #if NH_3D
   m_if.filterVer(compID, ref, refStride, dst, dstStride, cxWidth, cxHeight, yFrac, true, !bi 
-#if NH_3D_IC
-    || bICFlag
-#endif
-    , chFmt, bitDepth
-#if NH_3D_ARP
-    , filterType
-#endif
-);
+    || bICFlag , chFmt, bitDepth , filterType );
 #else
     m_if.filterVer(compID, ref, refStride, dst, dstStride, cxWidth, cxHeight, yFrac, true, !bi, chFmt, bitDepth );
-
 #endif
   }
@@ -1904,5 +1863,5 @@
     const Int vFilterSize = isLuma(compID) ? NTAPS_LUMA : NTAPS_CHROMA;
 
-#if NH_3D_ARP 
+#if NH_3D
     m_if.filterHor(compID, ref - ((vFilterSize>>1) -1)*refStride, refStride, tmp, tmpStride, cxWidth, cxHeight+vFilterSize-1, xFrac, false,      chFmt, bitDepth, filterType );
 #else
@@ -1912,12 +1871,5 @@
 #if NH_3D
     m_if.filterVer(compID, tmp + ((vFilterSize>>1) -1)*tmpStride, tmpStride, dst, dstStride, cxWidth, cxHeight,               yFrac, false, !bi
-#if NH_3D_IC
-    || bICFlag
-#endif
-    , chFmt, bitDepth
-#if NH_3D_ARP
-    , filterType
-#endif 
-);
+    || bICFlag , chFmt, bitDepth , filterType );
 #else
     m_if.filterVer(compID, tmp + ((vFilterSize>>1) -1)*tmpStride, tmpStride, dst, dstStride, cxWidth, cxHeight,               yFrac, false, !bi, chFmt, bitDepth );
@@ -1925,5 +1877,5 @@
   }
 
-#if NH_3D_IC
+#if NH_3D
   if( bICFlag )
   {
@@ -2104,5 +2056,276 @@
           (uiDirMode==HOR_IDX || uiDirMode==VER_IDX);
 }
-#if NH_3D_IC
+
+
+#if MCTS_ENC_CHECK
+
+Void getRefPUPartPos(TComDataCU* pcCU, TComMv& cMv, Int uiPartIdx, Int& ruiPredXLeft, Int& ruiPredYTop, Int& ruiPredXRight, Int& ruiPredYBottom, Int iWidth, Int iHeight)
+{
+  ruiPredXLeft = pcCU->getCUPelX();
+  ruiPredYTop = pcCU->getCUPelY();
+
+  switch (pcCU->getPartitionSize(0))
+  {
+  case SIZE_2NxN:
+    if (uiPartIdx == 0)
+    {
+      ruiPredXRight = ruiPredXLeft + iWidth;
+      ruiPredYBottom = ruiPredYTop + iHeight;
+    }
+    else
+    {
+      ruiPredXRight = ruiPredXLeft + iWidth;
+      ruiPredYBottom = ruiPredYTop + (iHeight << 1);
+      ruiPredYTop += iHeight;
+    }
+    break;
+  case SIZE_Nx2N:
+    if (uiPartIdx == 0)
+    {
+      ruiPredXRight = ruiPredXLeft + iWidth;
+      ruiPredYBottom = ruiPredYTop + iHeight;
+    }
+    else
+    {
+      ruiPredXRight = ruiPredXLeft + (iWidth << 1);
+      ruiPredYBottom = ruiPredYTop + iHeight;
+      ruiPredXLeft += iWidth;
+    }
+    break;
+  case SIZE_NxN:
+    if (uiPartIdx == 0)
+    {
+      ruiPredXRight = ruiPredXLeft + iWidth;
+      ruiPredYBottom = ruiPredYTop + iHeight;
+    }
+    else if (uiPartIdx == 1)
+    {
+      ruiPredXRight = ruiPredXLeft + (iWidth << 1);
+      ruiPredYBottom = ruiPredYTop + iHeight;
+      ruiPredXLeft += iWidth;
+    }
+    else if (uiPartIdx == 2)
+    {
+      ruiPredXRight = ruiPredXLeft + iWidth;
+      ruiPredYBottom = ruiPredYTop + (iHeight << 1);
+      ruiPredYTop += iHeight;
+    }
+    else if (uiPartIdx == 3)
+    {
+      ruiPredXRight = ruiPredXLeft + (iWidth << 1);
+      ruiPredYBottom = ruiPredYTop + (iHeight << 1);
+      ruiPredXLeft += iWidth;
+      ruiPredYTop += iHeight;
+    }
+    break;
+  case SIZE_2NxnU:
+    if (uiPartIdx == 0)
+    {
+      ruiPredXRight = ruiPredXLeft + iWidth;
+      ruiPredYBottom = ruiPredYTop + iHeight;
+    }
+    else
+    {
+      ruiPredXRight = ruiPredXLeft + iWidth;
+      ruiPredYBottom = ruiPredYTop + pcCU->getHeight(0);
+      ruiPredYTop += (iHeight / 3);
+    }
+    break;
+  case SIZE_2NxnD:
+    if (uiPartIdx == 0)
+    {
+      ruiPredXRight = ruiPredXLeft + iWidth;
+      ruiPredYBottom = ruiPredYTop + iHeight;
+    }
+    else
+    {
+      Int oriHeight = iHeight << 2;
+      ruiPredXRight = ruiPredXLeft + iWidth;
+      ruiPredYBottom = ruiPredYTop + oriHeight;
+      ruiPredYTop += (oriHeight >> 2) + (oriHeight >> 1);
+    }
+    break;
+  case SIZE_nLx2N:
+    if (uiPartIdx == 0)
+    {
+      ruiPredXRight = ruiPredXLeft + iWidth;
+      ruiPredYBottom = ruiPredYTop + iHeight;
+    }
+    else
+    {
+      ruiPredXRight = ruiPredXLeft + pcCU->getWidth(0);
+      ruiPredYBottom = ruiPredYTop + iHeight;
+      ruiPredXLeft += (iWidth / 3);
+    }
+    break;
+  case SIZE_nRx2N:
+    if (uiPartIdx == 0)
+    {
+      ruiPredXRight = ruiPredXLeft + iWidth;
+      ruiPredYBottom = ruiPredYTop + iHeight;
+    }
+    else
+    {
+      Int oriWidth = (iWidth << 2);
+      ruiPredXRight = ruiPredXLeft + oriWidth;
+      ruiPredYBottom = ruiPredYTop + iHeight;
+      ruiPredXLeft += (oriWidth >> 2) + (oriWidth >> 1);
+    }
+    break;
+  default:
+    ruiPredXRight = ruiPredXLeft + iWidth;
+    ruiPredYBottom = ruiPredYTop + iHeight;
+    break;
+  }
+
+  ruiPredXLeft   += (cMv.getHor() >> 2);
+  ruiPredYTop    += (cMv.getVer() >> 2);
+  ruiPredXRight  += (cMv.getHor() >> 2) - 1;
+  ruiPredYBottom += (cMv.getVer() >> 2) - 1;
+}
+
+Bool checkMVPRange(TComMv& cMv, UInt ctuLength, UInt tileXPosInCtus, UInt tileYPosInCtus, UInt tileWidthtInCtus, UInt tileHeightInCtus, Int PredXLeft, Int PredXRight, Int PredYTop, Int PredYBottom, ChromaFormat chromaFormat)
+{
+  // filter length of sub-sample generation filter to be considered
+  const UInt LumaLTSampleOffset = 3;
+  const UInt LumaRBSampleOffset = 4;
+  const UInt CromaLTSampleoffset = 1;
+  const UInt CromaRBSampleoffset = 2;
+
+  // tile position in full pels
+  const Int leftTopPelPosX = ctuLength * tileXPosInCtus;
+  const Int leftTopPelPosY = ctuLength * tileYPosInCtus;
+  const Int rightBottomPelPosX = ((tileWidthtInCtus + tileXPosInCtus) * ctuLength) - 1;
+  const Int rightBottomPelPosY = ((tileHeightInCtus + tileYPosInCtus) * ctuLength) - 1;
+
+  // Luma MV range check
+  const Bool isFullPelHorLuma = (cMv.getHor() % 4 == 0);
+  const Bool isFullPelVerLuma = (cMv.getVer() % 4 == 0);
+
+  const Int lRangeXLeft = leftTopPelPosX + (isFullPelHorLuma ? 0 : LumaLTSampleOffset);
+  const Int lRangeYTop = leftTopPelPosY + (isFullPelVerLuma ? 0 : LumaLTSampleOffset);
+  const Int lRangeXRight = rightBottomPelPosX - (isFullPelHorLuma ? 0 : LumaRBSampleOffset);
+  const Int lRangeYBottom = rightBottomPelPosY - (isFullPelVerLuma ? 0 : LumaRBSampleOffset);
+
+  if (!(PredXLeft >= lRangeXLeft && PredXLeft <= lRangeXRight) || !(PredXRight >= lRangeXLeft && PredXRight <= lRangeXRight))
+  {
+    return false;
+  }
+  else if (!(PredYTop >= lRangeYTop && PredYTop <= lRangeYBottom) || !(PredYBottom >= lRangeYTop && PredYBottom <= lRangeYBottom))
+  {
+    return false;
+  }
+
+  if ((chromaFormat != CHROMA_444) && (chromaFormat != CHROMA_400))
+  {
+    // Chroma MV range check
+    const Bool isFullPelHorChroma = (cMv.getHor() % 8 == 0);
+    const Bool isFullPelVerChroma = (cMv.getVer() % 8 == 0);
+
+    const Int cRangeXLeft = leftTopPelPosX + (isFullPelHorChroma ? 0 : CromaLTSampleoffset);
+    const Int cRangeYTop = leftTopPelPosY + (isFullPelVerChroma ? 0 : CromaLTSampleoffset);
+    const Int cRangeXRight = rightBottomPelPosX - (isFullPelHorChroma ? 0 : CromaRBSampleoffset);
+    const Int cRangeYBottom = rightBottomPelPosY - (isFullPelVerChroma ? 0 : CromaRBSampleoffset);
+
+    if (!(PredXLeft >= cRangeXLeft && PredXLeft <= cRangeXRight) || !(PredXRight >= cRangeXLeft && PredXRight <= cRangeXRight))
+    {
+      return false;
+    }
+    else if ((!(PredYTop >= cRangeYTop && PredYTop <= cRangeYBottom) || !(PredYBottom >= cRangeYTop && PredYBottom <= cRangeYBottom)) && (chromaFormat != CHROMA_422))
+    {
+      return false;
+    }
+  }
+
+  return true;
+}
+
+Bool TComPrediction::checkTMctsMvp(TComDataCU* pcCU, Int partIdx)
+{
+  Int   partWidth  = 0;
+  Int   partHeight = 0;
+  UInt  partAddr   = 0;
+
+  UInt  tileXPosInCtus = 0;
+  UInt  tileYPosInCtus = 0;
+  UInt  tileWidthtInCtus = 0;
+  UInt  tileHeightInCtus = 0;
+  
+  getTilePosition(pcCU, tileXPosInCtus, tileYPosInCtus, tileWidthtInCtus, tileHeightInCtus);
+
+  const UInt            ctuLength = pcCU->getPic()->getPicSym()->getSPS().getMaxCUWidth();
+  const ChromaFormat chromaFormat = pcCU->getPic()->getPicSym()->getSPS().getChromaFormatIdc();
+
+  Int   predXLeft;
+  Int   predYTop;
+  Int   predXRight;
+  Int   predYBottom;
+
+  if (partIdx >= 0)
+  {
+    pcCU->getPartIndexAndSize(partIdx, partAddr, partWidth, partHeight);
+
+    if (xCheckIdenticalMotion(pcCU, partAddr))
+    {
+      RefPicList eRefPicList = REF_PIC_LIST_0;
+      TComMv      cMv = pcCU->getCUMvField(eRefPicList)->getMv(partAddr);
+      getRefPUPartPos(pcCU, cMv, partIdx, predXLeft, predYTop, predXRight, predYBottom, partWidth, partHeight);
+      if (!checkMVPRange(cMv, ctuLength, tileXPosInCtus, tileYPosInCtus, tileWidthtInCtus, tileHeightInCtus, predXLeft, predXRight, predYTop, predYBottom, chromaFormat))
+      {
+        return false;
+      }
+    }
+    else
+    {
+      for (UInt refList = 0; refList < NUM_REF_PIC_LIST_01; refList++)
+      {
+        RefPicList eRefPicList = (refList ? REF_PIC_LIST_1 : REF_PIC_LIST_0);
+
+        TComMv      cMv = pcCU->getCUMvField(eRefPicList)->getMv(partAddr);
+        getRefPUPartPos(pcCU, cMv, partIdx, predXLeft, predYTop, predXRight, predYBottom, partWidth, partHeight);
+        if (!checkMVPRange(cMv, ctuLength, tileXPosInCtus, tileYPosInCtus, tileWidthtInCtus, tileHeightInCtus, predXLeft, predXRight, predYTop, predYBottom, chromaFormat))
+        {
+          return false;
+        }
+      }
+    }
+    return true;
+  }
+
+  for (partIdx = 0; partIdx < pcCU->getNumPartitions(); partIdx++)
+  {
+    pcCU->getPartIndexAndSize(partIdx, partAddr, partWidth, partHeight);
+
+    if (xCheckIdenticalMotion(pcCU, partAddr))
+    {
+      RefPicList eRefPicList = REF_PIC_LIST_0;
+      TComMv      cMv = pcCU->getCUMvField(eRefPicList)->getMv(partAddr);
+      getRefPUPartPos(pcCU, cMv, partIdx, predXLeft, predYTop, predXRight, predYBottom, partWidth, partHeight);
+      if (!checkMVPRange(cMv, ctuLength, tileXPosInCtus, tileYPosInCtus, tileWidthtInCtus, tileHeightInCtus, predXLeft, predXRight, predYTop, predYBottom, chromaFormat))
+      {
+        return false;
+      }
+    }
+    else
+    {
+      for (UInt refList = 0; refList < NUM_REF_PIC_LIST_01; refList++)
+      {
+        RefPicList eRefPicList = (refList ? REF_PIC_LIST_1 : REF_PIC_LIST_0);
+
+        TComMv      cMv = pcCU->getCUMvField(eRefPicList)->getMv(partAddr);
+        getRefPUPartPos(pcCU, cMv, partIdx, predXLeft, predYTop, predXRight, predYBottom, partWidth, partHeight);
+        if (!checkMVPRange(cMv, ctuLength, tileXPosInCtus, tileYPosInCtus, tileWidthtInCtus, tileHeightInCtus, predXLeft, predXRight, predYTop, predYBottom, chromaFormat))
+        {
+          return false;
+        }
+      }
+    }
+  }
+  return true;
+}
+
+
+#endif
+#if NH_3D
 /** Function for deriving the position of first non-zero binary bit of a value
  * \param x input value
@@ -2130,5 +2353,4 @@
   return iMSB;
 }
-
 
 /** Function for deriving LM illumination compensation.
@@ -2252,6 +2474,5 @@
   }   
 #endif
-
-#if NH_3D_SDC_INTRA
+#if NH_3D
 Void TComPrediction::predConstantSDC( Pel* ptrSrc, UInt srcStride, UInt uiSize, Pel& predDC )
 {
@@ -2262,7 +2483,5 @@
   predDC = (*pLeftTop + *pRightTop + *pLeftBottom + *pRightBottom + 2)>>2;
 }
-#endif // NH_3D_SDC_INTRA
-
-#if NH_3D_DMM
+
 Void TComPrediction::predContourFromTex( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Bool* segPattern )
 {
Index: /trunk/source/Lib/TLibCommon/TComPrediction.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComPrediction.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComPrediction.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -45,5 +45,5 @@
 #include "TComWeightPrediction.h"
 
-#if NH_3D_ARP
+#if NH_3D
 #include "TComPic.h"
 #endif
@@ -80,5 +80,5 @@
   TComYuv   m_acYuvPred[NUM_REF_PIC_LIST_01];
   TComYuv   m_cYuvPredTemp;
-#if NH_3D_ARP
+#if NH_3D
   TComYuv   m_acYuvPredBase[2];
 #endif
@@ -90,9 +90,6 @@
   Pel*   m_pLumaRecBuffer;       ///< array for downsampled reconstructed luma sample
   Int    m_iLumaRecStride;       ///< stride of #m_pLumaRecBuffer array
-#if NH_3D_IC
+#if NH_3D
   UInt   m_uiaShift[ 64 ];       // Table for multiplication to substitue of division operation
-#endif
-
-#if NH_3D_VSP
   Int*    m_pDepthBlock;         ///< Store a depth block, local variable, to prevent memory allocation every time
   TComYuv m_cYuvDepthOnVsp;
@@ -102,5 +99,5 @@
 
   // motion compensation functions
-#if NH_3D_ARP
+#if NH_3D
   Void xPredInterUniARP         ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi );
   Void xPredInterUniARPviewRef  ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi );
@@ -110,22 +107,13 @@
   Void xPredInterUni            ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv* pcYuvPred, Bool bi=false          );
   Void xPredInterBi             ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight,                         TComYuv* pcYuvPred          );
-#if NH_3D_VSP
+#if NH_3D
   Void xPredInterUniVSP         ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi=false          );
   Void xPredInterBiVSP          ( TComDataCU* pcCU,                          UInt uiPartAddr,               Int iWidth, Int iHeight,                         TComYuv*& rpcYuvPred );
+  Void xPredInterBlk(const ComponentID compID, TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *dstPic, Bool bi, const Int bitDepth, Bool filterType = false, Bool bICFlag    = false );
+#else
+  Void xPredInterBlk(const ComponentID compID, TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *dstPic, Bool bi, const Int bitDepth );
 #endif
 
 #if NH_3D
-  Void xPredInterBlk(const ComponentID compID, TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *dstPic, Bool bi, const Int bitDepth
-#if NH_3D_ARP
-    , Bool filterType = false
-#endif
-#if NH_3D_IC
-    , Bool bICFlag    = false
-#endif
- );
-#else
-  Void xPredInterBlk(const ComponentID compID, TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *dstPic, Bool bi, const Int bitDepth );
-#endif
-#if NH_3D_VSP
   Void xPredInterUniSubPU        ( TComDataCU *cu, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi, Int widthSubPU=4, Int heightSubPU=4 );
 #endif
@@ -134,10 +122,10 @@
 
   Void xGetLLSPrediction ( const Pel* pSrc0, Int iSrcStride, Pel* pDst0, Int iDstStride, UInt uiWidth, UInt uiHeight, UInt uiExt0, const ChromaFormat chFmt  DEBUG_STRING_FN_DECLARE(sDebug) );
-#if NH_3D_IC
+#if NH_3D
   Void xGetLLSICPrediction( const ComponentID compID, TComDataCU* pcCU, TComMv *pMv, TComPicYuv *pRefPic, Int &a, Int &b, const Int bitDepth);
 #endif
   Void xDCPredFiltering( const Pel* pSrc, Int iSrcStride, Pel* pDst, Int iDstStride, Int iWidth, Int iHeight, ChannelType channelType );
   Bool xCheckIdenticalMotion    ( TComDataCU* pcCU, UInt PartAddr);
-#if NH_3D_SPIVMP
+#if NH_3D
   Bool xCheckTwoSPMotion ( TComDataCU* pcCU, UInt PartAddr0, UInt PartAddr1 );
   Void xGetSubPUAddrAndMerge(TComDataCU* pcCU, UInt uiPartAddr, Int iSPWidth, Int iSPHeight, Int iNumSPInOneLine, Int iNumSP, UInt* uiMergedSPW, UInt* uiMergedSPH, UInt* uiSPAddr );
@@ -164,20 +152,13 @@
 
   Pel  predIntraGetPredValDC      ( const Pel* pSrc, Int iSrcStride, UInt iWidth, UInt iHeight);
-#if NH_3D_DMM
+#if NH_3D
   Void predIntraLumaDmm           ( TComDataCU* pcCU, UInt uiAbsPartIdx, DmmID dmmType, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight );
   Void predContourFromTex         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Bool* segPattern );
   Void predBiSegDCs               ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Bool* biSegPattern, Int patternStride, Pel& predDC1, Pel& predDC2 );
   Void assignBiSegDCs             ( Pel* ptrDst, UInt dstStride, Bool* biSegPattern, Int patternStride, Pel valDC1, Pel valDC2 );
-#endif
-#if NH_3D_SDC_INTRA
   Void predConstantSDC            ( Pel* ptrSrc, UInt srcStride, UInt uiSize, Pel& predDC );
-#endif
-  
-#if NH_3D_DBBP
   PartSize      getPartitionSizeFromDepth(Pel* pDepthPels, UInt uiDepthStride, UInt uiSize, TComDataCU*& pcCU);
   Bool          getSegmentMaskFromDepth( Pel* pDepthPels, UInt uiDepthStride, UInt uiWidth, UInt uiHeight, Bool* pMask, TComDataCU*& pcCU);
   Void          combineSegmentsWithMask( TComYuv* pInYuv[2], TComYuv* pOutYuv, Bool* pMask, UInt uiWidth, UInt uiHeight, UInt uiPartAddr, UInt partSize, Int bitDepthY );
-#endif
-#if NH_3D
   Pel  predIntraGetPredValDC      ( const Pel* pSrc, Int iSrcStride, UInt iWidth, UInt iHeight, Bool bAbove, Bool bLeft );
 #endif
@@ -197,4 +178,8 @@
 
   static Bool UseDPCMForFirstPassIntraEstimation(TComTU &rTu, const UInt uiDirMode);
+
+#if MCTS_ENC_CHECK
+  Bool checkTMctsMvp(TComDataCU* pcCU, Int partIdx = -1);
+#endif
 };
 
Index: /trunk/source/Lib/TLibCommon/TComRdCost.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComRdCost.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComRdCost.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -41,4 +41,10 @@
 #include "TComRom.h"
 #include "TComRdCost.h"
+
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+#include <emmintrin.h>
+#include <xmmintrin.h>
+#endif
+
 #if NH_3D_VSO
 #include "TComDataCU.h"
@@ -208,5 +214,5 @@
   m_bUseEstimatedVSD        = false; 
 #endif
-#if NH_3D_DBBP
+#if NH_3D
   m_bUseMask                = false;
 #endif
@@ -237,5 +243,5 @@
   rcDistParam.DistFunc = m_afpDistortFunc[eDFunc + g_aucConvertToBit[ rcDistParam.iCols ] + 1 ];
 
-#if NH_3D_DBBP
+#if NH_3D
   if( m_bUseMask )
   {
@@ -298,5 +304,5 @@
   }
 
-#if NH_3D_DBBP
+#if NH_3D
   if( m_bUseMask )
   {
@@ -349,5 +355,5 @@
   }
 
-#if NH_3D_DBBP
+#if NH_3D
   if( m_bUseMask )
   {
@@ -372,5 +378,5 @@
   rcDP.DistFunc   = m_afpDistortFunc[ ( bHadamard ? DF_HADS : DF_SADS ) + g_aucConvertToBit[ iWidth ] + 1 ];
   rcDP.m_maximumDistortionForEarlyExit = std::numeric_limits<Distortion>::max();
-#if NH_3D_DBBP
+#if NH_3D
   if( m_bUseMask )
   {
@@ -391,5 +397,9 @@
       for ( x=0; x<iWidth; x+= 8 )
       {
-        uiSum += xCalcHADs8x8( &pi0[x], &pi1[x], iStride0, iStride1, 1 );
+        uiSum += xCalcHADs8x8( &pi0[x], &pi1[x], iStride0, iStride1, 1
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+          , bitDepth
+#endif
+          );
       }
       pi0 += iStride0*8;
@@ -415,5 +425,5 @@
 }
 
-#if NH_3D_ENC_DEPTH
+#if NH_3D
 UInt TComRdCost::calcVAR (Pel* pi0, Int stride, Int width, Int height, Int cuDepth, UInt maxCuWidth)
 { 
@@ -465,8 +475,6 @@
   cDtParam.bitDepth     = bitDepth;
 
-#if NH_3D_IC
+#if NH_3D
   cDtParam.bUseIC       = false;
-#endif
-#if NH_3D_SDC_INTER
   cDtParam.bUseSDCMRSAD = false;
 #endif
@@ -481,4 +489,161 @@
   }
 }
+
+// ====================================================================================================================
+// Distortion functions
+// ====================================================================================================================
+
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+inline Int simdSADLine4n16b( const Pel * piOrg , const Pel * piCur , Int nWidth )
+{
+  // internal bit-depth must be 12-bit or lower
+  assert( !( nWidth & 0x03 ) );
+  __m128i org , cur , abs , sum;
+  sum = _mm_setzero_si128();
+  for( Int n = 0 ; n < nWidth ; n += 4 )
+  {
+    org = _mm_loadl_epi64( ( __m128i* )( piOrg + n ) );
+    cur = _mm_loadl_epi64( ( __m128i* )( piCur + n ) );
+    abs = _mm_subs_epi16( _mm_max_epi16( org , cur )  , _mm_min_epi16( org , cur ) );
+    sum = _mm_adds_epu16( abs , sum );
+  }
+  __m128i zero =  _mm_setzero_si128();
+  sum = _mm_unpacklo_epi16( sum , zero );
+  sum = _mm_add_epi32( sum , _mm_shuffle_epi32( sum , _MM_SHUFFLE( 2 , 3 , 0 , 1 ) ) );
+  sum = _mm_add_epi32( sum , _mm_shuffle_epi32( sum , _MM_SHUFFLE( 1 , 0 , 3 , 2 ) ) );
+  return( _mm_cvtsi128_si32( sum ) );
+}
+
+inline Int simdSADLine8n16b( const Pel * piOrg , const Pel * piCur , Int nWidth )
+{
+  // internal bit-depth must be 12-bit or lower
+  assert( !( nWidth & 0x07 ) );
+  __m128i org , cur , abs , sum;
+  sum = _mm_setzero_si128();
+  for( Int n = 0 ; n < nWidth ; n += 8 )
+  {
+    org = _mm_loadu_si128( ( __m128i* )( piOrg + n ) );
+    cur = _mm_loadu_si128( ( __m128i* )( piCur + n ) );
+    abs = _mm_subs_epi16( _mm_max_epi16( org , cur )  , _mm_min_epi16( org , cur ) );
+    sum = _mm_adds_epu16( abs , sum );
+  }
+  __m128i zero =  _mm_setzero_si128();
+  __m128i hi = _mm_unpackhi_epi16( sum , zero );
+  __m128i lo = _mm_unpacklo_epi16( sum , zero );
+  sum = _mm_add_epi32( lo , hi );
+  sum = _mm_add_epi32( sum , _mm_shuffle_epi32( sum , _MM_SHUFFLE( 2 , 3 , 0 , 1 ) ) );
+  sum = _mm_add_epi32( sum , _mm_shuffle_epi32( sum , _MM_SHUFFLE( 1 , 0 , 3 , 2 ) ) );
+  return( _mm_cvtsi128_si32( sum ) );
+}
+
+inline Void simd8x8Transpose32b( __m128i * pBuffer )
+{
+  __m128 tmp[16];
+  for( Int n = 0 ; n < 16 ; n++ )
+  {
+    tmp[n] = _mm_castsi128_ps( pBuffer[n] );
+  }
+  _MM_TRANSPOSE4_PS( tmp[0] , tmp[2] , tmp[4] , tmp[6] );
+  _MM_TRANSPOSE4_PS( tmp[1] , tmp[3] , tmp[5] , tmp[7] );
+  _MM_TRANSPOSE4_PS( tmp[8] , tmp[10] , tmp[12] , tmp[14] );
+  _MM_TRANSPOSE4_PS( tmp[9] , tmp[11] , tmp[13] , tmp[15] );
+  for( Int n = 0 ; n < 8 ; n += 2 )
+  {
+    pBuffer[n] = _mm_castps_si128( tmp[n] );
+    pBuffer[n+1]  = _mm_castps_si128( tmp[n+8] );
+    pBuffer[n+8] = _mm_castps_si128( tmp[n+1] );
+    pBuffer[n+9]  = _mm_castps_si128( tmp[n+9] );
+  }
+}
+
+#ifdef __GNUC__
+#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
+#if GCC_VERSION > 40600 && GCC_VERSION < 40700
+__attribute__((optimize("no-tree-vrp")))
+#endif
+#endif
+Void simd8x8HAD1D32b( __m128i * pInput , __m128i * pOutput )
+{
+  __m128i m1[8][2] , m2[8][2];
+
+  m2[0][0] = _mm_add_epi32( pInput[0] ,pInput[8 ] );  m2[0][1] = _mm_add_epi32( pInput[1] ,pInput[9 ] );
+  m2[1][0] = _mm_add_epi32( pInput[2] ,pInput[10] );  m2[1][1] = _mm_add_epi32( pInput[3] ,pInput[11] );
+  m2[2][0] = _mm_add_epi32( pInput[4] ,pInput[12] );  m2[2][1] = _mm_add_epi32( pInput[5] ,pInput[13] );
+  m2[3][0] = _mm_add_epi32( pInput[6] ,pInput[14] );  m2[3][1] = _mm_add_epi32( pInput[7] ,pInput[15] );
+  m2[4][0] = _mm_sub_epi32( pInput[0] ,pInput[8 ] );  m2[4][1] = _mm_sub_epi32( pInput[1] ,pInput[9 ] );
+  m2[5][0] = _mm_sub_epi32( pInput[2] ,pInput[10] );  m2[5][1] = _mm_sub_epi32( pInput[3] ,pInput[11] );
+  m2[6][0] = _mm_sub_epi32( pInput[4] ,pInput[12] );  m2[6][1] = _mm_sub_epi32( pInput[5] ,pInput[13] );
+  m2[7][0] = _mm_sub_epi32( pInput[6] ,pInput[14] );  m2[7][1] = _mm_sub_epi32( pInput[7] ,pInput[15] );
+
+  m1[0][0] = _mm_add_epi32( m2[0][0] , m2[2][0] );  m1[0][1] = _mm_add_epi32( m2[0][1] , m2[2][1] );
+  m1[1][0] = _mm_add_epi32( m2[1][0] , m2[3][0] );  m1[1][1] = _mm_add_epi32( m2[1][1] , m2[3][1] );
+  m1[2][0] = _mm_sub_epi32( m2[0][0] , m2[2][0] );  m1[2][1] = _mm_sub_epi32( m2[0][1] , m2[2][1] );
+  m1[3][0] = _mm_sub_epi32( m2[1][0] , m2[3][0] );  m1[3][1] = _mm_sub_epi32( m2[1][1] , m2[3][1] );
+  m1[4][0] = _mm_add_epi32( m2[4][0] , m2[6][0] );  m1[4][1] = _mm_add_epi32( m2[4][1] , m2[6][1] );
+  m1[5][0] = _mm_add_epi32( m2[5][0] , m2[7][0] );  m1[5][1] = _mm_add_epi32( m2[5][1] , m2[7][1] );
+  m1[6][0] = _mm_sub_epi32( m2[4][0] , m2[6][0] );  m1[6][1] = _mm_sub_epi32( m2[4][1] , m2[6][1] );
+  m1[7][0] = _mm_sub_epi32( m2[5][0] , m2[7][0] );  m1[7][1] = _mm_sub_epi32( m2[5][1] , m2[7][1] );
+
+  pInput[0 ] = _mm_add_epi32( m1[0][0] , m1[1][0] );  pInput[1 ] = _mm_add_epi32( m1[0][1] , m1[1][1] );
+  pInput[2 ] = _mm_sub_epi32( m1[0][0] , m1[1][0] );  pInput[3 ] = _mm_sub_epi32( m1[0][1] , m1[1][1] );
+  pInput[4 ] = _mm_add_epi32( m1[2][0] , m1[3][0] );  pInput[5 ] = _mm_add_epi32( m1[2][1] , m1[3][1] );
+  pInput[6 ] = _mm_sub_epi32( m1[2][0] , m1[3][0] );  pInput[7 ] = _mm_sub_epi32( m1[2][1] , m1[3][1] );
+  pInput[8 ] = _mm_add_epi32( m1[4][0] , m1[5][0] );  pInput[9 ] = _mm_add_epi32( m1[4][1] , m1[5][1] );
+  pInput[10] = _mm_sub_epi32( m1[4][0] , m1[5][0] );  pInput[11] = _mm_sub_epi32( m1[4][1] , m1[5][1] );
+  pInput[12] = _mm_add_epi32( m1[6][0] , m1[7][0] );  pInput[13] = _mm_add_epi32( m1[6][1] , m1[7][1] );
+  pInput[14] = _mm_sub_epi32( m1[6][0] , m1[7][0] );  pInput[15] = _mm_sub_epi32( m1[6][1] , m1[7][1] );
+}
+
+inline __m128i simdAbs32b( __m128i m )
+{
+  const __m128i zero = _mm_setzero_si128();
+  __m128i tmp = _mm_sub_epi32( zero , m );
+  __m128i mask = _mm_cmpgt_epi32( m , tmp );
+  return( _mm_or_si128( _mm_and_si128( mask , m ) , _mm_andnot_si128( mask , tmp ) ) );
+}
+
+UInt simdHADs8x8( const Pel * piOrg, const Pel * piCur, Int iStrideOrg, Int iStrideCur )
+{
+  __m128i mmDiff[8][2];
+  __m128i mmZero = _mm_setzero_si128();
+  for( Int n = 0 ; n < 8 ; n++ , piOrg += iStrideOrg , piCur += iStrideCur )
+  {
+    __m128i diff = _mm_sub_epi16( _mm_loadu_si128( ( __m128i* )piOrg ) , _mm_loadu_si128( ( __m128i* )piCur ) );
+    // sign extension
+    __m128i mask = _mm_cmplt_epi16( diff , mmZero );
+    mmDiff[n][0] = _mm_unpacklo_epi16( diff , mask );
+    mmDiff[n][1] = _mm_unpackhi_epi16( diff , mask );
+  }
+
+  // transpose
+  simd8x8Transpose32b( &mmDiff[0][0] );
+
+  // horizontal
+  simd8x8HAD1D32b( &mmDiff[0][0] , &mmDiff[0][0] );
+
+  // transpose
+  simd8x8Transpose32b( &mmDiff[0][0] );
+
+  // vertical
+  simd8x8HAD1D32b( &mmDiff[0][0] , &mmDiff[0][0] );
+
+  __m128i mmSum = _mm_setzero_si128();
+  for( Int n = 0 ; n < 8 ; n++ )
+  {
+    mmSum = _mm_add_epi32( mmSum , simdAbs32b( mmDiff[n][0] ) );
+    mmSum = _mm_add_epi32( mmSum , simdAbs32b( mmDiff[n][1] ) );
+  }
+  mmSum = _mm_add_epi32( mmSum , _mm_shuffle_epi32( mmSum , _MM_SHUFFLE( 2 , 3 , 0 , 1 ) ) );
+  mmSum = _mm_add_epi32( mmSum , _mm_shuffle_epi32( mmSum , _MM_SHUFFLE( 1 , 0 , 3 , 2 ) ) );
+
+  UInt sad = _mm_cvtsi128_si32( mmSum );
+  sad = ( sad + 2 ) >> 2;
+
+  return( sad );
+}
+#endif
+
+
+
 #if NH_3D_VSO
 // SAIT_VSO_EST_A0033
@@ -507,6 +672,4 @@
 #if NH_3D
   cDtParam.bUseIC       = false;
-#endif
-#if NH_3D_SDC_INTER
   cDtParam.bUseSDCMRSAD = false;
 #endif
@@ -554,9 +717,5 @@
 #endif
 
-// ====================================================================================================================
-// Distortion functions
-// ====================================================================================================================
-
-#if NH_3D_DBBP
+#if NH_3D
 // --------------------------------------------------------------------------------------------------------------------
 // Masked distortion functions
@@ -599,7 +758,5 @@
   
   AOF(!pcDtParam->bApplyWeight);
-#if NH_3D_IC
   AOF(!pcDtParam->bUseIC);
-#endif
   
   const Pel* piOrg   = pcDtParam->pOrg;
@@ -674,11 +831,10 @@
     return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
   }
-#if NH_3D_IC
+#if NH_3D
   if( pcDtParam->bUseIC )
   {
     return xGetSADic( pcDtParam );
   }
-#endif
-#if NH_3D_SDC_INTER
+
   if( pcDtParam->bUseSDCMRSAD )
   {
@@ -696,4 +852,29 @@
   Distortion uiSum = 0;
 
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  if( pcDtParam->bitDepth <= 10 )
+  {
+    if( ( iCols & 0x07 ) == 0 )
+    {
+      for( Int iRows   = pcDtParam->iRows ; iRows != 0; iRows-- )
+      {
+        uiSum += simdSADLine8n16b( piOrg , piCur , iCols );
+        piOrg += iStrideOrg;
+        piCur += iStrideCur;
+      }
+    }
+    else
+    {
+      for( Int  iRows   = pcDtParam->iRows; iRows != 0; iRows-- )
+      {
+        uiSum += simdSADLine4n16b( piOrg , piCur , iCols );
+        piOrg += iStrideOrg;
+        piCur += iStrideCur;
+      }
+    }
+  }
+  else
+  {
+#endif
   for(Int iRows = pcDtParam->iRows ; iRows != 0; iRows-- )
   {
@@ -709,4 +890,7 @@
     piCur += iStrideCur;
   }
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  }
+#endif
 
   return ( uiSum >> distortionShift );
@@ -720,11 +904,9 @@
   }
 
-#if NH_3D_IC
+#if NH_3D
   if( pcDtParam->bUseIC )
   {
     return xGetSAD4ic( pcDtParam );
   }
-#endif
-#if NH_3D_SDC_INTER
   if( pcDtParam->bUseSDCMRSAD )
   {
@@ -743,4 +925,17 @@
   Distortion uiSum = 0;
 
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  if( pcDtParam->bitDepth <= 10 )
+  {
+    for( ; iRows != 0; iRows-=iSubStep )
+    {
+      uiSum += simdSADLine4n16b( piOrg , piCur , 4 );
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+    }
+  }
+  else
+  {
+#endif
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -753,4 +948,7 @@
     piCur += iStrideCur;
   }
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  }
+#endif
 
   uiSum <<= iSubShift;
@@ -765,11 +963,9 @@
   }
 
-#if NH_3D_IC
+#if NH_3D
   if( pcDtParam->bUseIC )
   {
     return xGetSAD8ic( pcDtParam );
   }
-#endif
-#if NH_3D_SDC_INTER
   if( pcDtParam->bUseSDCMRSAD )
   {
@@ -788,4 +984,17 @@
   Distortion uiSum = 0;
 
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  if( pcDtParam->bitDepth <= 10 )
+  {
+    for( ; iRows != 0; iRows-=iSubStep )
+    {
+      uiSum += simdSADLine8n16b( piOrg , piCur , 8 );
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+    }
+  }
+  else
+  {
+#endif
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -802,4 +1011,7 @@
     piCur += iStrideCur;
   }
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  }
+#endif
 
   uiSum <<= iSubShift;
@@ -814,11 +1026,9 @@
   }
 
-#if NH_3D_IC
+#if NH_3D
   if( pcDtParam->bUseIC )
   {
     return xGetSAD16ic( pcDtParam );
   }
-#endif
-#if NH_3D_SDC_INTER
   if( pcDtParam->bUseSDCMRSAD )
   {
@@ -837,4 +1047,17 @@
   Distortion uiSum = 0;
 
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  if( pcDtParam->bitDepth <= 10 )
+  {
+    for( ; iRows != 0; iRows-=iSubStep )
+    {
+      uiSum += simdSADLine8n16b( piOrg , piCur , 16 );
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+    }
+  }
+  else
+  {
+#endif
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -859,4 +1082,7 @@
     piCur += iStrideCur;
   }
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  }
+#endif
 
   uiSum <<= iSubShift;
@@ -870,11 +1096,9 @@
     return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
   }
-#if NH_3D_IC
+#if NH_3D
   if( pcDtParam->bUseIC )
   {
     return xGetSAD12ic( pcDtParam );
   }
-#endif
-#if NH_3D_SDC_INTER
   if( pcDtParam->bUseSDCMRSAD )
   {
@@ -918,11 +1142,9 @@
 Distortion TComRdCost::xGetSAD16N( DistParam* pcDtParam )
 {
-#if NH_3D_IC
+#if NH_3D
   if( pcDtParam->bUseIC )
   {
     return xGetSAD16Nic( pcDtParam );
   }
-#endif
-#if NH_3D_SDC_INTER
   if( pcDtParam->bUseSDCMRSAD )
   {
@@ -942,4 +1164,17 @@
   Distortion uiSum = 0;
 
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  if( pcDtParam->bitDepth <= 10 )
+  {
+    for( ; iRows != 0; iRows-=iSubStep )
+    {
+      uiSum += simdSADLine8n16b( piOrg , piCur , iCols );
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+    }
+  }
+  else
+  {
+#endif
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -966,4 +1201,7 @@
     piCur += iStrideCur;
   }
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  }
+#endif
 
   uiSum <<= iSubShift;
@@ -978,11 +1216,9 @@
   }
 
-#if NH_3D_IC
+#if NH_3D
   if( pcDtParam->bUseIC )
   {
     return xGetSAD32ic( pcDtParam );
   }
-#endif
-#if NH_3D_SDC_INTER
   if( pcDtParam->bUseSDCMRSAD )
   {
@@ -1001,4 +1237,17 @@
   Distortion uiSum = 0;
 
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  if( pcDtParam->bitDepth <= 10 )
+  {
+    for( ; iRows != 0; iRows-=iSubStep )
+    {
+      uiSum += simdSADLine8n16b( piOrg , piCur , 32 );
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+    }
+  }
+  else
+  {
+#endif
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -1039,4 +1288,7 @@
     piCur += iStrideCur;
   }
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  }
+#endif
 
   uiSum <<= iSubShift;
@@ -1051,11 +1303,9 @@
   }
 
-#if NH_3D_IC
+#if NH_3D
   if( pcDtParam->bUseIC )
   {
     return xGetSAD24ic( pcDtParam );
   }
-#endif
-#if NH_3D_SDC_INTER
   if( pcDtParam->bUseSDCMRSAD )
   {
@@ -1074,4 +1324,17 @@
   Distortion uiSum = 0;
 
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  if( pcDtParam->bitDepth <= 10 )
+  {
+    for( ; iRows != 0; iRows-=iSubStep )
+    {
+      uiSum += simdSADLine8n16b( piOrg , piCur , 24 );
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+    }
+  }
+  else
+  {
+#endif
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -1104,4 +1367,7 @@
     piCur += iStrideCur;
   }
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  }
+#endif
 
   uiSum <<= iSubShift;
@@ -1116,11 +1382,9 @@
   }
 
-#if NH_3D_IC
+#if NH_3D
   if( pcDtParam->bUseIC )
   {
     return xGetSAD64ic( pcDtParam );
   }
-#endif
-#if NH_3D_SDC_INTER
   if( pcDtParam->bUseSDCMRSAD )
   {
@@ -1139,4 +1403,17 @@
   Distortion uiSum = 0;
 
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  if( pcDtParam->bitDepth <= 10 )
+  {
+    for( ; iRows != 0; iRows-=iSubStep )
+    {
+      uiSum += simdSADLine8n16b( piOrg , piCur , 64 );
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+    }
+  }
+  else
+  {
+#endif
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -1209,4 +1486,7 @@
     piCur += iStrideCur;
   }
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  }
+#endif
 
   uiSum <<= iSubShift;
@@ -1220,11 +1500,9 @@
     return TComRdCostWeightPrediction::xGetSADw( pcDtParam );
   }
-#if NH_3D_IC
+#if NH_3D
   if( pcDtParam->bUseIC )
   {
     return xGetSAD48ic( pcDtParam );
   }
-#endif
-#if NH_3D_SDC_INTER
   if( pcDtParam->bUseSDCMRSAD )
   {
@@ -1243,4 +1521,17 @@
   Distortion uiSum = 0;
 
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  if( pcDtParam->bitDepth <= 10 )
+  {
+    for( ; iRows != 0; iRows-=iSubStep )
+    {
+      uiSum += simdSADLine8n16b( piOrg , piCur , 48 );
+      piOrg += iStrideOrg;
+      piCur += iStrideCur;
+    }
+  }
+  else
+  {
+#endif
   for( ; iRows != 0; iRows-=iSubStep )
   {
@@ -1297,5 +1588,7 @@
     piCur += iStrideCur;
   }
-
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  }
+#endif
   uiSum <<= iSubShift;
   return ( uiSum >> DISTORTION_PRECISION_ADJUSTMENT(pcDtParam->bitDepth-8) );
@@ -1303,5 +1596,5 @@
 
 
-#if NH_3D_IC || NH_3D_SDC_INTER
+#if NH_3D
 UInt TComRdCost::xGetSADic( DistParam* pcDtParam )
 {
@@ -3138,6 +3431,16 @@
 }
 
-Distortion TComRdCost::xCalcHADs8x8( const Pel *piOrg, const Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep )
-{
+Distortion TComRdCost::xCalcHADs8x8( const Pel *piOrg, const Pel *piCur, Int iStrideOrg, Int iStrideCur, Int iStep
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  , Int bitDepth
+#endif
+  )
+{
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+  if( bitDepth <= 10 )
+{
+    return( simdHADs8x8( piOrg , piCur , iStrideOrg , iStrideCur ) );
+  }
+#endif
   Int k, i, j, jj;
   Distortion sad = 0;
@@ -3242,11 +3545,9 @@
     return TComRdCostWeightPrediction::xGetHADsw( pcDtParam );
   }
-#if NH_3D_IC
+#if NH_3D
   if( pcDtParam->bUseIC )
   {
     return xGetHADsic( pcDtParam );
   }
-#endif
-#if NH_3D_SDC_INTER
   if( pcDtParam->bUseSDCMRSAD )
   {
@@ -3275,5 +3576,9 @@
       for ( x=0; x<iCols; x+= 8 )
       {
-        uiSum += xCalcHADs8x8( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+        uiSum += xCalcHADs8x8( &piOrg[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+          , pcDtParam->bitDepth
+#endif
+                            );
       }
       piOrg += iOffsetOrg;
@@ -3318,5 +3623,5 @@
 }
 
-#if NH_3D_IC || NH_3D_SDC_INTER
+#if NH_3D
 UInt TComRdCost::xGetHADsic( DistParam* pcDtParam )
 {
@@ -3389,5 +3694,9 @@
       for ( x=0; x<iCols; x+= 8 )
       {
-        uiSum += xCalcHADs8x8( &tempOrgMinusDeltaDc[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep );
+        uiSum += xCalcHADs8x8( &tempOrgMinusDeltaDc[x], &piCur[x*iStep], iStrideOrg, iStrideCur, iStep 
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+          , pcDtParam->bitDepth
+#endif    
+          );
       }
       tempOrgMinusDeltaDc += iOffsetOrg;
@@ -3470,6 +3779,5 @@
   m_uiLambdaMotionSSEVSO = (UInt)floor(65536.0 *       m_dLambdaVSO    );
 }
-#endif
-#if NH_3D_VSO
+
 Dist TComRdCost::xGetDistVSOMode4( Int iStartPosX, Int iStartPosY, Pel* piCur, Int iCurStride, Pel* piOrg, Int iOrgStride, UInt uiBlkWidth, UInt uiBlkHeight, Bool bSAD )
 { 
@@ -3626,3 +3934,4 @@
 #endif
 
+
 //! \}
Index: /trunk/source/Lib/TLibCommon/TComRdCost.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComRdCost.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComRdCost.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -90,8 +90,6 @@
   Int   iStrideVir;
 #endif
-#if NH_3D_IC
+#if NH_3D
   Bool  bUseIC;
-#endif
-#if NH_3D_SDC_INTER
   Bool  bUseSDCMRSAD;
 #endif
@@ -136,5 +134,5 @@
     iStrideVir = 0;
 #endif
-#if NH_3D_SDC_INTER
+#if NH_3D
     bUseSDCMRSAD = false;
 #endif
@@ -165,5 +163,5 @@
   Double                  m_motionLambda;
   Int                     m_iCostScale;
-#if NH_3D_DBBP
+#if NH_3D
   Bool                    m_bUseMask;
 #endif
@@ -204,5 +202,5 @@
   Void    setDistParam( DistParam& rcDP, Int bitDepth, const Pel* p1, Int iStride1, const Pel* p2, Int iStride2, Int iWidth, Int iHeight, Bool bHadamard = false );
 
-#if NH_3D_DBBP
+#if NH_3D
   Void    setUseMask(Bool b) { m_bUseMask = b; }
 #endif
@@ -210,5 +208,5 @@
   Distortion calcHAD(Int bitDepth, const Pel* pi0, Int iStride0, const Pel* pi1, Int iStride1, Int iWidth, Int iHeight );
 
-#if NH_3D_ENC_DEPTH
+#if NH_3D
   UInt    calcVAR(Pel* pi0, Int stride, Int width, Int height, Int cuDepth, UInt maxCuWidth );
 #endif  
@@ -242,5 +240,5 @@
   static Distortion xGetSSE64         ( DistParam* pcDtParam );
   static Distortion xGetSSE16N        ( DistParam* pcDtParam );
-#if NH_3D_IC || NH_3D_SDC_INTER
+#if NH_3D
   static UInt xGetSADic         ( DistParam* pcDtParam );
   static UInt xGetSAD4ic        ( DistParam* pcDtParam );
@@ -269,5 +267,5 @@
 #endif
 
-#if NH_3D_IC || NH_3D_SDC_INTER
+#if NH_3D
   static UInt xGetSAD12ic       ( DistParam* pcDtParam );
   static UInt xGetSAD24ic       ( DistParam* pcDtParam );
@@ -280,5 +278,5 @@
 
 
-#if NH_3D_IC || NH_3D_SDC_INTER
+#if NH_3D
   static UInt xGetHADsic          ( DistParam* pcDtParam );
 #endif
@@ -287,6 +285,10 @@
   static Distortion xCalcHADs2x2      ( const Pel *piOrg, const Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
   static Distortion xCalcHADs4x4      ( const Pel *piOrg, const Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
-  static Distortion xCalcHADs8x8      ( const Pel *piOrg, const Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep );
-#if NH_3D_DBBP
+  static Distortion xCalcHADs8x8      ( const Pel *piOrg, const Pel *piCurr, Int iStrideOrg, Int iStrideCur, Int iStep
+#if VECTOR_CODING__DISTORTION_CALCULATIONS && (RExt__HIGH_BIT_DEPTH_SUPPORT==0)
+                                      , Int bitDepth
+#endif
+                                      );
+#if NH_3D
   static UInt xGetMaskedSSE     ( DistParam* pcDtParam );
   static UInt xGetMaskedSAD     ( DistParam* pcDtParam );
Index: /trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -74,23 +74,4 @@
   Distortion uiSum = 0;
 
-#if !U0040_MODIFIED_WEIGHTEDPREDICTION_WITH_BIPRED_AND_CLIPPING
-  for(Int iRows = pcDtParam->iRows; iRows != 0; iRows-- )
-  {
-    for (Int n = 0; n < iCols; n++ )
-    {
-      const Pel pred = ( (w0*piCur[n] + round) >> shift ) + offset ;
-
-      uiSum += abs( piOrg[n] - pred );
-    }
-    if (pcDtParam->m_maximumDistortionForEarlyExit <  ( uiSum >> distortionShift))
-    {
-      return uiSum >> distortionShift;
-    }
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-
-  pcDtParam->compIdx = MAX_NUM_COMPONENT;  // reset for DEBUG (assert test)
-#else
   // Default weight
   if (w0 == 1 << shift)
@@ -222,5 +203,4 @@
   }
   //pcDtParam->compIdx = MAX_NUM_COMPONENT;  // reset for DEBUG (assert test)
-#endif
 
   return uiSum >> distortionShift;
@@ -256,19 +236,4 @@
   Distortion sum = 0;
 
-#if !U0040_MODIFIED_WEIGHTEDPREDICTION_WITH_BIPRED_AND_CLIPPING
-  for(Int iRows = pcDtParam->iRows ; iRows != 0; iRows-- )
-  {
-    for (Int n = 0; n < iCols; n++ )
-    {
-      const Pel pred     = ( (w0*piCur[n] + round) >> shift ) + offset ;
-      const Pel residual = piOrg[n] - pred;
-      sum += ( Distortion(residual) * Distortion(residual) ) >> distortionShift;
-    }
-    piOrg += iStrideOrg;
-    piCur += iStrideCur;
-  }
-
-  pcDtParam->compIdx = MAX_NUM_COMPONENT; // reset for DEBUG (assert test)
-#else
   if (pcDtParam->bIsBiPred)
   {
@@ -303,5 +268,4 @@
 
   //pcDtParam->compIdx = MAX_NUM_COMPONENT; // reset for DEBUG (assert test)
-#endif
 
   return sum;
Index: /trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComRdCostWeightPrediction.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComRectangle.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComRectangle.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComRectangle.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComRom.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComRom.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComRom.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -253,5 +253,5 @@
     }
   }
-#if NH_3D_DMM
+#if NH_3D
   if( !g_dmmWedgeLists.empty() ) 
   {
@@ -509,5 +509,5 @@
   //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, DM
   { 0, 1, 2, 2, 2, 2, 3, 5, 7, 8, 10, 12, 13, 15, 17, 18, 19, 20, 21, 22, 23, 23, 24, 24, 25, 25, 26, 27, 27, 28, 28, 29, 29, 30, 31, DM_CHROMA_IDX};
-#if NH_3D_DMM
+#if NH_3D
 // ====================================================================================================================
 // Depth coding modes
@@ -537,5 +537,5 @@
 const Bool g_bEncDecTraceEnable  = true;
 const Bool g_bEncDecTraceDisable = false;
-Bool   g_HLSTraceEnable = false;
+Bool   g_HLSTraceEnable = true;
 Bool   g_bJustDoIt = false;
 UInt64 g_nSymbolCounter = 0;
@@ -790,5 +790,5 @@
 #endif
 #endif
-#if NH_3D_DMM
+#if NH_3D
 std::vector< std::vector<TComWedgelet>  > g_dmmWedgeLists;
 std::vector< std::vector<TComWedgeNode> > g_dmmWedgeNodeLists;
Index: /trunk/source/Lib/TLibCommon/TComRom.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComRom.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComRom.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -39,5 +39,5 @@
 #include<stdio.h>
 #include<iostream>
-#if NH_3D_DMM
+#if NH_3D
 #include "TComWedgelet.h"
 #endif
@@ -91,5 +91,5 @@
 extern const UChar  g_aucIntraModeNumFast_NotUseMPM[MAX_CU_DEPTH];
 extern const UChar  g_chroma422IntraAngleMappingTable[NUM_INTRA_MODE];
-#if NH_3D_DMM
+#if NH_3D
 // ====================================================================================================================
 // Depth coding modes
Index: /trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -655,5 +655,5 @@
   Bool  bPCMFilter = (pcPic->getSlice(0)->getSPS()->getUsePCM() && pcPic->getSlice(0)->getSPS()->getPCMFilterDisableFlag())? true : false;
 
-  if(bPCMFilter || pcPic->getSlice(0)->getPPS()->getTransquantBypassEnableFlag())
+  if(bPCMFilter || pcPic->getSlice(0)->getPPS()->getTransquantBypassEnabledFlag())
   {
     for( UInt ctuRsAddr = 0; ctuRsAddr < pcPic->getNumberOfCtusInFrame() ; ctuRsAddr++ )
Index: /trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComSampleAdaptiveOffset.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComSlice.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComSlice.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComSlice.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
 
@@ -42,5 +42,7 @@
 #include "TLibEncoder/TEncSbac.h"
 #include "TLibDecoder/TDecSbac.h"
-
+#if NH_MV
+#include <set>
+#endif
 
 //! \ingroup TLibCommon
@@ -139,15 +141,11 @@
 , m_pocMsbValRequiredFlag         (false)
 #endif
-#if NH_3D_IC
+#if NH_3D
 , m_bApplyIC                      (false)
 , m_icSkipParseFlag               (false)
-#endif
-#if NH_3D
 , m_inCmpPredFlag                 (false)
 , m_numViews                      (0)
 , m_depthToDisparityB             (NULL)
 , m_depthToDisparityF             (NULL)
-#endif
-#if NH_3D_DIS
 , m_bApplyDIS                     (false)
 #endif
@@ -289,5 +287,5 @@
     m_iSliceChromaQpDelta[component] = 0;
   }
-#if NH_3D_IV_MERGE
+#if NH_3D
   m_maxNumMergeCand = MRG_MAX_NUM_CANDS_MEM;
 #else
@@ -300,5 +298,5 @@
   m_cabacInitFlag        = false;
   m_enableTMVPFlag = true;
-#if NH_3D_TMVP
+#if NH_3D
   m_aiAlterRefIdx[0]                  = -1;
   m_aiAlterRefIdx[1]                  = -1;
@@ -828,5 +826,4 @@
 }
 #if NH_3D
-#if NH_3D_TMVP
 Void TComSlice::generateAlterRefforTMVP()
 {
@@ -849,5 +846,4 @@
   }
 }
-#endif
 #endif
 
@@ -1169,8 +1165,6 @@
   }
 #endif
-#if NH_3D_DIS
+#if NH_3D
   m_bApplyDIS = pSrc->m_bApplyDIS;
-#endif
-#if NH_3D_IC
   m_bApplyIC = pSrc->m_bApplyIC;
   m_icSkipParseFlag = pSrc->m_icSkipParseFlag;
@@ -1967,15 +1961,15 @@
   for( Int i = 0; i < MAX_NUM_LAYERS; i++ )
   {
-    m_layerIdInNuh      [i] = ( i == 0 ) ? 0 : -1; 
-    m_numDirectRefLayers[i] = 0; 
+    m_layerIdInNuh        [i] = ( i == 0 ) ? 0 : -1; 
+    m_numDirectRefLayers  [i] = 0; 
 #if NH_3D
-    m_numRefListLayers[i] = 0; 
-#endif
-    m_vpsRepFormatIdx    [i] = 0; 
+    m_numRefListLayers    [i] = 0; 
+#endif
+    m_vpsRepFormatIdx     [i] = 0; 
     m_pocLsbNotPresentFlag[i] = 0;    
-    m_viewIdVal          [i] = 0; 
+    m_viewIdVal           [i] = 0; 
 
 #if NH_3D
-    m_viewIndex         [i] = -1; 
+    m_viewIndex           [i] = -1; 
 #endif
 
@@ -1998,6 +1992,4 @@
       m_dimensionId[i][j] = 0;
     }
-#if NH_3D_ARP
-#endif
   }  
 #endif
@@ -2283,4 +2275,20 @@
 
 
+#if NH_3D
+Bool TComVPS::isFirstDepthLayer(Int layerIdInNuh) const
+{
+  Bool firstDepthLayer = false;
+  for(Int i = 0; i <= getMaxLayersMinus1(); i++  )
+  {
+    Int curLayerIdInNuh = getLayerIdInNuh( i );
+    if ( getVpsDepthFlag( curLayerIdInNuh ) )
+    {
+      firstDepthLayer =  ( curLayerIdInNuh == layerIdInNuh);
+      break;
+    }
+  }
+  return firstDepthLayer;
+}
+#endif
 
 Void TComVPS::deriveLayerSetLayerIdList()
@@ -2488,4 +2496,69 @@
 }
 
+
+Void TComVPS::printRepFormat() const
+{
+
+  vector<Int> idc;
+  vector<Int> width;
+  vector<Int> height; 
+  vector<Int> chromaAndBitDepthPresent;
+  vector<Int> chormaFormat;   
+  vector<Int> bitDepthLuma; 
+  vector<Int> bitDepthChroma;
+  vector<Int> conformanceWindowPresent; 
+  vector<Int> confLeftOff;
+  vector<Int> confRightOff;
+  vector<Int> confTopOff;
+  vector<Int> confBottomOff;
+
+  for (Int i = 0; i <= getVpsNumRepFormatsMinus1(); i++ )
+  {
+    const TComRepFormat* repFormat = getRepFormat( i );
+
+    idc                             .push_back(        i             );
+    width                           .push_back(  repFormat->getPicWidthVpsInLumaSamples()  );
+    height                          .push_back(  repFormat->getPicHeightVpsInLumaSamples() );
+    chromaAndBitDepthPresent        .push_back(  repFormat->getChromaAndBitDepthVpsPresentFlag() ? 1 : 0    );
+    chormaFormat                    .push_back(  repFormat->getChromaFormatVpsIdc()        );
+    bitDepthLuma                    .push_back(  repFormat->getBitDepthVpsLumaMinus8()     );
+    bitDepthChroma                  .push_back(  repFormat->getBitDepthVpsChromaMinus8()   );
+    conformanceWindowPresent        .push_back(  repFormat->getConformanceWindowVpsFlag()  );
+    confLeftOff                     .push_back(  repFormat->getConfWinVpsLeftOffset()      );
+    confRightOff                    .push_back(  repFormat->getConfWinVpsRightOffset()     );
+    confTopOff                      .push_back(  repFormat->getConfWinVpsTopOffset()       );
+    confBottomOff                   .push_back(  repFormat->getConfWinVpsBottomOffset()    );
+  }
+
+  std::cout << std::right << std::setw(60) << std::setfill('-') << " " << std::setfill(' ') << std::endl << "Rep Format" << std::endl; 
+  
+  std::vector<Int> repFormatIdx;
+
+  for (Int i = 0; i <= getMaxLayersMinus1(); i++ )
+  {
+    repFormatIdx.push_back( getVpsRepFormatIdx(i ) );
+  }
+
+  xPrintArray( "rep_format_idx", getMaxLayersMinus1()+1, repFormatIdx, false  );
+
+  std::cout << std::endl;
+
+  xPrintArray( "i"                                      , getVpsNumRepFormatsMinus1()+1, idc                                    , false, 6 );
+  xPrintArray( "pic_width_vps_in_luma_samples"          , getVpsNumRepFormatsMinus1()+1, width                                  , false, 6 );
+  xPrintArray( "pic_height_vps_in_luma_samples"         , getVpsNumRepFormatsMinus1()+1, height                                 , false, 6 );       
+  xPrintArray( "chroma_and_bit_depth_vps_present_flag"  , getVpsNumRepFormatsMinus1()+1, chromaAndBitDepthPresent               , false, 6 );     
+  xPrintArray( "chroma_format_vps_idc"                  , getVpsNumRepFormatsMinus1()+1, chormaFormat                           , false, 6 );     
+  xPrintArray( "bit_depth_vps_luma_minus8"              , getVpsNumRepFormatsMinus1()+1, bitDepthLuma                           , false, 6 );     
+  xPrintArray( "bit_depth_vps_chroma_minus8"            , getVpsNumRepFormatsMinus1()+1, bitDepthChroma                         , false, 6 );     
+  xPrintArray( "conformance_window_vps_flag"            , getVpsNumRepFormatsMinus1()+1, conformanceWindowPresent               , false, 6 );     
+  xPrintArray( "conf_win_vps_left_offset"               , getVpsNumRepFormatsMinus1()+1, confLeftOff                            , false, 6 );     
+  xPrintArray( "conf_win_vps_right_offset"              , getVpsNumRepFormatsMinus1()+1, confRightOff                           , false, 6 );     
+  xPrintArray( "conf_win_vps_top_offset"                , getVpsNumRepFormatsMinus1()+1, confTopOff                             , false, 6 );     
+  xPrintArray( "conf_win_vps_bottom_offset"             , getVpsNumRepFormatsMinus1()+1, confBottomOff                          , false, 6 );     
+
+  std::cout << std::endl;
+}
+
+
 Void TComVPS::printLayerDependencies() const
 {
@@ -2614,4 +2687,46 @@
   xPrintArray( "TargetDecLayerIdList", getNumOutputLayerSets(), rangeOutputLayerSets, numDecLayer,                     m_targetDecLayerIdLists, true );
   std::cout << endl;
+}
+
+IntAry1d TComVPS::getLayersOfVpsPtl(Int idxOfVpsPtl) const
+{
+  std::set<Int> applicableLayerIdsInVps;
+  // Get max chroma format and max bit depth of layers to which ptl is applicable to.
+
+  if ( idxOfVpsPtl == 0 || idxOfVpsPtl == 1 )
+  {
+    // If the profile_tier_level( ) syntax structure is included in an active SPS for the base layer or is the profile_tier_level( ) syntax structure 
+    // VpsProfileTierLevel[ 0 ], it applies to the OLS containing all layers in the bitstream but with only the base layer being the output layer.
+
+    // the value of profile_tier_level_idx[ 0 ][ 0 ] is inferred to be equal to 1, such that 
+    // VpsProfileTierLevel[ 1 ] applies to the 0-th OLS, which contains only the base layer that is the only output layer.
+
+    // Consider only the base layer
+    applicableLayerIdsInVps.insert( 0 );
+  }
+  else
+  {
+    // Otherwise, the profile_tier_level( ) syntax structure provides profile, tier and level to which a layer in an OLS conforms 
+    // and the profile_tier_level_idx[ i ][ j ] syntax element specifies that the profile_tier_level( ) syntax structure 
+    // VpsProfileTierLevel[ profile_tier_level_idx[ i ][ j ] ] applies to the j-th layer of the i-th OLS.
+
+    for (Int j = 0; j < getNumOutputLayerSets(); j++ )
+    {
+      for (Int k = 0; k < getNumOutputLayersInOutputLayerSet( j );  k++)
+      {
+        if ( getProfileTierLevelIdx(j,k)  == idxOfVpsPtl )
+        {
+          applicableLayerIdsInVps.insert( getLayerIdInVps( getTargetOptLayerIdList( j )[ k ]  ) );
+        }
+      }
+    }
+  }
+
+  IntAry1d layers;
+  for(std::set<Int>::iterator it = applicableLayerIdsInVps.begin(); it != applicableLayerIdsInVps.end(); ++it  )
+  {
+    layers.push_back( *it ); 
+  }
+  return layers;
 }
 
@@ -2774,6 +2889,7 @@
   m_spsMultilayerExtensionFlag = false;
   m_spsExtension5bits          = 0;
-  m_sps3dExtensionFlag         = false; 
-
+  m_sps3dExtensionFlag         = false;   
+  m_layerId                    = -1; 
+  m_inferredRepFormat          = NULL;
 #endif
 
@@ -2822,5 +2938,5 @@
 , m_numRefIdxL0DefaultActive         (1)
 , m_numRefIdxL1DefaultActive         (1)
-, m_TransquantBypassEnableFlag       (false)
+, m_TransquantBypassEnabledFlag      (false)
 , m_useTransformSkip                 (false)
 , m_dependentSliceSegmentsEnabledFlag(false)
@@ -2831,5 +2947,5 @@
 , m_numTileColumnsMinus1             (0)
 , m_numTileRowsMinus1                (0)
-, m_signHideFlag                     (false)
+, m_signDataHidingEnabledFlag        (false)
 , m_cabacInitPresentFlag             (false)
 , m_sliceHeaderExtensionPresentFlag  (false)
@@ -2842,5 +2958,5 @@
 , m_pocResetInfoPresentFlag          (false)
 #endif
-#if NH_3D_DLT
+#if NH_3D
 , m_cDLT                             ()
 #endif
@@ -2859,6 +2975,6 @@
 }
 
-#if NH_3D_DLT
-TComDLT::TComDLT()
+#if NH_3D
+TComDLT::TComDLT( )
 : m_bDltPresentFlag(false)
 , m_iNumDepthViews(0)
@@ -3004,12 +3120,48 @@
 
 #if NH_MV
-Void TComSPS::inferRepFormat( TComVPS* vps, Int layerIdCurr, Bool encoder )
-{
-  if ( getMultiLayerExtSpsFlag() )
-  {    
-    Int            repFormatIdx = getUpdateRepFormatFlag() ?  getSpsRepFormatIdx() : vps->getVpsRepFormatIdx( vps->getLayerIdInVps( layerIdCurr ) ) ;
-    const TComRepFormat* repFormat    = vps->getRepFormat( repFormatIdx ); 
-
-    if ( encoder )
+Void TComSPS::inferRepFormat( TComVPS* vps, Int layerIdCurr, Bool alreadySet )
+{ 
+  // Parameters are present in the SPS
+  // - base layer or muliLayerExpSpsFlag equal to zero
+
+  // It is a requirement of bitstream conformance that, when present, the value of chroma_format_idc, 
+  // separate_colour_plane_flag, pic_width_in_luma_samples, pic_height_in_luma_samples, bit_depth_luma_minus8 or 
+  // bit_depth_chroma_minus8 shall be less than or equal to chroma_format_vps_idc, separate_colour_plane_vps_flag, 
+  // pic_width_vps_in_luma_samples, pic_height_vps_in_luma_samples, bit_depth_vps_luma_minus8, or bit_depth_vps_chroma_minus8, 
+  // respectively, of the vps_rep_format_idx[ j ]-th rep_format( ) syntax structure 
+  // in the active VPS, where j is equal to LayerIdxInVps[ layerIdCurr ].
+
+  Bool baseLayer               = ( layerIdCurr == 0 );
+  Bool independentNonBaseLayer = vps->isIndependendNonBaseLayer( layerIdCurr );
+  Bool multiLayerExtSpsFlag    = getMultiLayerExtSpsFlag(); 
+
+  Int            repFormatIdx = getUpdateRepFormatFlag() ?  getSpsRepFormatIdx() : vps->getVpsRepFormatIdx( vps->getLayerIdInVps( layerIdCurr ) ) ;
+  const TComRepFormat* repFormat    = vps->getRepFormat( repFormatIdx ); 
+
+  assert( !( multiLayerExtSpsFlag && ( independentNonBaseLayer || baseLayer )) ); 
+
+  Bool presentInSps = !multiLayerExtSpsFlag;
+  if ( presentInSps )
+  {
+    // Values have been set before in xInitSps
+
+    assert( getChromaFormatIdc()      <=  repFormat->getChromaFormatVpsIdc()         ); 
+    //// ToDo: add when supported: 
+    ///  assert( getSeperateColourPlaneFlag() <=  repFormat->getSeparateColourPlaneVpsFlag() ) ; 
+
+    assert( getPicWidthInLumaSamples()  <= repFormat->getPicWidthVpsInLumaSamples()    ); 
+    assert( getPicHeightInLumaSamples() <= repFormat->getPicHeightVpsInLumaSamples()   ); 
+
+    assert( getBitDepth( CHANNEL_TYPE_LUMA   )  <= repFormat->getBitDepthVpsLumaMinus8()   + 8 );         
+    assert( getBitDepth( CHANNEL_TYPE_CHROMA )  <= repFormat->getBitDepthVpsChromaMinus8() + 8 ); 
+  }
+
+  if ( !independentNonBaseLayer )
+  {
+
+    Window &spsConf    = getConformanceWindow();    
+
+    // Inference when not already done at the encoder.
+    if ( alreadySet )
     {
       assert( getChromaFormatIdc() ==  (ChromaFormat) repFormat->getChromaFormatVpsIdc() );         
@@ -3025,4 +3177,11 @@
       assert( getBitDepth              ( CHANNEL_TYPE_CHROMA ) == repFormat->getBitDepthVpsChromaMinus8() + 8 ); 
       assert( getQpBDOffset            ( CHANNEL_TYPE_CHROMA ) == (Int) (6* ( getBitDepth( CHANNEL_TYPE_CHROMA ) -8 ) ) );
+
+      
+      assert( spsConf.getWindowLeftOffset  () == repFormat->getConfWinVpsLeftOffset()    );
+      assert( spsConf.getWindowRightOffset () == repFormat->getConfWinVpsRightOffset()   );
+      assert( spsConf.getWindowTopOffset   () == repFormat->getConfWinVpsTopOffset()     );
+      assert( spsConf.getWindowBottomOffset() == repFormat->getConfWinVpsBottomOffset()  );            
+
     }
     else
@@ -3040,6 +3199,5 @@
       setBitDepth              ( CHANNEL_TYPE_CHROMA, repFormat->getBitDepthVpsChromaMinus8() + 8 ); 
       setQpBDOffset            ( CHANNEL_TYPE_CHROMA, (Int) (6* ( getBitDepth( CHANNEL_TYPE_CHROMA ) -8 ) ) );
-      Window &spsConf    = getConformanceWindow();    
-
+      
       // Scaled later
       spsConf.setScaledFlag( false ); 
@@ -3049,18 +3207,6 @@
       spsConf.setWindowBottomOffset( repFormat->getConfWinVpsBottomOffset()  );            
     }
-
-   if ( getMultiLayerExtSpsFlag() && getUpdateRepFormatFlag() )
-    {
-      assert( getChromaFormatIdc()      <=  repFormat->getChromaFormatVpsIdc()         ); 
-      //// ToDo: add when supported: 
-      // assert( getSeperateColourPlaneFlag() <=  repFormat->getSeparateColourPlaneVpsFlag() ) ; 
-
-      assert( getPicWidthInLumaSamples()  <= repFormat->getPicWidthVpsInLumaSamples()    ); 
-      assert( getPicHeightInLumaSamples() <= repFormat->getPicHeightVpsInLumaSamples()   ); 
-
-      assert( getBitDepth( CHANNEL_TYPE_LUMA   )  <= repFormat->getBitDepthVpsLumaMinus8()   + 8 );         
-      assert( getBitDepth( CHANNEL_TYPE_CHROMA )  <= repFormat->getBitDepthVpsChromaMinus8() + 8 ); 
-    }
-  }
+  }
+  
 
   // Set conformance window
@@ -3068,16 +3214,4 @@
   getConformanceWindow().scaleOffsets( scal );
   getVuiParameters()->getDefaultDisplayWindow().scaleOffsets( scal );
-
-  if (encoder && getMultiLayerExtSpsFlag() )
-  { 
-    Int            repFormatIdx = getUpdateRepFormatFlag() ?  getSpsRepFormatIdx() : vps->getVpsRepFormatIdx( vps->getLayerIdInVps( layerIdCurr ) ) ;
-    const TComRepFormat* repFormat    = vps->getRepFormat( repFormatIdx ); 
-
-    Window &spsConf    = getConformanceWindow();    
-    assert( spsConf.getWindowLeftOffset  () == repFormat->getConfWinVpsLeftOffset()    );
-    assert( spsConf.getWindowRightOffset () == repFormat->getConfWinVpsRightOffset()   );
-    assert( spsConf.getWindowTopOffset   () == repFormat->getConfWinVpsTopOffset()     );
-    assert( spsConf.getWindowBottomOffset() == repFormat->getConfWinVpsBottomOffset()  );            
-  }
 }
 
@@ -3092,5 +3226,5 @@
 }
 
-Void TComSPS::inferSpsMaxDecPicBufferingMinus1( TComVPS* vps, Int targetOptLayerSetIdx, Int currLayerId, Bool encoder )
+Void TComSPS::inferSpsMaxDecPicBufferingMinus1( TComVPS* vps, Int targetOptLayerSetIdx, Int currLayerId, Bool doCheck )
 {
   if ( getMultiLayerExtSpsFlag() )
@@ -3116,5 +3250,5 @@
       Int maxNumReorderPics       = vps->getDpbSize()->getMaxVpsNumReorderPics( targetOptLayerSetIdx, i ); 
       Int maxLatencyIncreasePlus1 = vps->getDpbSize()->getMaxVpsLatencyIncreasePlus1( targetOptLayerSetIdx, i ); 
-      if ( encoder )      
+      if ( doCheck )      
       {
         assert( getMaxDecPicBuffering( i ) - 1 == maxDecPicBufferingMinus1 ); 
@@ -3602,5 +3736,5 @@
 }
 #endif
-#if NH_3D_NBDV
+#if NH_3D
 Void TComSlice::setDefaultRefView()
 {
@@ -3636,7 +3770,5 @@
   }
 }
-#endif
-
-#if NH_3D_ARP
+
 Void TComSlice::setARPStepNum( TComPicLists*ivPicLists )
 {
@@ -3722,7 +3854,5 @@
   }
 }
-#endif
-
-#if NH_3D_IC
+
 // This is an encoder only function and should be moved to TEncSlice or TEncSearch!!
 Void TComSlice::xSetApplyIC(Bool bUseLowLatencyICEnc)
@@ -3860,6 +3990,5 @@
   }//if(bUseLowLatencyICEnc)
 }
-#endif
-#if NH_3D_QTL
+
 Void TComSlice::setIvPicLists( TComPicLists* m_ivPicLists )
 {  
@@ -3879,12 +4008,6 @@
   
   setupLUT = setupLUT || getViewSynthesisPredFlag( ); 
-
-#if NH_3D_NBDV_REF
   setupLUT = setupLUT || getDepthRefinementFlag( );
-#endif  
-
-#if NH_3D_IV_MERGE
   setupLUT = setupLUT || ( getIvMvPredFlag() && getIsDepth() );
-#endif
 
   Int bitDepthY = getSPS()->getBitDepth(CHANNEL_TYPE_LUMA);
@@ -4388,5 +4511,6 @@
     if( getVPS()->getViewCompLayerPresentFlag( m_inCmpRefViewIdcs[ i ], !getIsDepth() ) )
     {
-      Int j = getVPS()->getLayerIdInVps( getVPS()->getViewCompLayerId( m_inCmpRefViewIdcs[ i ],  !getIsDepth() ) );
+      Int jInNuh = getVPS()->getViewCompLayerId( m_inCmpRefViewIdcs[ i ],  !getIsDepth() );
+      Int j = getVPS()->getLayerIdInVps( jInNuh );
       if  ( getVPS()->getDirectDependencyFlag( getVPS()->getLayerIdInVps( getLayerId() ) ,  j ) &&
         getVPS()->getSubLayersVpsMaxMinus1( j ) >= getTemporalId()   &&
@@ -4738,8 +4862,10 @@
 , m_spsMap(MAX_NUM_SPS)
 , m_ppsMap(MAX_NUM_PPS)
-, m_activeVPSId(-1)
 #if !NH_MV
 , m_activeSPSId(-1)
-#endif
+#else
+, m_spsActiveForLayer(MAX_NUM_LAYERS)
+#endif
+, m_activeVPSId(-1)
 {
 #if NH_MV  
@@ -4861,4 +4987,16 @@
 
   return false;
+}
+
+template <>
+Void ParameterSetMap<TComPPS>::setID(TComPPS* parameterSet, const Int psId)
+{
+  parameterSet->setPPSId(psId);
+}
+
+template <>
+Void ParameterSetMap<TComSPS>::setID(TComSPS* parameterSet, const Int psId)
+{
+  parameterSet->setSPSId(psId);
 }
 
@@ -4941,16 +5079,16 @@
 }
 
-Void calculateParameterSetChangedFlag(Bool &bChanged, const std::vector<UChar> *pOldData, const std::vector<UChar> &newData)
+Void calculateParameterSetChangedFlag(Bool &bChanged, const std::vector<UChar> *pOldData, const std::vector<UChar> *pNewData)
 {
   if (!bChanged)
   {
-    if ((pOldData==0 && pOldData!=0) || (pOldData!=0 && pOldData==0))
+    if ((pOldData==0 && pNewData!=0) || (pOldData!=0 && pNewData==0))
     {
       bChanged=true;
     }
-    else if (pOldData!=0 && pOldData!=0)
+    else if (pOldData!=0 && pNewData!=0)
     {
       // compare the two
-      if (pOldData->size() != pOldData->size())
+      if (pOldData->size() != pNewData->size())
       {
         bChanged=true;
@@ -4958,5 +5096,5 @@
       else
       {
-        const UChar *pNewDataArray=&(newData)[0];
+        const UChar *pNewDataArray=&(*pNewData)[0];
         const UChar *pOldDataArray=&(*pOldData)[0];
         if (memcmp(pOldDataArray, pNewDataArray, pOldData->size()))
Index: /trunk/source/Lib/TLibCommon/TComSlice.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComSlice.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComSlice.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -1315,5 +1315,5 @@
 
   Bool    getViewCompLayerPresentFlag (Int i, Bool d ) const                    { return  m_viewCompLayerPresentFlag[ getVoiInVps(i) ][d]; }
-  Bool    getViewCompLayerId          (Int i, Bool d ) const                    { return  m_viewCompLayerId         [ getVoiInVps(i) ][d]; }
+  Int     getViewCompLayerId          (Int i, Bool d ) const                    { return  m_viewCompLayerId         [ getVoiInVps(i) ][d]; }
 #endif
   Bool    getDependencyFlag( Int i, Int j ) const                               { return m_dependencyFlag[i][j]; }
@@ -1352,9 +1352,16 @@
 
   Bool    isOutputLayer( Int outLayerSetIdx, Int layerIdInNuh )  const;    
+  Bool    isIndependendNonBaseLayer    ( Int layerIdInNuh )      const    {       return (layerIdInNuh > 0) && getNumRefLayers( layerIdInNuh ) == 0 ; };
+#if NH_3D
+  Bool    isFirstDepthLayer            ( Int layerIdInNuh )      const;
+#endif
+
   Void    deriveLayerSetLayerIdList();
 
   Int     olsIdxToLsIdx( Int i )                                       const    { return ( i < getNumLayerSets() ) ? i  : getLayerSetIdxForOlsMinus1( i ) + 1 ; };
+
   Void    initTargetLayerIdLists  ( );
   Void    deriveTargetLayerIdList ( Int i );
+  
   std::vector<Int> getTargetDecLayerIdList( Int targetDecLayerSetIdx ) const     { return m_targetDecLayerIdLists[targetDecLayerSetIdx]; }; 
   std::vector<Int> getTargetOptLayerIdList( Int targetOptLayerSetIdx ) const     { return m_targetOptLayerIdLists[targetOptLayerSetIdx]; }; 
@@ -1377,8 +1384,10 @@
   // helpers
   Void    printPTL()                                                   const;
+  Void    printRepFormat()                                             const;
   Void    printLayerDependencies()                                     const;
   Void    printScalabilityId()                                         const;
   Void    printLayerSets()                                             const;
 
+  IntAry1d  getLayersOfVpsPtl( Int idxOfVpsPtl )                       const;
 
   /// VPS EXTENSION 2 SYNTAX ELEMENTS
@@ -1427,10 +1436,10 @@
 #endif
 
-  template <typename T, typename S, typename U> Void xPrintArray( const TChar* name, Int numElemDim1, U idx, S numElemDim2, T vec, Bool printNumber, Bool printIdx = true ) const
+  template <typename T, typename S, typename U> Void xPrintArray( const TChar* name, Int numElemDim1, U idx, S numElemDim2, T vec, Bool printNumber, Bool printIdx = true, Int elemDist = 3 ) const
   {
     std::cout << std::endl; 
     for (Int j = 0; j < numElemDim1; j++ )
     { 
-      std::cout << std::right << std::setw(27) << name; 
+      std::cout << std::right << std::setw(40) << name; 
       if (printIdx)
       {
@@ -1454,5 +1463,5 @@
       for (Int i = 0; i < numElemDim2[j]; i++)
       {
-        std::cout << std::right << std::setw(3) << vec[j][i];
+        std::cout << std::right << std::setw(elemDist) << vec[j][i];
       }   
       std::cout << std::endl; 
@@ -1460,16 +1469,17 @@
   }
 
-  template <typename T> Void xPrintArray( const char* name, Int numElem, T vec, Bool printNumber  )  const
+  template <typename T> Void xPrintArray( const char* name, Int numElem, T vec, Bool printNumber, Int elemDist = 3  )  const
   {
     std::vector<Int> numElemDim2(1, numElem);    
     std::vector<T>   vec2       (1,  vec    );
     std::vector<Int> idx2       (0); 
-    xPrintArray( name, 1, idx2, numElemDim2, vec2, printNumber, false );
+    xPrintArray( name, 1, idx2, numElemDim2, vec2, printNumber, false, elemDist );
   }
 
 #endif
+
 };
 
-#if NH_3D_DLT
+#if NH_3D
 class TComDLT
 {
@@ -1491,5 +1501,5 @@
 
 public:
-  TComDLT();
+  TComDLT( );
   ~TComDLT();
   
@@ -1811,18 +1821,18 @@
     for (Int d = 0; d < 2; d++)
     {
-      m_ivDiMcEnabledFlag          [d] = false; 
-      m_ivMvScalEnabledFlag       [d] = false; 
-      m_log2IvmcSubPbSizeMinus3   [d] = 3; 
-      m_ivResPredEnabledFlag         [d] = false; 
-      m_depthRefEnabledFlag   [d] = false; 
-      m_vspMcEnabledFlag [d] = false; 
-      m_dbbpEnabledFlag [d] = false; 
-      m_texMcEnabledFlag               [d] = false; 
-      m_log2TexmcSubPbSizeMinus3[d] = 3; 
-      m_intraContourEnabledFlag      [d] = false; 
+      m_ivDiMcEnabledFlag               [d] = false; 
+      m_ivMvScalEnabledFlag             [d] = false; 
+      m_log2IvmcSubPbSizeMinus3         [d] = 3; 
+      m_ivResPredEnabledFlag            [d] = false; 
+      m_depthRefEnabledFlag             [d] = false; 
+      m_vspMcEnabledFlag                [d] = false; 
+      m_dbbpEnabledFlag                 [d] = false; 
+      m_texMcEnabledFlag                [d] = false; 
+      m_log2TexmcSubPbSizeMinus3        [d] = 3; 
+      m_intraContourEnabledFlag         [d] = false; 
       m_intraDcOnlyWedgeEnabledFlag     [d] = false; 
-      m_cqtCuPartPredEnabledFlag            [d] = false; 
+      m_cqtCuPartPredEnabledFlag        [d] = false; 
       m_interDcOnlyEnabledFlag          [d] = false; 
-      m_skipIntraEnabledFlag    [d] = false;   
+      m_skipIntraEnabledFlag            [d] = false;   
     }
   }
@@ -1917,5 +1927,5 @@
 #endif
   Bool             m_bLongTermRefsPresent;
-  Bool             m_TMVPFlagsPresent;
+  Bool             m_SPSTemporalMVPEnabledFlag;
   Int              m_numReorderPics[MAX_TLAYER];
 
@@ -1974,5 +1984,5 @@
   UInt             m_forceDecodeBitDepth; // 0 = do not force the decoder's bit depth, other = force the decoder's bit depth to this value (best effort decoding)
 #endif
-#if NH_MV
+#if NH_MV  
   TComVPS*         m_pcVPS; 
   // SPS           
@@ -2001,4 +2011,5 @@
 #if NH_MV           
   Int              m_layerId; 
+  TComRepFormat*   m_inferredRepFormat;
 #endif
 
@@ -2025,4 +2036,5 @@
   UInt                   getPicWidthInLumaSamples() const                                                { return  m_picWidthInLumaSamples;                                     }
   Void                   setPicHeightInLumaSamples( UInt u )                                             { m_picHeightInLumaSamples = u;                                        }
+  
   UInt                   getPicHeightInLumaSamples() const                                               { return  m_picHeightInLumaSamples;                                    }
 
@@ -2092,8 +2104,8 @@
   Void                   setLongTermRefsPresent(Bool b)                                                  { m_bLongTermRefsPresent=b;                                            }
 #endif
-  Bool                   getTMVPFlagsPresent() const                                                     { return m_TMVPFlagsPresent;                                           }
-  Void                   setTMVPFlagsPresent(Bool b)                                                     { m_TMVPFlagsPresent=b;                                                }
-#if NH_MV
-  Bool                   getSpsTemporalMvpEnabledFlag() const                                            { return m_TMVPFlagsPresent;                                           }
+  Bool                   getSPSTemporalMVPEnabledFlag() const                                            { return m_SPSTemporalMVPEnabledFlag;                                  }
+  Void                   setSPSTemporalMVPEnabledFlag(Bool b)                                            { m_SPSTemporalMVPEnabledFlag=b;                                       }
+#if NH_MV
+  Bool                   getSpsTemporalMvpEnabledFlag() const                                            { return m_SPSTemporalMVPEnabledFlag;                                           }
 #endif
   // physical transform
@@ -2103,4 +2115,5 @@
   // Bit-depth
   Int                    getBitDepth(ChannelType type) const                                             { return m_bitDepths.recon[type];                                      }
+
   Void                   setBitDepth(ChannelType type, Int u )                                           { m_bitDepths.recon[type] = u;                                         }
 #if O0043_BEST_EFFORT_DECODING
@@ -2219,5 +2232,5 @@
   // Inference          
                         
-  Void                   inferRepFormat( TComVPS* vps, Int layerIdCurr, Bool encoder );
+  Void                   inferRepFormat  ( TComVPS* vps, Int layerIdCurr, Bool alreadySet );
   Void                   inferScalingList( const TComSPS* spsSrc );
                         
@@ -2358,5 +2371,5 @@
   Bool             m_useWeightedBiPred;                 //!< Use of Weighting Bi-Prediction (B_SLICE)
   Bool             m_OutputFlagPresentFlag;             //!< Indicates the presence of output_flag in slice header
-  Bool             m_TransquantBypassEnableFlag;        //!< Indicates presence of cu_transquant_bypass_flag in CUs.
+  Bool             m_TransquantBypassEnabledFlag;       //!< Indicates presence of cu_transquant_bypass_flag in CUs.
   Bool             m_useTransformSkip;
   Bool             m_dependentSliceSegmentsEnabledFlag; //!< Indicates the presence of dependent slices
@@ -2371,5 +2384,5 @@
   std::vector<Int> m_tileRowHeight;
 
-  Bool             m_signHideFlag;
+  Bool             m_signDataHidingEnabledFlag;
 
   Bool             m_cabacInitPresentFlag;
@@ -2379,5 +2392,5 @@
   Bool             m_deblockingFilterControlPresentFlag;
   Bool             m_deblockingFilterOverrideEnabledFlag;
-  Bool             m_picDisableDeblockingFilterFlag;
+  Bool             m_ppsDeblockingFilterDisabledFlag;
   Int              m_deblockingFilterBetaOffsetDiv2;    //< beta offset for deblocking filter
   Int              m_deblockingFilterTcOffsetDiv2;      //< tc offset for deblocking filter
@@ -2403,5 +2416,5 @@
 #endif
 
-#if NH_3D_DLT
+#if NH_3D
   TComDLT                m_cDLT;
 #endif
@@ -2428,5 +2441,5 @@
   UInt                   getMaxCuDQPDepth() const                                         { return m_uiMaxCuDQPDepth;                     }
 
-#if NH_3D_DLT
+#if NH_3D
   Void                   setDLT( TComDLT cDLT )                                           { m_cDLT = cDLT;                                }
   const TComDLT*         getDLT() const                                                   { return &m_cDLT;                               }
@@ -2467,6 +2480,6 @@
   Void                   setOutputFlagPresentFlag( Bool b )                               { m_OutputFlagPresentFlag = b;                  }
   Bool                   getOutputFlagPresentFlag() const                                 { return m_OutputFlagPresentFlag;               }
-  Void                   setTransquantBypassEnableFlag( Bool b )                          { m_TransquantBypassEnableFlag = b;             }
-  Bool                   getTransquantBypassEnableFlag() const                            { return m_TransquantBypassEnableFlag;          }
+  Void                   setTransquantBypassEnabledFlag( Bool b )                         { m_TransquantBypassEnabledFlag = b;            }
+  Bool                   getTransquantBypassEnabledFlag() const                           { return m_TransquantBypassEnabledFlag;         }
 
   Bool                   getUseTransformSkip() const                                      { return m_useTransformSkip;                    }
@@ -2493,6 +2506,6 @@
   UInt                   getTileRowHeight(UInt rowIdx) const                              { return m_tileRowHeight[rowIdx];               }
 
-  Void                   setSignHideFlag( Bool signHideFlag )                             { m_signHideFlag = signHideFlag;                }
-  Bool                   getSignHideFlag() const                                          { return m_signHideFlag;                        }
+  Void                   setSignDataHidingEnabledFlag( Bool b )                           { m_signDataHidingEnabledFlag = b;              }
+  Bool                   getSignDataHidingEnabledFlag() const                             { return m_signDataHidingEnabledFlag;           }
 
   Void                   setCabacInitPresentFlag( Bool flag )                             { m_cabacInitPresentFlag = flag;                }
@@ -2502,6 +2515,6 @@
   Void                   setDeblockingFilterOverrideEnabledFlag( Bool val )               { m_deblockingFilterOverrideEnabledFlag = val;  }
   Bool                   getDeblockingFilterOverrideEnabledFlag() const                   { return m_deblockingFilterOverrideEnabledFlag; }
-  Void                   setPicDisableDeblockingFilterFlag(Bool val)                      { m_picDisableDeblockingFilterFlag = val;       } //!< set offset for deblocking filter disabled
-  Bool                   getPicDisableDeblockingFilterFlag() const                        { return m_picDisableDeblockingFilterFlag;      } //!< get offset for deblocking filter disabled
+  Void                   setPPSDeblockingFilterDisabledFlag(Bool val)                     { m_ppsDeblockingFilterDisabledFlag = val;      } //!< set offset for deblocking filter disabled
+  Bool                   getPPSDeblockingFilterDisabledFlag() const                       { return m_ppsDeblockingFilterDisabledFlag;     } //!< get offset for deblocking filter disabled
   Void                   setDeblockingFilterBetaOffsetDiv2(Int val)                       { m_deblockingFilterBetaOffsetDiv2 = val;       } //!< set beta offset for deblocking filter
   Int                    getDeblockingFilterBetaOffsetDiv2() const                        { return m_deblockingFilterBetaOffsetDiv2;      } //!< get beta offset for deblocking filter
@@ -2726,26 +2739,18 @@
   Int        m_pocMsbCycleVal;
   Bool       m_pocMsbValRequiredFlag;
+#endif
 
 #if NH_3D
   IntAry2d   m_aaiCodedScale ;
   IntAry2d   m_aaiCodedOffset;
-#endif
-#if NH_3D_TMVP
+
   Int        m_aiAlterRefIdx   [2]; 
-#endif
-#if NH_3D_ARP
   Bool       m_arpRefPicAvailable[2][MAX_NUM_LAYERS];
   TComList<TComPic*> * m_pBaseViewRefPicList[MAX_NUM_LAYERS];
   UInt        m_nARPStepNum; 
   Int         m_aiFirstTRefIdx    [2];   
-#endif
-#if NH_3D
   std::vector<Int> m_pocsInCurrRPSs; 
-#endif
-#if NH_3D_IC
   Bool       m_bApplyIC;
   Bool       m_icSkipParseFlag;
-#endif
-#if NH_3D
   std::vector<Int> m_inCmpRefViewIdcs;
   Bool       m_inCmpPredAvailFlag; 
@@ -2753,19 +2758,11 @@
   Bool       m_cpAvailableFlag; 
   Int        m_numViews; 
-#endif
-#if NH_3D_QTL
   TComPic*   m_ivPicsCurrPoc [2][MAX_NUM_LAYERS];  
-#endif
-#if NH_3D
   Int**      m_depthToDisparityB; 
   Int**      m_depthToDisparityF; 
   Bool       m_bApplyDIS;
-#endif
-#endif
-#if NH_3D_IC
   Int*       m_aICEnableCandidate;
   Int*       m_aICEnableNum;
-#endif       
-#if NH_3D   
+
   Int        m_iDefaultRefViewIdx;
   Bool       m_bDefaultRefViewIdxAvailableFlag;
@@ -2844,4 +2841,5 @@
   Int                         getNumRefIdx( RefPicList e ) const                     { return m_aiNumRefIdx[e];                                      }
   TComPic*                    getPic()                                               { return m_pcPic;                                               }
+  const TComPic*              getPic() const                                         { return m_pcPic;                                               }
   TComPic*                    getRefPic( RefPicList e, Int iRefIdx)                  { return m_apcRefPicList[e][iRefIdx];                           }
   const TComPic*              getRefPic( RefPicList e, Int iRefIdx) const            { return m_apcRefPicList[e][iRefIdx];                           }
@@ -2855,10 +2853,6 @@
   Int                         getNumCurCmpLIds( )                      const         { return (Int) m_inCmpRefViewIdcs.size();                       }
   TComPic*                    getIvPic( Bool depthFlag, Int viewIndex) const         { return  m_ivPicsCurrPoc[ depthFlag ? 1 : 0 ][ viewIndex ];    }
-#endif
-#if NH_3D_QTL
   TComPic*                    getTexturePic       ()                                 { return  m_ivPicsCurrPoc[0][ m_viewIndex ];                    }
 
-#endif                            
-#if NH_3D_IC                                                                                                                                          
   Void                        setApplyIC( Bool b )                                   { m_bApplyIC = b;                                               }
   Bool                        getApplyIC()                                           { return m_bApplyIC;                                            }
@@ -2867,6 +2861,5 @@
   Void                        setIcSkipParseFlag( Bool b )                           { m_icSkipParseFlag = b;                                        }
   Bool                        getIcSkipParseFlag()                                   { return m_icSkipParseFlag;                                     }
-#endif                                                                                                                                               
-#if NH_3D_ARP                                                                                                                                         
+
   Void                        setBaseViewRefPicList( TComList<TComPic*> *pListPic, Int iViewIdx )      { m_pBaseViewRefPicList[iViewIdx] = pListPic; }                  
   Void                        setARPStepNum( TComPicLists*ivPicLists );                                                                              
@@ -3155,10 +3148,7 @@
 
 #if NH_3D
-#if NH_3D_TMVP
   Void                        generateAlterRefforTMVP ();   
   Void                        setAlterRefIdx          ( RefPicList e, Int i )        { m_aiAlterRefIdx[e]    = i;                                    }
   Int                         getAlterRefIdx          ( RefPicList e )               { return  m_aiAlterRefIdx[e];                                   }
-#endif                                                                                                                                               
-#if NH_3D_ARP                                                                                                                                         
   Int                         getFirstTRefIdx        ( RefPicList e )                { return  m_aiFirstTRefIdx[e];                                  }
   Void                        setFirstTRefIdx        ( RefPicList e, Int i )         { m_aiFirstTRefIdx[e]    = i;                                   }
@@ -3166,5 +3156,4 @@
   Bool                        getArpRefPicAvailable  ( RefPicList e, Int viewIdx)    { return m_arpRefPicAvailable[e][getVPS()->getLayerIdInNuh(viewIdx, false, 0 )]; }
   IntAry1d                    getPocsInCurrRPSs()                                    { return m_pocsInCurrRPSs;                                      } 
-#endif                        
 #endif
 #if NH_3D_VSO || NH_3D
@@ -3192,14 +3181,11 @@
   Int                         getCpInvOff( Int j )                                   { return m_aaiCodedOffset[1][j];                                }
                                                                                                                                                         
-#endif
-#if NH_3D_QTL
   Void                        setIvPicLists( TComPicLists* m_ivPicLists );                                                                              
-#endif
-#if NH_3D
+
   Void                        setDepthToDisparityLUTs();                                                                                                
                                                                                                                                                         
   Int*                        getDepthToDisparityB( Int refViewIdx )                 { return m_depthToDisparityB[ getVPS()->getVoiInVps( refViewIdx) ];}
   Int*                        getDepthToDisparityF( Int refViewIdx )                 { return m_depthToDisparityF[ getVPS()->getVoiInVps( refViewIdx) ];}
-#if NH_3D_IC                                                                                                                                             
+
   Void                        setICEnableCandidate( Int* icEnableCandidate)          { m_aICEnableCandidate = icEnableCandidate;                     }
   Void                        setICEnableNum( Int* icEnableNum)                      { m_aICEnableNum = icEnableNum;                                 }
@@ -3209,5 +3195,4 @@
   Int                         getICEnableCandidate( Int layer)                       { return  m_aICEnableCandidate[ layer ];                        }
   Int                         getICEnableNum( Int layer)                             { return m_aICEnableNum[ layer ];                               }
-#endif
 #endif
 // Additional slice header syntax elements
@@ -3335,5 +3320,5 @@
   Int                         getMpiSubPbSize           ( )                          { return m_mpiSubPbSize           ;                             };
   Int                         getSubPbSize              ( )                          { return m_subPbSize              ;                             };
-#if NH_3D_NBDV
+
   Int                         getDefaultRefViewIdx()                                 { return m_iDefaultRefViewIdx;                                  }
   Void                        setDefaultRefViewIdx(Int iViewIdx)                     { m_iDefaultRefViewIdx = iViewIdx;                              }
@@ -3343,5 +3328,4 @@
   Void                        setDefaultRefView( );
 #endif
-#endif
 #if NH_MV
  TComPic*                     getRefPicSetInterLayer( Int setIdc, Int i ) const; 
@@ -3364,5 +3348,5 @@
 
 
-Void calculateParameterSetChangedFlag(Bool &bChanged, const std::vector<UChar> *pOldData, const std::vector<UChar> &newData);
+Void calculateParameterSetChangedFlag(Bool &bChanged, const std::vector<UChar> *pOldData, const std::vector<UChar> *pNewData);
 
 template <class T> class ParameterSetMap
@@ -3390,5 +3374,18 @@
   }
 
-  Void storePS(Int psId, T *ps, const std::vector<UChar> &naluData)
+  T *allocatePS(const Int psId)
+  {
+    assert ( psId < m_maxId );
+    if ( m_paramsetMap.find(psId) == m_paramsetMap.end() )
+    {
+      m_paramsetMap[psId].bChanged = true;
+      m_paramsetMap[psId].pNaluData=0;
+      m_paramsetMap[psId].parameterSet = new T;
+      setID(m_paramsetMap[psId].parameterSet, psId);
+    }
+    return m_paramsetMap[psId].parameterSet;
+  }
+
+  Void storePS(Int psId, T *ps, const std::vector<UChar> *pNaluData)
   {
     assert ( psId < m_maxId );
@@ -3398,5 +3395,5 @@
 
       // work out changed flag
-      calculateParameterSetChangedFlag(mapData.bChanged, mapData.pNaluData, naluData);
+      calculateParameterSetChangedFlag(mapData.bChanged, mapData.pNaluData, pNaluData);
       delete m_paramsetMap[psId].pNaluData;
       delete m_paramsetMap[psId].parameterSet;
@@ -3409,6 +3406,21 @@
       m_paramsetMap[psId].bChanged = false;
     }
+    if (pNaluData != 0)
+    {
       m_paramsetMap[psId].pNaluData=new std::vector<UChar>;
-    *(m_paramsetMap[psId].pNaluData) = naluData;
+      *(m_paramsetMap[psId].pNaluData) = *pNaluData;
+    }
+    else
+    {
+      m_paramsetMap[psId].pNaluData=0;
+    }
+  }
+
+  Void setChangedFlag(Int psId, Bool bChanged=true)
+  {
+    if ( m_paramsetMap.find(psId) != m_paramsetMap.end() )
+    {
+      m_paramsetMap[psId].bChanged=bChanged;
+    }
   }
 
@@ -3451,4 +3463,6 @@
   std::map<Int,MapData<T> > m_paramsetMap;
   Int                       m_maxId;
+
+  static Void setID(T* parameterSet, const Int psId);
 };
 
@@ -3460,5 +3474,5 @@
 
   //! store sequence parameter set and take ownership of it
-  Void           storeVPS(TComVPS *vps, const std::vector<UChar> &naluData) { m_vpsMap.storePS( vps->getVPSId(), vps, naluData); };
+  Void           storeVPS(TComVPS *vps, const std::vector<UChar> &naluData) { m_vpsMap.storePS( vps->getVPSId(), vps, &naluData); };
   //! get pointer to existing video parameter set
   TComVPS*       getVPS(Int vpsId)                                           { return m_vpsMap.getPS(vpsId); };
@@ -3468,5 +3482,5 @@
 
   //! store sequence parameter set and take ownership of it
-  Void           storeSPS(TComSPS *sps, const std::vector<UChar> &naluData) { m_spsMap.storePS( sps->getSPSId(), sps, naluData); };
+  Void           storeSPS(TComSPS *sps, const std::vector<UChar> &naluData) { m_spsMap.storePS( sps->getSPSId(), sps, &naluData); };
   //! get pointer to existing sequence parameter set
   TComSPS*       getSPS(Int spsId)                                           { return m_spsMap.getPS(spsId); };
@@ -3476,5 +3490,5 @@
 
   //! store picture parameter set and take ownership of it
-  Void           storePPS(TComPPS *pps, const std::vector<UChar> &naluData) { m_ppsMap.storePS( pps->getPPSId(), pps, naluData); };
+  Void           storePPS(TComPPS *pps, const std::vector<UChar> &naluData) { m_ppsMap.storePS( pps->getPPSId(), pps, &naluData); };
   //! get pointer to existing picture parameter set
   TComPPS*       getPPS(Int ppsId)                                           { return m_ppsMap.getPS(ppsId); };
@@ -3502,13 +3516,26 @@
 
 #if NH_MV  
-  const TComSPS* getActiveSPS( Int layer )const { return m_spsMap.getPS(m_activeSPSId[layer]); };
+  const TComSPS* getActiveSPS( Int layer )const { return m_spsActiveForLayer.getPS(layer); };
 #else  
   const TComSPS* getActiveSPS()const { return m_spsMap.getPS(m_activeSPSId); };
 #endif
 
+#if NH_MV
+  Void          setSpsActiveForLayer( Int layer, TComSPS*& ps  )
+  {
+    TComSPS* psCopy = m_spsActiveForLayer.allocatePS( layer );
+    (*psCopy) = (*ps);
+    ps = psCopy;
+  }
+#endif
 protected:
   ParameterSetMap<TComVPS> m_vpsMap;
   ParameterSetMap<TComSPS> m_spsMap;
   ParameterSetMap<TComPPS> m_ppsMap;
+
+#if NH_MV
+  // As several SPS syntax elements be might inferred depending for the current layer, copies are stored for each layer  
+  ParameterSetMap<TComSPS> m_spsActiveForLayer;  
+#endif
 
   Int m_activeVPSId; // -1 for nothing active
Index: /trunk/source/Lib/TLibCommon/TComTU.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComTU.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComTU.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComTU.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComTU.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComTU.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComTrQuant.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComTrQuant.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -1153,8 +1153,6 @@
   if ( useRDOQ && (isLuma(compID) || RDOQ_CHROMA) )
   {
-#if T0196_SELECTIVE_RDOQ
     if ( !m_useSelectiveRDOQ || xNeedRDOQ( rTu, piCoef, compID, cQP ) )
     {
-#endif
 #if ADAPTIVE_QP_SELECTION
       xRateDistOptQuant( rTu, piCoef, pDes, pArlDes, uiAbsSum, compID, cQP );
@@ -1162,5 +1160,4 @@
       xRateDistOptQuant( rTu, piCoef, pDes, uiAbsSum, compID, cQP );
 #endif
-#if T0196_SELECTIVE_RDOQ
     }
     else
@@ -1169,5 +1166,4 @@
       uiAbsSum = 0;
     }
-#endif
   }
   else
@@ -1243,5 +1239,5 @@
     } // for n
 
-    if( pcCU->getSlice()->getPPS()->getSignHideFlag() )
+    if( pcCU->getSlice()->getPPS()->getSignDataHidingEnabledFlag() )
     {
       if(uiAbsSum >= 2) //this prevents TUs with only one coefficient of value 1 from being tested
@@ -1254,5 +1250,4 @@
 }
 
-#if T0196_SELECTIVE_RDOQ
 Bool TComTrQuant::xNeedRDOQ( TComTU &rTu, TCoeff * pSrc, const ComponentID compID, const QpParam &cQP )
 {
@@ -1310,5 +1305,4 @@
   return false;
 }
-#endif
 
 Void TComTrQuant::xDeQuant(       TComTU        &rTu,
@@ -1434,7 +1428,5 @@
                           Bool  bUseRDOQ,
                           Bool  bUseRDOQTS,
-#if T0196_SELECTIVE_RDOQ
                           Bool  useSelectiveRDOQ,
-#endif
                           Bool  bEnc,
                           Bool  useTransformSkipFast
@@ -1448,7 +1440,5 @@
   m_useRDOQ      = bUseRDOQ;
   m_useRDOQTS    = bUseRDOQTS;
-#if T0196_SELECTIVE_RDOQ
   m_useSelectiveRDOQ = useSelectiveRDOQ;
-#endif
 #if ADAPTIVE_QP_SELECTION
   m_bUseAdaptQpSelect = bUseAdaptQpSelect;
@@ -2538,5 +2528,5 @@
 
 
-  if( pcCU->getSlice()->getPPS()->getSignHideFlag() && uiAbsSum>=2)
+  if( pcCU->getSlice()->getPPS()->getSignDataHidingEnabledFlag() && uiAbsSum>=2)
   {
     const Double inverseQuantScale = Double(g_invQuantScales[cQP.rem]);
Index: /trunk/source/Lib/TLibCommon/TComTrQuant.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComTrQuant.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComTrQuant.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -106,7 +106,5 @@
                               Bool useRDOQ                = false,
                               Bool useRDOQTS              = false,
-#if T0196_SELECTIVE_RDOQ
                               Bool useSelectiveRDOQ       = false,
-#endif
                               Bool bEnc                   = false,
                               Bool useTransformSkipFast   = false
@@ -219,7 +217,5 @@
   Bool     m_useRDOQ;
   Bool     m_useRDOQTS;
-#if T0196_SELECTIVE_RDOQ
   Bool     m_useSelectiveRDOQ;
-#endif
 #if ADAPTIVE_QP_SELECTION
   Bool     m_bUseAdaptQpSelect;
@@ -254,10 +250,8 @@
                const QpParam      &cQP );
 
-#if T0196_SELECTIVE_RDOQ
   Bool xNeedRDOQ(    TComTU       &rTu,
                      TCoeff      * pSrc,
                const ComponentID   compID,
                const QpParam      &cQP );
-#endif
 
   // RDOQ functions
Index: /trunk/source/Lib/TLibCommon/TComWedgelet.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComWedgelet.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComWedgelet.cpp	(revision 1413)
@@ -45,5 +45,5 @@
 using namespace std;
 
-#if NH_3D_DMM
+#if NH_3D
 TComWedgelet::TComWedgelet( UInt uiWidth, UInt uiHeight ) : m_uhXs     ( 0 ),
                                                             m_uhYs     ( 0 ),
@@ -345,3 +345,3 @@
   m_uiRefineIdx[uiPos] = uiIdx;  
 }
-#endif //NH_3D_DMM
+#endif //NH_3D
Index: /trunk/source/Lib/TLibCommon/TComWedgelet.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComWedgelet.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComWedgelet.h	(revision 1413)
@@ -43,5 +43,5 @@
 #include <vector>
 
-#if NH_3D_DMM
+#if NH_3D
 #define DMM_OFFSET     (NUM_INTRA_MODE+1) // offset for DMM and RBC mode numbers
 #define DMM_MIN_SIZE                   4  // min. block size for DMM and RBC modes
@@ -182,5 +182,5 @@
 // type definition wedgelet node list
 typedef std::vector<TComWedgeNode> WedgeNodeList;
-#endif //NH_3D_DMM
+#endif //NH_3D
 
 #endif // __TCOMWEDGELET__
Index: /trunk/source/Lib/TLibCommon/TComWeightPrediction.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComWeightPrediction.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComWeightPrediction.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComWeightPrediction.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibCommon/TComYuv.cpp
===================================================================
--- /trunk/source/Lib/TLibCommon/TComYuv.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComYuv.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -491,5 +491,5 @@
 #endif
 
-#if NH_3D_ARP
+#if NH_3D
 Void TComYuv::addARP( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth, UInt uiHeight, Bool bClip, const BitDepths &clipBitDepths )
 {
Index: /trunk/source/Lib/TLibCommon/TComYuv.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TComYuv.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TComYuv.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -208,5 +208,4 @@
 #endif
 #if NH_3D
-#if NH_3D_ARP
   Void         addARP                     ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight , Bool bClip, const BitDepths &clipBitDepths );
   Void         addARPLuma                 ( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, UInt uiAbsPartIdx, UInt uiWidth , UInt uiHeight , Bool bClip, const BitDepths &clipBitDepths );
@@ -221,5 +220,4 @@
   Void         xxMultiplyLine             ( Pel * pSrcDst , UInt uiWidth , UChar dW );
 #endif
-#endif
 
 };// END CLASS DEFINITION TComYuv
Index: /trunk/source/Lib/TLibCommon/TypeDef.h
===================================================================
--- /trunk/source/Lib/TLibCommon/TypeDef.h	(revision 1412)
+++ /trunk/source/Lib/TLibCommon/TypeDef.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -40,4 +40,6 @@
 #endif
 #include <vector>
+#include <utility>
+
 //! \ingroup TLibCommon
 //! \{
@@ -60,22 +62,16 @@
 #define NH_MV          ( HEVC_EXT != 0)
 #define NH_3D          ( HEVC_EXT == 2)
+
+#define NH_MV_ALLOW_NON_CONFORMING                0   // Allow non-conforming representations formats
 /////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////   FIXES AND INTEGRATIONS     ////////////////////////
 /////////////////////////////////////////////////////////////////////////////////////////
 #if NH_MV
-// Recent bug fixes
-#define RM_INIT_FIX                      1
-#define RM_FIX_SETUP                     1
-#define NH_MV_FIX_VERT_MV_REST                         1
-
-#define NH_3D_FIX_INTRA_SDC_VSO_OFF              1
-#define NH_3D_FIX_TICKET_114                     1  //Mismatch between text and software on DPB size syntax
-#define NH_3D_FIX_LEAK                           1
-// Things that needs to be fixed also in the Specification ...
+// Things that needs to be fixed also in the Specification ... CHECK if this has been done
 #define NH_MV_FIX_NO_REF_PICS_CHECK               1 // !!SPEC!!
 #define NH_MV_FIX_INIT_NUM_ACTIVE_REF_LAYER_PICS  1 // Derivation of NumActiveRefLayerPIcs. !!SPEC!!
 #define NH_MV_FIX_NUM_POC_TOTAL_CUR               1 // Derivation of NumPocTotalCur for IDR pictures. !!SPEC!!
 // To be done 
-#define NH_MV_HLS_PTL_LIMITS                       0
+#define NH_MV_HLS_PTL_LIMITS                      0
 #define NH_MV_SEI_TBD                             0
 #endif
@@ -83,15 +79,31 @@
 ///////////////////////////////////   MAJOR DEFINES   ///////////////////////////////////
 /////////////////////////////////////////////////////////////////////////////////////////
+
+
 #if NH_MV
 #define NH_MV_ENC_DEC_TRAC                 1  //< CU/PU level tracking
 #if NH_3D
-#define NH_3D_INTEGER_MV_DEPTH            1
-#define NH_3D_ENC_DEPTH                   1   // Encoder optimizations for depth, incl.
+#define NH_3D_VSO                          1  // VSO, View synthesis optimization, includes:
+// HHI_VSO
+// HHI_VSO_LS_TABLE_M23714 enable table base Lagrange multiplier optimization
+// SAIT_VSO_EST_A0033, JCT3V-A0033 modification 3
+// LGE_WVSO_A0119
+// SCU_HS_VSD_BUGFIX_IMPROV_G0163
+
+#define NH_3D_FAST_TEXTURE_ENCODING        1   // Fast merge mode decision and early CU determination for texture component of dependent view, JCT3V-E0173
+
+/////////////////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////   REMOVED DEFINES   /////////////////////////////////
+/////////////////////////////////////////////////////////////////////////////////////////
+
+//#define NH_3D_INTEGER_MV_DEPTH            1
+
+//#define NH_3D_ENC_DEPTH                   1   // Encoder optimizations for depth, incl.
                                               // HHI_DEPTH_INTRA_SEARCH_RAU_C0160
                                               // LG_ZEROINTRADEPTHRESI_A0087
                                               // HHI_DMM4_ENC_I0066
                                               // H_3D_FAST_DEPTH_INTRA
-#define NH_3D_FAST_TEXTURE_ENCODING       1   // Fast merge mode decision and early CU determination for texture component of dependent view, JCT3V-E0173
-#define NH_3D_ARP                         1  // Advanced residual prediction (ARP), JCT3V-D0177
+
+//#define NH_3D_ARP                         1  // Advanced residual prediction (ARP), JCT3V-D0177
                                              // QC_MTK_INTERVIEW_ARP_F0123_F0108 JCT3V-F0123; JCT3V-F0108
                                              // SHARP_ARP_REF_CHECK_F0105        ARP reference picture selection and DPB check
@@ -105,15 +117,9 @@
                                              // SEC_ARP_VIEW_REF_CHECK_J0037    Signaling iv_res_pred_weight_idx when the current slice has both view and temporal reference picture(s), JCT3V-J0037 item1
                                              // SEC_ARP_REM_ENC_RESTRICT_K0035    Removal of encoder restriction of ARP, JCT3V-K0035
-#define NH_3D_QTL                          1
-#define NH_3D_QTLPC                        1   // OL_QTLIMIT_PREDCODING_B0068 //JCT3V-B0068
+//#define NH_3D_QTL                          1
+//#define NH_3D_QTLPC                        1   // OL_QTLIMIT_PREDCODING_B0068 //JCT3V-B0068
                                               // HHI_QTLPC_RAU_OFF_C0160 JCT3V-C0160 change 2: quadtree limitation and predictive coding switched off in random access units
                                               // MTK_TEX_DEP_PAR_G0055 Texture-partition-dependent depth partition. JCT3V-G0055
-#define NH_3D_VSO                          1   // VSO, View synthesis optimization, includes:
-                                              // HHI_VSO
-                                              // HHI_VSO_LS_TABLE_M23714 enable table base Lagrange multiplier optimization
-                                              // SAIT_VSO_EST_A0033, JCT3V-A0033 modification 3
-                                              // LGE_WVSO_A0119
-                                              // SCU_HS_VSD_BUGFIX_IMPROV_G0163
-#define NH_3D_NBDV                         1   // Neighboring block disparity derivation
+//#define NH_3D_NBDV                         1   // Neighboring block disparity derivation
                                               // QC_JCT3V-A0097
                                               // LGE_DVMCP_A0126
@@ -131,5 +137,5 @@
                                               // MTK_TEXTURE_MRGCAND_BUGFIX_E0182  Bug fix for TEXTURE MERGING CANDIDATE     , JCT3V-E0182
                                               // LGE_SIMP_DISP_AVAIL_J0041    // Use 2 status for disparity availability - DISP_AVAILABLE and DISP_NONE
-#define NH_3D_IC                          1   // Illumination Compensation, JCT3V-B0045, JCT3V-C0046, JCT3V-D0060
+//#define NH_3D_IC                          1   // Illumination Compensation, JCT3V-B0045, JCT3V-C0046, JCT3V-D0060
                                               // Unifying rounding offset, for IC part, JCT3V-D0135
                                               // Full Pel Interpolation for Depth, HHI_FULL_PEL_DEPTH_MAP_MV_ACC
@@ -144,6 +150,6 @@
                                               // SEC_IC_NEIGHBOR_CLIP_I0080    // Clipping of neighboring sample position, JCT3V-I0080
                                               // LGE_CHROMA_IC_J0050_J0034
-#if NH_3D_NBDV
-#define NH_3D_NBDV_REF                     1   // Depth oriented neighboring block disparity derivation
+//#if NH_3D_NBDV
+//#define NH_3D_NBDV_REF                     1   // Depth oriented neighboring block disparity derivation
                                               // MTK_D0156
                                               // MERL_D0166: Reference view selection in NBDV & Bi-VSP
@@ -152,6 +158,6 @@
                                               // NTT_DoNBDV_VECTOR_CLIP_E0141 disparity vector clipping in DoNBDV, JCT3V-E0141 and JCT3V-E0209
                                               // SEC_VER_DONBDV_H0103          Vertical DV Restriction for DoNBDV
-#endif
-#define NH_3D_VSP                          1   // View synthesis prediction
+//#endif
+//#define NH_3D_VSP                          1   // View synthesis prediction
                                               // MERL_C0152: Basic VSP
                                               // MERL_D0166: Reference view selection in NBDV & Bi-VSP
@@ -171,6 +177,6 @@
                                               // MTK_MRG_LIST_SIZE_CLEANUP_J0059   1   // Include VSP for deriving merge candidate list size, JCT3V-J0059
                                               // SEC_A1_BASED_VSP_J0039            1   // Removal of redundant VSP in Merge list
-#define NH_3D_MLC                          1
-#define NH_3D_IV_MERGE                     1  // Inter-view motion merge candidate
+//#define NH_3D_MLC                          1
+//#define NH_3D_IV_MERGE                     1  // Inter-view motion merge candidate
                                               // HHI_INTER_VIEW_MOTION_PRED
                                               // SAIT_IMPROV_MOTION_PRED_M24829, improved inter-view motion vector prediction
@@ -193,11 +199,11 @@
                                               // SEC_SIMP_SHIFTED_DV_I0086     Simplification of Shifted DV candidate, JCT3V-I0086
                                               // SEC_SHIFTED_IVMC_POS_K0036    Position Derivation for Shifted-IVMC, JCT3V-K0036
-#define NH_3D_TEXT_MERGE                  1
+//#define NH_3D_TEXT_MERGE                  1
                                               // TEXTURE MERGING CANDIDATE     , JCT3V-C0137
                                               // EC_MPI_ENABLING_MERGE_F0150, MPI flag in VPS and enabling in Merge mode
-#define NH_3D_TMVP                        1   // QC_TMVP_C0047
+//#define NH_3D_TMVP                        1   // QC_TMVP_C0047
                                               // Sony_M23639
                                               // H_3D_TMVP_SCALING_FIX_K0053       1   // QC/CY for K0053
-#define NH_3D_DMM                         1   // Depth modeling modes
+//#define NH_3D_DMM                         1   // Depth modeling modes
                                               // HHI_DMM_PRED_TEX
                                               // HHI_DMM_WEDGE_INTRA
@@ -223,5 +229,5 @@
                                               // MTK_DMM_SIM_J0035
                                               // SHARP_DMM_CLEAN_K0042             1   // Generate DMM pattern with rotation
-#define NH_3D_DLT                         1   // Depth Lookup Table
+//#define NH_3D_DLT                         1   // Depth Lookup Table
                                               // HHI_DELTADC_DLT_D0035
                                               // LGE_PRED_RES_CODING_DLT_DOMAIN_F0159 JCT3V-F0159
@@ -231,6 +237,6 @@
                                               // RWTH_DLT_CLIP_I0057
                                               // SHARP_DLT_SIMP_J0029 DLT(DepthValue2Idx[]) table derivation cleanup
-#define NH_3D_SDC_INTRA                   1   // Segment-wise DC Coding method for INTRA
-#define NH_3D_SDC_INTER                   1   // Segment-wise DC Coding method for INTER
+//#define NH_3D_SDC_INTRA                   1   // Segment-wise DC Coding method for INTRA
+//#define NH_3D_SDC_INTER                   1   // Segment-wise DC Coding method for INTER
                                               // RWTH_SDC_DLT_B0036
                                               // INTEL_SDC64_D0193
@@ -252,10 +258,10 @@
                                               // LGE_INTER_SDC_E0156 Enable inter SDC for depth coding
                                               // SEC_INTER_SDC_G0101 Improved inter SDC with multiple DC candidates
-#define NH_3D_SPIVMP                       1   // H_3D_SPIVMP JCT3V-F0110: Sub-PU level inter-view motion prediction
+//#define NH_3D_SPIVMP                       1   // H_3D_SPIVMP JCT3V-F0110: Sub-PU level inter-view motion prediction
                                               // SEC_SPIVMP_MCP_SIZE_G0077, Apply SPIVMP only to 2Nx2N partition, JCT3V-G0077
                                               // QC_SPIVMP_MPI_G0119 Sub-PU level MPI merge candidate
                                               // Simplification on Sub-PU level temporal interview motion prediction
                                               // MPI_SUBPU_DEFAULT_MV_H0077_H0099_H0111_H0133
-#define NH_3D_DBBP                         1   // DBBP: Depth-based Block Partitioning and Merging
+//#define NH_3D_DBBP                         1   // DBBP: Depth-based Block Partitioning and Merging
                                               // MTK_DBBP_AMP_REM_H0072
                                               // RWTH_DBBP_NO_SPU_H0057
@@ -270,7 +276,6 @@
                                               // RWTH_DBBP_NO_SATD_K0028
                                               // HS_DBBP_CLEAN_K0048
-#define NH_3D_DIS                         1   // Depth intra skip
+//#define NH_3D_DIS                         1   // Depth intra skip
                                               // SEC_DEPTH_INTRA_SKIP_MODE_K0033  Depth intra skip mode
-#define H_3D_FCO                          0   // Flexible coding order for 3D
 // OTHERS
                                               // MTK_SONY_PROGRESSIVE_MV_COMPRESSION_E0170 // Progressive MV Compression, JCT3V-E0170
@@ -315,21 +320,21 @@
 #endif
 ////   ****** NEIGHBOURING BLOCK-BASED DISPARITY VECTOR  *********
-#if NH_3D_NBDV
+#if NH_3D
 #define DVFROM_LEFT                       0
 #define DVFROM_ABOVE                      1
 #define IDV_CANDS                         2
-#endif
+
 /////////////////////////////////////////////////////////////////////////////////////
 /// GT: Move values which are not flags to CommonDef.h and convert to static int !!
 ///////////////////////////////////////////////////////////////////////////////////
 ///// ***** ILLUMATION COMPENSATION *********
-#if NH_3D_IC
+
 #define IC_REG_COST_SHIFT                 7
 #define IC_CONST_SHIFT                    5
 #define IC_SHIFT_DIFF                     12
 #define IC_LOW_LATENCY_ENCODING_THRESHOLD 0.1 // Threshold for low-latency IC encoding in JCT3V-H0086
-#endif
+
 ///// ***** DEPTH BASED BLOCK PARTITIONING *********
-#if NH_3D_DBBP
+
 #define DBBP_INVALID_SHORT                (-4)
 #endif
@@ -358,12 +363,6 @@
 #endif
 
-#if NH_MV
-#if ENC_DEC_TRACE
-#define GT_DEBUG   1
-#else
-#define GT_DEBUG   0
-#endif
-#endif
 #define DEC_NUH_TRACE                                     0 ///< When trace enabled, enable tracing of NAL unit headers at the decoder (currently not possible at the encoder)
+
 #define PRINT_RPS_INFO                                    0 ///< Enable/disable the printing of bits used to send the RPS.
 // ====================================================================================================================
@@ -371,13 +370,28 @@
 // ====================================================================================================================
 #define DECODER_CHECK_SUBSTREAM_AND_SLICE_TRAILING_BYTES  1 ///< TODO: integrate this macro into a broader conformance checking system.
-#define T0196_SELECTIVE_RDOQ                              1 ///< selective RDOQ
-#define U0040_MODIFIED_WEIGHTEDPREDICTION_WITH_BIPRED_AND_CLIPPING 1
-#define U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI    1 ///< Alternative transfer characteristics SEI message (JCTVC-U0033, with syntax naming from V1005)
-#define W0062_RECALCULATE_QP_TO_ALIGN_WITH_LAMBDA         0 ///< This recalculates QP to align with the derived lambda (same relation as for all intra coding is used). Currently disabled by default.
-#define OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP            1 ///< Adds command line option to reset SAO parameters after each IRAP.
-
+#define X0038_LAMBDA_FROM_QP_CAPABILITY                   ( HEVC_EXT == 0 ) ///< This approach derives lambda from QP+QPoffset+QPoffset2. QPoffset2 is derived from QP+QPoffset using a linear model that is clipped between 0 and 3.
+                                                            // To use this capability enable config parameter LambdaFromQpEnable
+                                                            // GT: This is currently disabled for MV-HEVC and 3D-HEVC. Enabling requires modifications of the cfg-files
+#define JCTVC_Y0038_PARAMS                                1
+
+#define JVET_E0059_FLOATING_POINT_QP_FIX                  1 ///< Replace floating point QP with a source-file frame number.
+#define JVET_G0101_QP_SWITCHING                           1 ///< After switching POC, increase base QP instead of frame level QP.
+
+#define JVET_F0064_MSSSIM                                 1 ///< Calculate MS-SSIM scores
+
+#ifndef EXTENSION_360_VIDEO
+#define EXTENSION_360_VIDEO                               0   ///< extension for 360/spherical video coding support; this macro should be controlled by makefile, as it would be used to control whether the library is built and linked
+#endif
+
+#define MCTS_ENC_CHECK                                    1  ///< Temporal MCTS encoder constraint and decoder checks. Also requires SEITMCTSTileConstraint to be enabled to enforce constraint
 // ====================================================================================================================
 // Tool Switches
 // ====================================================================================================================
+
+// Please also refer to "TDecConformance.h" for DECODER_PARTIAL_CONFORMANCE_CHECK
+
+#define REDUCED_ENCODER_MEMORY                            0 ///< When 1, the encoder will allocate TComPic memory when required and release it when no longer required.
+// GT: To be aligned
+
 #define ADAPTIVE_QP_SELECTION                             1 ///< G382: Adaptive reconstruction levels, non-normative part for adaptive QP selection
 #define AMP_ENC_SPEEDUP                                   1 ///< encoder only speed-up by AMP mode skipping
@@ -399,10 +413,12 @@
 #define RExt__HIGH_BIT_DEPTH_SUPPORT                                           0 ///< 0 (default) use data type definitions for 8-10 bit video, 1 = use larger data types to allow for up to 16-bit video (originally developed as part of N0188)
 #endif
-#define U0132_TARGET_BITS_SATURATION                      1 ///< Rate control with target bits saturation method
-#ifdef  U0132_TARGET_BITS_SATURATION
-#define V0078_ADAPTIVE_LOWER_BOUND                        1 ///< Target bits saturation with adaptive lower bound
-#endif
-#define W0038_DB_OPT                                      1 ///< adaptive DB parameter selection, LoopFilterOffsetInPPS and LoopFilterDisable are set to 0 and DeblockingFilterMetric=2;
-#define W0038_CQP_ADJ                                     1 ///< chroma QP adjustment based on TL, CQPTLAdjustEnabled is set to 1;
+
+#if defined __SSE2__ || defined __AVX2__ || defined __AVX__ || defined _M_AMD64 || defined _M_X64
+#define VECTOR_CODING__INTERPOLATION_FILTER               1 ///< enable vector coding for the interpolation filter. 1 (default if SSE possible) disable SSE vector coding. Should not affect RD costs/decisions. Code back-ported from JEM2.0.
+#define VECTOR_CODING__DISTORTION_CALCULATIONS            1 ///< enable vector coding for distortion calculations   1 (default if SSE possible) disable SSE vector coding. Should not affect RD costs/decisions. Code back-ported from JEM2.0.
+#else
+#define VECTOR_CODING__INTERPOLATION_FILTER               0 ///< enable vector coding for the interpolation filter. 0 (default if SSE not possible) disable SSE vector coding. Should not affect RD costs/decisions. Code back-ported from JEM2.0.
+#define VECTOR_CODING__DISTORTION_CALCULATIONS            0 ///< enable vector coding for distortion calculations   0 (default if SSE not possible) disable SSE vector coding. Should not affect RD costs/decisions. Code back-ported from JEM2.0.
+#endif
 
 // ====================================================================================================================
@@ -706,5 +722,5 @@
   MD_ABOVE_LEFT         ///< MVP of above left block
 };
-#if NH_3D_MLC
+#if NH_3D
 enum DefaultMergCandOrder
 {
@@ -858,6 +874,8 @@
 #if NH_MV
     ,MULTIVIEWMAIN = 6,
-#if NH_3D
     MAIN3D = 8,
+#if NH_MV_ALLOW_NON_CONFORMING
+    MULTIVIEWMAIN_NONCONFORMING = 29,
+    MAIN3D_NONCONFORMING= 31,
 #endif
 #endif
@@ -870,4 +888,5 @@
     MAIN = 0,
     HIGH = 1,
+    NUMBER_OF_TIERS = 2
   };
   enum Name
@@ -998,4 +1017,13 @@
   NAL_UNIT_INVALID,
 };
+
+enum LumaLevelToDQPMode
+{
+  LUMALVL_TO_DQP_DISABLED   = 0,
+  LUMALVL_TO_DQP_AVG_METHOD = 1, // use average of CTU to determine luma level
+  LUMALVL_TO_DQP_MAX_METHOD = 2,  // use maximum value of CTU to determine luma level
+  LUMALVL_TO_DQP_NUM_MODES  = 3
+};
+
 #if NH_MV
 /// scalability types
@@ -1159,4 +1187,23 @@
   UShort    whitePoint[2];
 };
+
+struct LumaLevelToDeltaQPMapping
+{
+  LumaLevelToDQPMode                 mode;             ///< use deltaQP determined by block luma level
+  Double                             maxMethodWeight;  ///< weight of max luma value when mode = 2
+  std::vector< std::pair<Int, Int> > mapping;          ///< first=luma level, second=delta QP.
+  Bool isEnabled() const { return mode!=LUMALVL_TO_DQP_DISABLED; }
+};
+
+struct WCGChromaQPControl
+{
+  Bool isEnabled() const { return enabled; }
+  Bool   enabled;         ///< Enabled flag (0:default)
+  Double chromaCbQpScale; ///< Chroma Cb QP Scale (1.0:default)
+  Double chromaCrQpScale; ///< Chroma Cr QP Scale (1.0:default)
+  Double chromaQpScale;   ///< Chroma QP Scale (0.0:default)
+  Double chromaQpOffset;  ///< Chroma QP Offset (0.0:default)
+};
+
 //! \}
 #endif
Index: /trunk/source/Lib/TLibDecoder/AnnexBread.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/AnnexBread.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/AnnexBread.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibDecoder/AnnexBread.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/AnnexBread.h	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/AnnexBread.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibDecoder/NALread.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/NALread.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/NALread.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibDecoder/NALread.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/NALread.h	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/NALread.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibDecoder/SEIread.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/SEIread.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/SEIread.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -201,7 +201,96 @@
     switch (payloadType)
     {
+    case SEI::BUFFERING_PERIOD:
+      if (!sps)
+      {
+        printf ("Warning: Found Buffering period SEI message, but no active SPS is available. Ignoring.");
+      }
+      else
+      {
+        sei = new SEIBufferingPeriod;
+        xParseSEIBufferingPeriod((SEIBufferingPeriod&) *sei, payloadSize, sps, pDecodedMessageOutputStream);
+      }
+      break;
+    case SEI::PICTURE_TIMING:
+      if (!sps)
+      {
+        printf ("Warning: Found Picture timing SEI message, but no active SPS is available. Ignoring.");
+      }
+      else
+      {
+        sei = new SEIPictureTiming;
+        xParseSEIPictureTiming((SEIPictureTiming&)*sei, payloadSize, sps, pDecodedMessageOutputStream);
+      }
+      break;
+    case SEI::PAN_SCAN_RECT:
+      sei = new SEIPanScanRect;
+      xParseSEIPanScanRect((SEIPanScanRect&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::FILLER_PAYLOAD:
+      sei = new SEIFillerPayload;
+      xParseSEIFillerPayload((SEIFillerPayload&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::USER_DATA_REGISTERED_ITU_T_T35:
+      sei = new SEIUserDataRegistered;
+      xParseSEIUserDataRegistered((SEIUserDataRegistered&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
     case SEI::USER_DATA_UNREGISTERED:
-      sei = new SEIuserDataUnregistered;
-      xParseSEIuserDataUnregistered((SEIuserDataUnregistered&) *sei, payloadSize, pDecodedMessageOutputStream);
+      sei = new SEIUserDataUnregistered;
+      xParseSEIUserDataUnregistered((SEIUserDataUnregistered&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::RECOVERY_POINT:
+      sei = new SEIRecoveryPoint;
+      xParseSEIRecoveryPoint((SEIRecoveryPoint&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::SCENE_INFO:
+      sei = new SEISceneInfo;
+      xParseSEISceneInfo((SEISceneInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::PICTURE_SNAPSHOT:
+      sei = new SEIPictureSnapshot;
+      xParseSEIPictureSnapshot((SEIPictureSnapshot&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::PROGRESSIVE_REFINEMENT_SEGMENT_START:
+      sei = new SEIProgressiveRefinementSegmentStart;
+      xParseSEIProgressiveRefinementSegmentStart((SEIProgressiveRefinementSegmentStart&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::PROGRESSIVE_REFINEMENT_SEGMENT_END:
+      sei = new SEIProgressiveRefinementSegmentEnd;
+      xParseSEIProgressiveRefinementSegmentEnd((SEIProgressiveRefinementSegmentEnd&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::FILM_GRAIN_CHARACTERISTICS:
+      sei = new SEIFilmGrainCharacteristics;
+      xParseSEIFilmGrainCharacteristics((SEIFilmGrainCharacteristics&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::POST_FILTER_HINT:
+      if (!sps)
+      {
+        printf ("Warning: post filter hint SEI message, but no active SPS is available. Ignoring.");
+      }
+      else
+      {
+        sei = new SEIPostFilterHint;
+        xParseSEIPostFilterHint((SEIPostFilterHint&) *sei, payloadSize, sps, pDecodedMessageOutputStream);
+      }
+      break;
+    case SEI::TONE_MAPPING_INFO:
+      sei = new SEIToneMappingInfo;
+      xParseSEIToneMappingInfo((SEIToneMappingInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::FRAME_PACKING:
+      sei = new SEIFramePacking;
+      xParseSEIFramePacking((SEIFramePacking&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::DISPLAY_ORIENTATION:
+      sei = new SEIDisplayOrientation;
+      xParseSEIDisplayOrientation((SEIDisplayOrientation&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::GREEN_METADATA:
+      sei = new SEIGreenMetadataInfo;
+      xParseSEIGreenMetadataInfo((SEIGreenMetadataInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::SOP_DESCRIPTION:
+      sei = new SEISOPDescription;
+      xParseSEISOPDescription((SEISOPDescription&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
     case SEI::ACTIVE_PARAMETER_SETS:
@@ -220,33 +309,31 @@
       }
       break;
-    case SEI::BUFFERING_PERIOD:
-      if (!sps)
-      {
-        printf ("Warning: Found Buffering period SEI message, but no active SPS is available. Ignoring.");
-      }
-      else
-      {
-        sei = new SEIBufferingPeriod;
-        xParseSEIBufferingPeriod((SEIBufferingPeriod&) *sei, payloadSize, sps, pDecodedMessageOutputStream);
-      }
-      break;
-    case SEI::PICTURE_TIMING:
-      if (!sps)
-      {
-        printf ("Warning: Found Picture timing SEI message, but no active SPS is available. Ignoring.");
-      }
-      else
-      {
-        sei = new SEIPictureTiming;
-        xParseSEIPictureTiming((SEIPictureTiming&)*sei, payloadSize, sps, pDecodedMessageOutputStream);
-      }
-      break;
-    case SEI::RECOVERY_POINT:
-      sei = new SEIRecoveryPoint;
-      xParseSEIRecoveryPoint((SEIRecoveryPoint&) *sei, payloadSize, pDecodedMessageOutputStream);
-      break;
-    case SEI::FRAME_PACKING:
-      sei = new SEIFramePacking;
-      xParseSEIFramePacking((SEIFramePacking&) *sei, payloadSize, pDecodedMessageOutputStream);
+    case SEI::TEMPORAL_LEVEL0_INDEX:
+      sei = new SEITemporalLevel0Index;
+      xParseSEITemporalLevel0Index((SEITemporalLevel0Index&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+#if NH_MV
+      xParseSEIScalableNesting((SEIScalableNesting&) *sei, nalUnitType, payloadSize, vps, sps, pDecodedMessageOutputStream);
+#else
+    case SEI::SCALABLE_NESTING:
+      sei = new SEIScalableNesting;
+      xParseSEIScalableNesting((SEIScalableNesting&) *sei, nalUnitType, payloadSize, sps, pDecodedMessageOutputStream);
+#endif
+      break;
+    case SEI::REGION_REFRESH_INFO:
+      sei = new SEIRegionRefreshInfo;
+      xParseSEIRegionRefreshInfo((SEIRegionRefreshInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::NO_DISPLAY:
+      sei = new SEINoDisplay;
+      xParseSEINoDisplay((SEINoDisplay&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::TIME_CODE:
+      sei = new SEITimeCode;
+      xParseSEITimeCode((SEITimeCode&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::MASTERING_DISPLAY_COLOUR_VOLUME:
+      sei = new SEIMasteringDisplayColourVolume;
+      xParseSEIMasteringDisplayColourVolume((SEIMasteringDisplayColourVolume&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
     case SEI::SEGM_RECT_FRAME_PACKING:
@@ -254,48 +341,11 @@
       xParseSEISegmentedRectFramePacking((SEISegmentedRectFramePacking&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
-    case SEI::DISPLAY_ORIENTATION:
-      sei = new SEIDisplayOrientation;
-      xParseSEIDisplayOrientation((SEIDisplayOrientation&) *sei, payloadSize, pDecodedMessageOutputStream);
-      break;
-    case SEI::TEMPORAL_LEVEL0_INDEX:
-      sei = new SEITemporalLevel0Index;
-      xParseSEITemporalLevel0Index((SEITemporalLevel0Index&) *sei, payloadSize, pDecodedMessageOutputStream);
-      break;
-    case SEI::REGION_REFRESH_INFO:
-      sei = new SEIGradualDecodingRefreshInfo;
-      xParseSEIRegionRefreshInfo((SEIGradualDecodingRefreshInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
-      break;
-    case SEI::NO_DISPLAY:
-      sei = new SEINoDisplay;
-      xParseSEINoDisplay((SEINoDisplay&) *sei, payloadSize, pDecodedMessageOutputStream);
-      break;
-    case SEI::TONE_MAPPING_INFO:
-      sei = new SEIToneMappingInfo;
-      xParseSEIToneMappingInfo((SEIToneMappingInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
-      break;
-    case SEI::SOP_DESCRIPTION:
-      sei = new SEISOPDescription;
-      xParseSEISOPDescription((SEISOPDescription&) *sei, payloadSize, pDecodedMessageOutputStream);
-      break;
-    case SEI::SCALABLE_NESTING:
-      sei = new SEIScalableNesting;
-#if NH_MV
-      xParseSEIScalableNesting((SEIScalableNesting&) *sei, nalUnitType, payloadSize, vps, sps, pDecodedMessageOutputStream);
-#else
-      xParseSEIScalableNesting((SEIScalableNesting&) *sei, nalUnitType, payloadSize, sps, pDecodedMessageOutputStream);
-#endif
-      break;
     case SEI::TEMP_MOTION_CONSTRAINED_TILE_SETS:
       sei = new SEITempMotionConstrainedTileSets;
       xParseSEITempMotionConstraintsTileSets((SEITempMotionConstrainedTileSets&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
-    case SEI::TIME_CODE:
-      sei = new SEITimeCode;
-      xParseSEITimeCode((SEITimeCode&) *sei, payloadSize, pDecodedMessageOutputStream);
-      break;
     case SEI::CHROMA_RESAMPLING_FILTER_HINT:
       sei = new SEIChromaResamplingFilterHint;
       xParseSEIChromaResamplingFilterHint((SEIChromaResamplingFilterHint&) *sei, payloadSize, pDecodedMessageOutputStream);
-      //}
       break;
     case SEI::KNEE_FUNCTION_INFO:
@@ -307,14 +357,28 @@
       xParseSEIColourRemappingInfo((SEIColourRemappingInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
-    case SEI::MASTERING_DISPLAY_COLOUR_VOLUME:
-      sei = new SEIMasteringDisplayColourVolume;
-      xParseSEIMasteringDisplayColourVolume((SEIMasteringDisplayColourVolume&) *sei, payloadSize, pDecodedMessageOutputStream);
-      break;
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
+    case SEI::DEINTERLACE_FIELD_IDENTIFICATION:
+      sei = new SEIDeinterlaceFieldIdentification;
+      xParseSEIDeinterlaceFieldIdentification((SEIDeinterlaceFieldIdentification&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::CONTENT_LIGHT_LEVEL_INFO:
+      sei = new SEIContentLightLevelInfo;
+      xParseSEIContentLightLevelInfo((SEIContentLightLevelInfo&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::DEPENDENT_RAP_INDICATION:
+      sei = new SEIDependentRAPIndication;
+      xParseSEIDependentRAPIndication((SEIDependentRAPIndication&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
+    case SEI::CODED_REGION_COMPLETION:
+      sei = new SEICodedRegionCompletion;
+      xParseSEICodedRegionCompletion((SEICodedRegionCompletion&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
     case SEI::ALTERNATIVE_TRANSFER_CHARACTERISTICS:
       sei = new SEIAlternativeTransferCharacteristics;
       xParseSEIAlternativeTransferCharacteristics((SEIAlternativeTransferCharacteristics&) *sei, payloadSize, pDecodedMessageOutputStream);
       break;
-#endif
+    case SEI::AMBIENT_VIEWING_ENVIRONMENT:
+      sei = new SEIAmbientViewingEnvironment;
+      xParseSEIAmbientViewingEnvironment((SEIAmbientViewingEnvironment&) *sei, payloadSize, pDecodedMessageOutputStream);
+      break;
 #if NH_MV
     case SEI::LAYERS_NOT_PRESENT:
@@ -412,11 +476,38 @@
     switch (payloadType)
     {
+      case SEI::FILLER_PAYLOAD:
+        sei = new SEIFillerPayload;
+        xParseSEIFillerPayload((SEIFillerPayload&) *sei, payloadSize, pDecodedMessageOutputStream);
+        break;
+      case SEI::USER_DATA_REGISTERED_ITU_T_T35:
+        sei = new SEIUserDataRegistered;
+        xParseSEIUserDataRegistered((SEIUserDataRegistered&) *sei, payloadSize, pDecodedMessageOutputStream);
+        break;
       case SEI::USER_DATA_UNREGISTERED:
-        sei = new SEIuserDataUnregistered;
-        xParseSEIuserDataUnregistered((SEIuserDataUnregistered&) *sei, payloadSize, pDecodedMessageOutputStream);
+        sei = new SEIUserDataUnregistered;
+        xParseSEIUserDataUnregistered((SEIUserDataUnregistered&) *sei, payloadSize, pDecodedMessageOutputStream);
+        break;
+      case SEI::PROGRESSIVE_REFINEMENT_SEGMENT_END:
+        sei = new SEIProgressiveRefinementSegmentEnd;
+        xParseSEIProgressiveRefinementSegmentEnd((SEIProgressiveRefinementSegmentEnd&) *sei, payloadSize, pDecodedMessageOutputStream);
+        break;
+      case SEI::POST_FILTER_HINT:
+        if (!sps)
+        {
+          printf ("Warning: post filter hint SEI message, but no active SPS is available. Ignoring.");
+        }
+        else
+        {
+          sei = new SEIPostFilterHint;
+          xParseSEIPostFilterHint((SEIPostFilterHint&) *sei, payloadSize, sps, pDecodedMessageOutputStream);
+        }
         break;
       case SEI::DECODED_PICTURE_HASH:
         sei = new SEIDecodedPictureHash;
         xParseSEIDecodedPictureHash((SEIDecodedPictureHash&) *sei, payloadSize, pDecodedMessageOutputStream);
+        break;
+      case SEI::CODED_REGION_COMPLETION:
+        sei = new SEICodedRegionCompletion;
+        xParseSEICodedRegionCompletion((SEICodedRegionCompletion&) *sei, payloadSize, pDecodedMessageOutputStream);
         break;
       default:
@@ -484,125 +575,4 @@
 }
 
-/**
- * parse bitstream bs and unpack a user_data_unregistered SEI message
- * of payloasSize bytes into sei.
- */
-
-Void SEIReader::xParseSEIuserDataUnregistered(SEIuserDataUnregistered &sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
-{
-  assert(payloadSize >= ISO_IEC_11578_LEN);
-  UInt val;
-  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
-
-  for (UInt i = 0; i < ISO_IEC_11578_LEN; i++)
-  {
-    sei_read_code( pDecodedMessageOutputStream, 8, val, "uuid_iso_iec_11578");
-    sei.uuid_iso_iec_11578[i] = val;
-  }
-
-  sei.userDataLength = payloadSize - ISO_IEC_11578_LEN;
-  if (!sei.userDataLength)
-  {
-    sei.userData = 0;
-    return;
-  }
-
-  sei.userData = new UChar[sei.userDataLength];
-  for (UInt i = 0; i < sei.userDataLength; i++)
-  {
-    sei_read_code( NULL, 8, val, "user_data_payload_byte" );
-    sei.userData[i] = val;
-  }
-  if (pDecodedMessageOutputStream)
-  {
-    (*pDecodedMessageOutputStream) << "  User data payload size: " << sei.userDataLength << "\n";
-  }
-}
-
-/**
- * parse bitstream bs and unpack a decoded picture hash SEI message
- * of payloadSize bytes into sei.
- */
-Void SEIReader::xParseSEIDecodedPictureHash(SEIDecodedPictureHash& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
-{
-  UInt bytesRead = 0;
-  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
-
-  UInt val;
-  sei_read_code( pDecodedMessageOutputStream, 8, val, "hash_type");
-  sei.method = static_cast<HashType>(val); bytesRead++;
-
-  const TChar *traceString="\0";
-  switch (sei.method)
-  {
-    case HASHTYPE_MD5: traceString="picture_md5"; break;
-    case HASHTYPE_CRC: traceString="picture_crc"; break;
-    case HASHTYPE_CHECKSUM: traceString="picture_checksum"; break;
-    default: assert(false); break;
-  }
-
-  if (pDecodedMessageOutputStream)
-  {
-    (*pDecodedMessageOutputStream) << "  " << std::setw(55) << traceString << ": " << std::hex << std::setfill('0');
-  }
-
-  sei.m_pictureHash.hash.clear();
-  for(;bytesRead < payloadSize; bytesRead++)
-  {
-    sei_read_code( NULL, 8, val, traceString);
-    sei.m_pictureHash.hash.push_back((UChar)val);
-    if (pDecodedMessageOutputStream)
-    {
-      (*pDecodedMessageOutputStream) << std::setw(2) << val;
-    }
-  }
-
-  if (pDecodedMessageOutputStream)
-  {
-    (*pDecodedMessageOutputStream) << std::dec << std::setfill(' ') << "\n";
-  }
-}
-
-Void SEIReader::xParseSEIActiveParameterSets(SEIActiveParameterSets& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
-{
-  UInt val;
-  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
-
-  sei_read_code( pDecodedMessageOutputStream, 4, val, "active_video_parameter_set_id");   sei.activeVPSId = val;
-  sei_read_flag( pDecodedMessageOutputStream,    val, "self_contained_cvs_flag");         sei.m_selfContainedCvsFlag     = (val != 0);
-  sei_read_flag( pDecodedMessageOutputStream,    val, "no_parameter_set_update_flag");    sei.m_noParameterSetUpdateFlag = (val != 0);
-  sei_read_uvlc( pDecodedMessageOutputStream,    val, "num_sps_ids_minus1");              sei.numSpsIdsMinus1 = val;
-
-  sei.activeSeqParameterSetId.resize(sei.numSpsIdsMinus1 + 1);
-  for (Int i=0; i < (sei.numSpsIdsMinus1 + 1); i++)
-  {
-    sei_read_uvlc( pDecodedMessageOutputStream, val, "active_seq_parameter_set_id[i]");    sei.activeSeqParameterSetId[i] = val;
-  }
-}
-
-Void SEIReader::xParseSEIDecodingUnitInfo(SEIDecodingUnitInfo& sei, UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
-{
-  UInt val;
-  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
-  sei_read_uvlc( pDecodedMessageOutputStream, val, "decoding_unit_idx");
-  sei.m_decodingUnitIdx = val;
-
-  const TComVUI *vui = sps->getVuiParameters();
-  if(vui->getHrdParameters()->getSubPicCpbParamsInPicTimingSEIFlag())
-  {
-    sei_read_code( pDecodedMessageOutputStream, ( vui->getHrdParameters()->getDuCpbRemovalDelayLengthMinus1() + 1 ), val, "du_spt_cpb_removal_delay_increment");
-    sei.m_duSptCpbRemovalDelay = val;
-  }
-  else
-  {
-    sei.m_duSptCpbRemovalDelay = 0;
-  }
-  sei_read_flag( pDecodedMessageOutputStream, val, "dpb_output_du_delay_present_flag"); sei.m_dpbOutputDuDelayPresentFlag = (val != 0);
-  if(sei.m_dpbOutputDuDelayPresentFlag)
-  {
-    sei_read_code( pDecodedMessageOutputStream, vui->getHrdParameters()->getDpbOutputDelayDuLengthMinus1() + 1, val, "pic_spt_dpb_output_du_delay");
-    sei.m_picSptDpbOutputDuDelay = val;
-  }
-}
 
 Void SEIReader::xParseSEIBufferingPeriod(SEIBufferingPeriod& sei, UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
@@ -713,4 +683,101 @@
 }
 
+Void SEIReader::xParseSEIPanScanRect(SEIPanScanRect& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_uvlc( pDecodedMessageOutputStream, code, "pan_scan_rect_id" );          sei.m_panScanRectId = code;
+  sei_read_flag( pDecodedMessageOutputStream, code, "pan_scan_rect_cancel_flag" ); sei.m_panScanRectCancelFlag = code!=0;
+  if (!sei.m_panScanRectCancelFlag)
+  {
+    UInt numRegions;
+    sei_read_uvlc( pDecodedMessageOutputStream, numRegions, "pan_scan_cnt_minus1" ); numRegions++;
+    sei.m_panScanRectRegions.resize(numRegions);
+    for(UInt region=0; region<numRegions; region++)
+    {
+      SEIPanScanRect::PanScanRect &rect=sei.m_panScanRectRegions[region];
+      Int  i;
+      sei_read_svlc( pDecodedMessageOutputStream, i, "pan_scan_rect_left_offset[i]" );   rect.leftOffset   = i;
+      sei_read_svlc( pDecodedMessageOutputStream, i, "pan_scan_rect_right_offset[i]" );  rect.rightOffset  = i;
+      sei_read_svlc( pDecodedMessageOutputStream, i, "pan_scan_rect_top_offset[i]" );    rect.topOffset    = i;
+      sei_read_svlc( pDecodedMessageOutputStream, i, "pan_scan_rect_bottom_offset[i]" ); rect.bottomOffset = i;
+    }
+    sei_read_flag( pDecodedMessageOutputStream, code, "pan_scan_rect_persistence_flag" ); sei.m_panScanRectPersistenceFlag = code!=0;
+  }
+  else
+  {
+    sei.m_panScanRectRegions.clear();
+    sei.m_panScanRectPersistenceFlag=false;
+  }
+}
+
+Void SEIReader::xParseSEIFillerPayload(SEIFillerPayload& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei.m_numFillerFFBytes = payloadSize;
+  Bool allBytesWereFF=true;
+  for(UInt k=0; k<payloadSize; k++)
+  {
+    UInt code;
+    sei_read_code( NULL, 8, code, "ff_byte" );
+    if (code!=0xff) allBytesWereFF=false;
+  }
+  if (pDecodedMessageOutputStream && !allBytesWereFF)
+  {
+    (*pDecodedMessageOutputStream) << "  not all filler payload bytes were 0xff\n";
+  }
+}
+
+
+Void SEIReader::xParseSEIUserDataRegistered(SEIUserDataRegistered& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+  {
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  UInt code;
+  assert(payloadSize>0);
+  sei_read_code( pDecodedMessageOutputStream, 8, code, "itu_t_t35_country_code" ); payloadSize--;
+  if (code == 255)
+  {
+    assert(payloadSize>0);
+    sei_read_code( pDecodedMessageOutputStream, 8, code, "itu_t_t35_country_code_extension_byte" ); payloadSize--;
+    code+=255;
+  }
+  sei.m_ituCountryCode = code;
+  sei.m_userData.resize(payloadSize);
+  for (UInt i = 0; i < sei.m_userData.size(); i++)
+  {
+    sei_read_code( NULL, 8, code, "itu_t_t35_payload_byte" );
+    sei.m_userData[i] = code;
+  }
+  if (pDecodedMessageOutputStream)
+  {
+    (*pDecodedMessageOutputStream) << "  itu_t_t35 payload size: " << sei.m_userData.size() << "\n";
+  }
+}
+
+Void SEIReader::xParseSEIUserDataUnregistered(SEIUserDataUnregistered &sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+    {
+  assert(payloadSize >= ISO_IEC_11578_LEN);
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  for (UInt i = 0; i < ISO_IEC_11578_LEN; i++)
+  {
+    sei_read_code( pDecodedMessageOutputStream, 8, val, "uuid_iso_iec_11578");
+    sei.m_uuid_iso_iec_11578[i] = val;
+    }
+  sei.m_userData.resize(payloadSize - ISO_IEC_11578_LEN);
+  for (UInt i = 0; i < sei.m_userData.size(); i++)
+  {
+    sei_read_code( NULL, 8, val, "user_data_payload_byte" );
+    sei.m_userData[i] = val;
+  }
+  if (pDecodedMessageOutputStream)
+  {
+    (*pDecodedMessageOutputStream) << "  User data payload size: " << sei.m_userData.size() << "\n";
+  }
+}
+
+
 Void SEIReader::xParseSEIRecoveryPoint(SEIRecoveryPoint& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
 {
@@ -724,87 +791,127 @@
 }
 
-Void SEIReader::xParseSEIFramePacking(SEIFramePacking& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
-{
-  UInt val;
-  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
-
-  sei_read_uvlc( pDecodedMessageOutputStream, val, "frame_packing_arrangement_id" );                 sei.m_arrangementId = val;
-  sei_read_flag( pDecodedMessageOutputStream, val, "frame_packing_arrangement_cancel_flag" );        sei.m_arrangementCancelFlag = val;
-
-  if ( !sei.m_arrangementCancelFlag )
-  {
-    sei_read_code( pDecodedMessageOutputStream, 7, val, "frame_packing_arrangement_type" );          sei.m_arrangementType = val;
-    assert((sei.m_arrangementType > 2) && (sei.m_arrangementType < 6) );
-
-    sei_read_flag( pDecodedMessageOutputStream, val, "quincunx_sampling_flag" );                     sei.m_quincunxSamplingFlag = val;
-
-    sei_read_code( pDecodedMessageOutputStream, 6, val, "content_interpretation_type" );             sei.m_contentInterpretationType = val;
-    sei_read_flag( pDecodedMessageOutputStream, val, "spatial_flipping_flag" );                      sei.m_spatialFlippingFlag = val;
-    sei_read_flag( pDecodedMessageOutputStream, val, "frame0_flipped_flag" );                        sei.m_frame0FlippedFlag = val;
-    sei_read_flag( pDecodedMessageOutputStream, val, "field_views_flag" );                           sei.m_fieldViewsFlag = val;
-    sei_read_flag( pDecodedMessageOutputStream, val, "current_frame_is_frame0_flag" );               sei.m_currentFrameIsFrame0Flag = val;
-    sei_read_flag( pDecodedMessageOutputStream, val, "frame0_self_contained_flag" );                 sei.m_frame0SelfContainedFlag = val;
-    sei_read_flag( pDecodedMessageOutputStream, val, "frame1_self_contained_flag" );                 sei.m_frame1SelfContainedFlag = val;
-
-    if ( sei.m_quincunxSamplingFlag == 0 && sei.m_arrangementType != 5)
-    {
-      sei_read_code( pDecodedMessageOutputStream, 4, val, "frame0_grid_position_x" );                sei.m_frame0GridPositionX = val;
-      sei_read_code( pDecodedMessageOutputStream, 4, val, "frame0_grid_position_y" );                sei.m_frame0GridPositionY = val;
-      sei_read_code( pDecodedMessageOutputStream, 4, val, "frame1_grid_position_x" );                sei.m_frame1GridPositionX = val;
-      sei_read_code( pDecodedMessageOutputStream, 4, val, "frame1_grid_position_y" );                sei.m_frame1GridPositionY = val;
-    }
-
-    sei_read_code( pDecodedMessageOutputStream, 8, val, "frame_packing_arrangement_reserved_byte" );   sei.m_arrangementReservedByte = val;
-    sei_read_flag( pDecodedMessageOutputStream, val,  "frame_packing_arrangement_persistence_flag" );  sei.m_arrangementPersistenceFlag = (val != 0);
-  }
-  sei_read_flag( pDecodedMessageOutputStream, val, "upsampled_aspect_ratio_flag" );                  sei.m_upsampledAspectRatio = val;
-}
-
-Void SEIReader::xParseSEISegmentedRectFramePacking(SEISegmentedRectFramePacking& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
-{
-  UInt val;
-  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
-  sei_read_flag( pDecodedMessageOutputStream, val,       "segmented_rect_frame_packing_arrangement_cancel_flag" );       sei.m_arrangementCancelFlag            = val;
-  if( !sei.m_arrangementCancelFlag )
-  {
-    sei_read_code( pDecodedMessageOutputStream, 2, val, "segmented_rect_content_interpretation_type" );                sei.m_contentInterpretationType = val;
-    sei_read_flag( pDecodedMessageOutputStream, val,     "segmented_rect_frame_packing_arrangement_persistence" );                              sei.m_arrangementPersistenceFlag               = val;
-  }
-}
-
-Void SEIReader::xParseSEIDisplayOrientation(SEIDisplayOrientation& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
-{
-  UInt val;
-  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
-  sei_read_flag( pDecodedMessageOutputStream, val,       "display_orientation_cancel_flag" );       sei.cancelFlag            = val;
-  if( !sei.cancelFlag )
-  {
-    sei_read_flag( pDecodedMessageOutputStream, val,     "hor_flip" );                              sei.horFlip               = val;
-    sei_read_flag( pDecodedMessageOutputStream, val,     "ver_flip" );                              sei.verFlip               = val;
-    sei_read_code( pDecodedMessageOutputStream, 16, val, "anticlockwise_rotation" );                sei.anticlockwiseRotation = val;
-    sei_read_flag( pDecodedMessageOutputStream, val,     "display_orientation_persistence_flag" );  sei.persistenceFlag       = val;
-  }
-}
-
-Void SEIReader::xParseSEITemporalLevel0Index(SEITemporalLevel0Index& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
-{
-  UInt val;
-  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
-  sei_read_code( pDecodedMessageOutputStream, 8, val, "temporal_sub_layer_zero_idx" );  sei.tl0Idx = val;
-  sei_read_code( pDecodedMessageOutputStream, 8, val, "irap_pic_id" );  sei.rapIdx = val;
-}
-
-Void SEIReader::xParseSEIRegionRefreshInfo(SEIGradualDecodingRefreshInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
-{
-  UInt val;
-  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
-  sei_read_flag( pDecodedMessageOutputStream, val, "refreshed_region_flag" ); sei.m_gdrForegroundFlag = val ? 1 : 0;
-}
-
-Void SEIReader::xParseSEINoDisplay(SEINoDisplay& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
-{
-  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
-  sei.m_noDisplay = true;
-}
+
+Void SEIReader::xParseSEISceneInfo(SEISceneInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+  {
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_flag( pDecodedMessageOutputStream, code, "scene_info_present_flag" ); sei.m_bSceneInfoPresentFlag = code!=0;
+  if (sei.m_bSceneInfoPresentFlag)
+  {
+    sei_read_flag( pDecodedMessageOutputStream, code, "prev_scene_id_valid_flag" ); sei.m_bPrevSceneIdValidFlag = code!=0;
+    sei_read_uvlc( pDecodedMessageOutputStream, code, "scene_id" );                 sei.m_sceneId = code;
+    sei_read_uvlc( pDecodedMessageOutputStream, code, "scene_transition_type" );    sei.m_sceneTransitionType = code;
+    if (sei.m_sceneTransitionType > 3)
+    {
+      sei_read_uvlc( pDecodedMessageOutputStream, code, "second_scene_id" );        sei.m_secondSceneId = code;
+    }
+    else
+    {
+      sei.m_secondSceneId = 0; // set to known value.
+    }
+  }
+}
+
+Void SEIReader::xParseSEIPictureSnapshot(SEIPictureSnapshot& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_uvlc( pDecodedMessageOutputStream, code, "snapshot_id" ); sei.m_snapshotId = code;
+  }
+
+
+Void SEIReader::xParseSEIProgressiveRefinementSegmentStart(SEIProgressiveRefinementSegmentStart& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_uvlc( pDecodedMessageOutputStream, code, "progressive_refinement_id" ); sei.m_progressiveRefinementId = code;
+  sei_read_uvlc( pDecodedMessageOutputStream, code, "pic_order_cnt_delta" );       sei.m_picOrderCntDelta = code;
+}
+
+
+Void SEIReader::xParseSEIProgressiveRefinementSegmentEnd(SEIProgressiveRefinementSegmentEnd& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_uvlc( pDecodedMessageOutputStream, code, "progressive_refinement_id" ); sei.m_progressiveRefinementId = code;
+}
+
+
+Void SEIReader::xParseSEIFilmGrainCharacteristics(SEIFilmGrainCharacteristics& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_flag( pDecodedMessageOutputStream, code, "film_grain_characteristics_cancel_flag" );     sei.m_filmGrainCharacteristicsCancelFlag = code!=0;
+  if (!sei.m_filmGrainCharacteristicsCancelFlag)
+  {
+    sei_read_code( pDecodedMessageOutputStream, 2, code, "film_grain_model_id" );                   sei.m_filmGrainModelId = code;
+    sei_read_flag( pDecodedMessageOutputStream,    code, "separate_colour_description_present_flag" ); sei.m_separateColourDescriptionPresentFlag = code!=0;
+    if (sei.m_separateColourDescriptionPresentFlag)
+    {
+      sei_read_code( pDecodedMessageOutputStream, 3, code, "film_grain_bit_depth_luma_minus8" );    sei.m_filmGrainBitDepthLumaMinus8      = code;
+      sei_read_code( pDecodedMessageOutputStream, 3, code, "film_grain_bit_depth_chroma_minus8" );  sei.m_filmGrainBitDepthChromaMinus8    = code;
+      sei_read_flag( pDecodedMessageOutputStream,    code, "film_grain_full_range_flag" );          sei.m_filmGrainFullRangeFlag           = code!=0;
+      sei_read_code( pDecodedMessageOutputStream, 8, code, "film_grain_colour_primaries" );         sei.m_filmGrainColourPrimaries         = code;
+      sei_read_code( pDecodedMessageOutputStream, 8, code, "film_grain_transfer_characteristics" ); sei.m_filmGrainTransferCharacteristics = code;
+      sei_read_code( pDecodedMessageOutputStream, 8, code, "film_grain_matrix_coeffs" );            sei.m_filmGrainMatrixCoeffs            = code;
+    }
+    sei_read_code( pDecodedMessageOutputStream, 2, code, "blending_mode_id" );                      sei.m_blendingModeId                   = code;
+    sei_read_code( pDecodedMessageOutputStream, 4, code, "log2_scale_factor" );                     sei.m_log2ScaleFactor                  = code;
+    for(Int c=0; c<3; c++)
+    {
+      sei_read_flag( pDecodedMessageOutputStream,    code, "comp_model_present_flag[c]" );          sei.m_compModel[c].bPresentFlag        = code!=0;
+    }
+    for(Int c=0; c<3; c++)
+    {
+      SEIFilmGrainCharacteristics::CompModel &cm=sei.m_compModel[c];
+      if (cm.bPresentFlag)
+      {
+        UInt numIntensityIntervals;
+        sei_read_code( pDecodedMessageOutputStream, 8, code, "num_intensity_intervals_minus1[c]" ); numIntensityIntervals = code+1;
+        sei_read_code( pDecodedMessageOutputStream, 3, code, "num_model_values_minus1[c]" );        cm.numModelValues     = code+1;
+        cm.intensityValues.resize(numIntensityIntervals);
+        for(UInt interval=0; interval<numIntensityIntervals; interval++)
+        {
+          SEIFilmGrainCharacteristics::CompModelIntensityValues &cmiv=cm.intensityValues[interval];
+          sei_read_code( pDecodedMessageOutputStream, 8, code, "intensity_interval_lower_bound[c][i]" ); cmiv.intensityIntervalLowerBound=code;
+          sei_read_code( pDecodedMessageOutputStream, 8, code, "intensity_interval_upper_bound[c][i]" ); cmiv.intensityIntervalUpperBound=code;
+          cmiv.compModelValue.resize(cm.numModelValues);
+          for(UInt j=0; j<cm.numModelValues; j++)
+          {
+            sei_read_svlc( pDecodedMessageOutputStream, cmiv.compModelValue[j], "comp_model_value[c][i]" );
+          }
+        }
+      }
+    } // for c
+    sei_read_flag( pDecodedMessageOutputStream, code, "film_grain_characteristics_persistence_flag" ); sei.m_filmGrainCharacteristicsPersistenceFlag = code!=0;
+  } // cancel flag
+}
+
+Void SEIReader::xParseSEIPostFilterHint(SEIPostFilterHint& sei, UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_uvlc( pDecodedMessageOutputStream,    code, "filter_hint_size_y" ); sei.m_filterHintSizeY = code;
+  sei_read_uvlc( pDecodedMessageOutputStream,    code, "filter_hint_size_x" ); sei.m_filterHintSizeX = code;
+  sei_read_code( pDecodedMessageOutputStream, 2, code, "filter_hint_type"   ); sei.m_filterHintType  = code;
+
+  sei.m_bIsMonochrome = (sps->getChromaFormatIdc() == CHROMA_400);
+  const UInt numChromaChannels = sei.m_bIsMonochrome ? 1:3;
+
+  sei.m_filterHintValues.resize(numChromaChannels * sei.m_filterHintSizeX * sei.m_filterHintSizeY);
+  for(std::size_t i=0; i<sei.m_filterHintValues.size(); i++)
+  {
+    Int v;
+    sei_read_svlc( pDecodedMessageOutputStream, v, "filter_hint_value[][][]" ); sei.m_filterHintValues[i] = code;
+
+}
+}
+
 
 Void SEIReader::xParseSEIToneMappingInfo(SEIToneMappingInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
@@ -893,4 +1000,74 @@
 }
 
+
+Void SEIReader::xParseSEIFramePacking(SEIFramePacking& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_uvlc( pDecodedMessageOutputStream, val, "frame_packing_arrangement_id" );                 sei.m_arrangementId = val;
+  sei_read_flag( pDecodedMessageOutputStream, val, "frame_packing_arrangement_cancel_flag" );        sei.m_arrangementCancelFlag = val;
+
+  if ( !sei.m_arrangementCancelFlag )
+  {
+    sei_read_code( pDecodedMessageOutputStream, 7, val, "frame_packing_arrangement_type" );          sei.m_arrangementType = val;
+    assert((sei.m_arrangementType > 2) && (sei.m_arrangementType < 6) );
+
+    sei_read_flag( pDecodedMessageOutputStream, val, "quincunx_sampling_flag" );                     sei.m_quincunxSamplingFlag = val;
+
+    sei_read_code( pDecodedMessageOutputStream, 6, val, "content_interpretation_type" );             sei.m_contentInterpretationType = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "spatial_flipping_flag" );                      sei.m_spatialFlippingFlag = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "frame0_flipped_flag" );                        sei.m_frame0FlippedFlag = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "field_views_flag" );                           sei.m_fieldViewsFlag = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "current_frame_is_frame0_flag" );               sei.m_currentFrameIsFrame0Flag = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "frame0_self_contained_flag" );                 sei.m_frame0SelfContainedFlag = val;
+    sei_read_flag( pDecodedMessageOutputStream, val, "frame1_self_contained_flag" );                 sei.m_frame1SelfContainedFlag = val;
+
+    if ( sei.m_quincunxSamplingFlag == 0 && sei.m_arrangementType != 5)
+    {
+      sei_read_code( pDecodedMessageOutputStream, 4, val, "frame0_grid_position_x" );                sei.m_frame0GridPositionX = val;
+      sei_read_code( pDecodedMessageOutputStream, 4, val, "frame0_grid_position_y" );                sei.m_frame0GridPositionY = val;
+      sei_read_code( pDecodedMessageOutputStream, 4, val, "frame1_grid_position_x" );                sei.m_frame1GridPositionX = val;
+      sei_read_code( pDecodedMessageOutputStream, 4, val, "frame1_grid_position_y" );                sei.m_frame1GridPositionY = val;
+    }
+
+    sei_read_code( pDecodedMessageOutputStream, 8, val, "frame_packing_arrangement_reserved_byte" );   sei.m_arrangementReservedByte = val;
+    sei_read_flag( pDecodedMessageOutputStream, val,  "frame_packing_arrangement_persistence_flag" );  sei.m_arrangementPersistenceFlag = (val != 0);
+  }
+  sei_read_flag( pDecodedMessageOutputStream, val, "upsampled_aspect_ratio_flag" );                  sei.m_upsampledAspectRatio = val;
+}
+
+
+Void SEIReader::xParseSEIDisplayOrientation(SEIDisplayOrientation& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_flag( pDecodedMessageOutputStream, val,       "display_orientation_cancel_flag" );       sei.cancelFlag            = val;
+  if( !sei.cancelFlag )
+  {
+    sei_read_flag( pDecodedMessageOutputStream, val,     "hor_flip" );                              sei.horFlip               = val;
+    sei_read_flag( pDecodedMessageOutputStream, val,     "ver_flip" );                              sei.verFlip               = val;
+    sei_read_code( pDecodedMessageOutputStream, 16, val, "anticlockwise_rotation" );                sei.anticlockwiseRotation = val;
+    sei_read_flag( pDecodedMessageOutputStream, val,     "display_orientation_persistence_flag" );  sei.persistenceFlag       = val;
+  }
+}
+
+
+Void SEIReader::xParseSEIGreenMetadataInfo(SEIGreenMetadataInfo& sei, UInt payloadSize, ostream* pDecodedMessageOutputStream)
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_code(pDecodedMessageOutputStream, 8, code, "green_metadata_type");
+  sei.m_greenMetadataType = code;
+
+  sei_read_code(pDecodedMessageOutputStream, 8, code, "xsd_metric_type");
+  sei.m_xsdMetricType = code;
+
+  sei_read_code(pDecodedMessageOutputStream, 16, code, "xsd_metric_value");
+  sei.m_xsdMetricValue = code;
+}
+
+
 Void SEIReader::xParseSEISOPDescription(SEISOPDescription &sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
 {
@@ -913,4 +1090,97 @@
       sei_read_svlc( pDecodedMessageOutputStream, iCode,                       "sop_poc_delta[i]"     ); sei.m_sopDescPocDelta[i] = iCode;
     }
+  }
+}
+
+Void SEIReader::xParseSEIActiveParameterSets(SEIActiveParameterSets& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_code( pDecodedMessageOutputStream, 4, val, "active_video_parameter_set_id");   sei.activeVPSId = val;
+  sei_read_flag( pDecodedMessageOutputStream,    val, "self_contained_cvs_flag");         sei.m_selfContainedCvsFlag     = (val != 0);
+  sei_read_flag( pDecodedMessageOutputStream,    val, "no_parameter_set_update_flag");    sei.m_noParameterSetUpdateFlag = (val != 0);
+  sei_read_uvlc( pDecodedMessageOutputStream,    val, "num_sps_ids_minus1");              sei.numSpsIdsMinus1 = val;
+
+  sei.activeSeqParameterSetId.resize(sei.numSpsIdsMinus1 + 1);
+  for (Int i=0; i < (sei.numSpsIdsMinus1 + 1); i++)
+  {
+    sei_read_uvlc( pDecodedMessageOutputStream, val, "active_seq_parameter_set_id[i]");    sei.activeSeqParameterSetId[i] = val;
+  }
+}
+
+
+Void SEIReader::xParseSEIDecodingUnitInfo(SEIDecodingUnitInfo& sei, UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_uvlc( pDecodedMessageOutputStream, val, "decoding_unit_idx");
+  sei.m_decodingUnitIdx = val;
+
+  const TComVUI *vui = sps->getVuiParameters();
+  if(vui->getHrdParameters()->getSubPicCpbParamsInPicTimingSEIFlag())
+  {
+    sei_read_code( pDecodedMessageOutputStream, ( vui->getHrdParameters()->getDuCpbRemovalDelayLengthMinus1() + 1 ), val, "du_spt_cpb_removal_delay_increment");
+    sei.m_duSptCpbRemovalDelay = val;
+  }
+  else
+  {
+    sei.m_duSptCpbRemovalDelay = 0;
+  }
+  sei_read_flag( pDecodedMessageOutputStream, val, "dpb_output_du_delay_present_flag"); sei.m_dpbOutputDuDelayPresentFlag = (val != 0);
+  if(sei.m_dpbOutputDuDelayPresentFlag)
+  {
+    sei_read_code( pDecodedMessageOutputStream, vui->getHrdParameters()->getDpbOutputDelayDuLengthMinus1() + 1, val, "pic_spt_dpb_output_du_delay");
+    sei.m_picSptDpbOutputDuDelay = val;
+  }
+}
+
+
+Void SEIReader::xParseSEITemporalLevel0Index(SEITemporalLevel0Index& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_code( pDecodedMessageOutputStream, 8, val, "temporal_sub_layer_zero_idx" );  sei.tl0Idx = val;
+  sei_read_code( pDecodedMessageOutputStream, 8, val, "irap_pic_id" );  sei.rapIdx = val;
+}
+
+
+Void SEIReader::xParseSEIDecodedPictureHash(SEIDecodedPictureHash& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt bytesRead = 0;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  UInt val;
+  sei_read_code( pDecodedMessageOutputStream, 8, val, "hash_type");
+  sei.method = static_cast<HashType>(val); bytesRead++;
+
+  const TChar *traceString="\0";
+  switch (sei.method)
+  {
+    case HASHTYPE_MD5: traceString="picture_md5"; break;
+    case HASHTYPE_CRC: traceString="picture_crc"; break;
+    case HASHTYPE_CHECKSUM: traceString="picture_checksum"; break;
+    default: assert(false); break;
+  }
+
+  if (pDecodedMessageOutputStream)
+  {
+    (*pDecodedMessageOutputStream) << "  " << std::setw(55) << traceString << ": " << std::hex << std::setfill('0');
+  }
+
+  sei.m_pictureHash.hash.clear();
+  for(;bytesRead < payloadSize; bytesRead++)
+  {
+    sei_read_code( NULL, 8, val, traceString);
+    sei.m_pictureHash.hash.push_back((UChar)val);
+    if (pDecodedMessageOutputStream)
+    {
+      (*pDecodedMessageOutputStream) << std::setw(2) << val;
+    }
+  }
+
+  if (pDecodedMessageOutputStream)
+  {
+    (*pDecodedMessageOutputStream) << std::dec << std::setfill(' ') << "\n";
   }
 }
@@ -976,59 +1246,18 @@
 
 
-Void SEIReader::xParseSEITempMotionConstraintsTileSets(SEITempMotionConstrainedTileSets& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
-{
-  UInt code;
-  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
-  sei_read_flag( pDecodedMessageOutputStream, code, "mc_all_tiles_exact_sample_value_match_flag");  sei.m_mc_all_tiles_exact_sample_value_match_flag = (code != 0);
-  sei_read_flag( pDecodedMessageOutputStream, code, "each_tile_one_tile_set_flag");                 sei.m_each_tile_one_tile_set_flag                = (code != 0);
-
-  if(!sei.m_each_tile_one_tile_set_flag)
-  {
-    sei_read_flag( pDecodedMessageOutputStream, code, "limited_tile_set_display_flag");  sei.m_limited_tile_set_display_flag = (code != 0);
-    sei_read_uvlc( pDecodedMessageOutputStream, code, "num_sets_in_message_minus1");     sei.setNumberOfTileSets(code + 1);
-
-    if(sei.getNumberOfTileSets() != 0)
-    {
-      for(Int i = 0; i < sei.getNumberOfTileSets(); i++)
-      {
-        sei_read_uvlc( pDecodedMessageOutputStream, code, "mcts_id");  sei.tileSetData(i).m_mcts_id = code;
-
-        if(sei.m_limited_tile_set_display_flag)
-        {
-          sei_read_flag( pDecodedMessageOutputStream, code, "display_tile_set_flag");  sei.tileSetData(i).m_display_tile_set_flag = (code != 1);
-        }
-
-        sei_read_uvlc( pDecodedMessageOutputStream, code, "num_tile_rects_in_set_minus1");  sei.tileSetData(i).setNumberOfTileRects(code + 1);
-
-        for(Int j=0; j<sei.tileSetData(i).getNumberOfTileRects(); j++)
-        {
-          sei_read_uvlc( pDecodedMessageOutputStream, code, "top_left_tile_index");      sei.tileSetData(i).topLeftTileIndex(j)     = code;
-          sei_read_uvlc( pDecodedMessageOutputStream, code, "bottom_right_tile_index");  sei.tileSetData(i).bottomRightTileIndex(j) = code;
-        }
-
-        if(!sei.m_mc_all_tiles_exact_sample_value_match_flag)
-        {
-          sei_read_flag( pDecodedMessageOutputStream, code, "exact_sample_value_match_flag");   sei.tileSetData(i).m_exact_sample_value_match_flag    = (code != 0);
-        }
-        sei_read_flag( pDecodedMessageOutputStream, code, "mcts_tier_level_idc_present_flag");  sei.tileSetData(i).m_mcts_tier_level_idc_present_flag = (code != 0);
-
-        if(sei.tileSetData(i).m_mcts_tier_level_idc_present_flag)
-        {
-          sei_read_flag( pDecodedMessageOutputStream, code,    "mcts_tier_flag"); sei.tileSetData(i).m_mcts_tier_flag = (code != 0);
-          sei_read_code( pDecodedMessageOutputStream, 8, code, "mcts_level_idc"); sei.tileSetData(i).m_mcts_level_idc =  code;
-        }
-      }
-    }
-  }
-  else
-  {
-    sei_read_flag( pDecodedMessageOutputStream, code, "max_mcs_tier_level_idc_present_flag");  sei.m_max_mcs_tier_level_idc_present_flag = code;
-    if(sei.m_max_mcs_tier_level_idc_present_flag)
-    {
-      sei_read_flag( pDecodedMessageOutputStream, code, "max_mcts_tier_flag");  sei.m_max_mcts_tier_flag = code;
-      sei_read_code( pDecodedMessageOutputStream, 8, code, "max_mcts_level_idc"); sei.m_max_mcts_level_idc = code;
-    }
-  }
-}
+Void SEIReader::xParseSEIRegionRefreshInfo(SEIRegionRefreshInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_flag( pDecodedMessageOutputStream, val, "refreshed_region_flag" ); sei.m_gdrForegroundFlag = val ? 1 : 0;
+        }
+
+
+Void SEIReader::xParseSEINoDisplay(SEINoDisplay& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+        {
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei.m_noDisplay = true;
+        }
+
 
 Void SEIReader::xParseSEITimeCode(SEITimeCode& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
@@ -1092,4 +1321,98 @@
 }
 
+
+Void SEIReader::xParseSEIMasteringDisplayColourVolume(SEIMasteringDisplayColourVolume& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_x[0]" ); sei.values.primaries[0][0] = code;
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_y[0]" ); sei.values.primaries[0][1] = code;
+
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_x[1]" ); sei.values.primaries[1][0] = code;
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_y[1]" ); sei.values.primaries[1][1] = code;
+
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_x[2]" ); sei.values.primaries[2][0] = code;
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_y[2]" ); sei.values.primaries[2][1] = code;
+
+
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "white_point_x" ); sei.values.whitePoint[0] = code;
+  sei_read_code( pDecodedMessageOutputStream, 16, code, "white_point_y" ); sei.values.whitePoint[1] = code;
+
+  sei_read_code( pDecodedMessageOutputStream, 32, code, "max_display_mastering_luminance" ); sei.values.maxLuminance = code;
+  sei_read_code( pDecodedMessageOutputStream, 32, code, "min_display_mastering_luminance" ); sei.values.minLuminance = code;
+}
+
+
+Void SEIReader::xParseSEISegmentedRectFramePacking(SEISegmentedRectFramePacking& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt val;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_flag( pDecodedMessageOutputStream, val,       "segmented_rect_frame_packing_arrangement_cancel_flag" );       sei.m_arrangementCancelFlag            = val;
+  if( !sei.m_arrangementCancelFlag )
+  {
+    sei_read_code( pDecodedMessageOutputStream, 2, val, "segmented_rect_content_interpretation_type" );                sei.m_contentInterpretationType = val;
+    sei_read_flag( pDecodedMessageOutputStream, val,     "segmented_rect_frame_packing_arrangement_persistence" );                              sei.m_arrangementPersistenceFlag               = val;
+  }
+}
+
+
+Void SEIReader::xParseSEITempMotionConstraintsTileSets(SEITempMotionConstrainedTileSets& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+  sei_read_flag( pDecodedMessageOutputStream, code, "mc_all_tiles_exact_sample_value_match_flag");  sei.m_mc_all_tiles_exact_sample_value_match_flag = (code != 0);
+  sei_read_flag( pDecodedMessageOutputStream, code, "each_tile_one_tile_set_flag");                 sei.m_each_tile_one_tile_set_flag                = (code != 0);
+
+  if(!sei.m_each_tile_one_tile_set_flag)
+  {
+    sei_read_flag( pDecodedMessageOutputStream, code, "limited_tile_set_display_flag");  sei.m_limited_tile_set_display_flag = (code != 0);
+    sei_read_uvlc( pDecodedMessageOutputStream, code, "num_sets_in_message_minus1");     sei.setNumberOfTileSets(code + 1);
+
+    if(sei.getNumberOfTileSets() != 0)
+    {
+      for(Int i = 0; i < sei.getNumberOfTileSets(); i++)
+      {
+        sei_read_uvlc( pDecodedMessageOutputStream, code, "mcts_id");  sei.tileSetData(i).m_mcts_id = code;
+
+        if(sei.m_limited_tile_set_display_flag)
+        {
+          sei_read_flag( pDecodedMessageOutputStream, code, "display_tile_set_flag");  sei.tileSetData(i).m_display_tile_set_flag = (code != 1);
+        }
+
+        sei_read_uvlc( pDecodedMessageOutputStream, code, "num_tile_rects_in_set_minus1");  sei.tileSetData(i).setNumberOfTileRects(code + 1);
+
+        for(Int j=0; j<sei.tileSetData(i).getNumberOfTileRects(); j++)
+        {
+          sei_read_uvlc( pDecodedMessageOutputStream, code, "top_left_tile_index");      sei.tileSetData(i).topLeftTileIndex(j)     = code;
+          sei_read_uvlc( pDecodedMessageOutputStream, code, "bottom_right_tile_index");  sei.tileSetData(i).bottomRightTileIndex(j) = code;
+        }
+
+        if(!sei.m_mc_all_tiles_exact_sample_value_match_flag)
+        {
+          sei_read_flag( pDecodedMessageOutputStream, code, "exact_sample_value_match_flag");   sei.tileSetData(i).m_exact_sample_value_match_flag    = (code != 0);
+        }
+        sei_read_flag( pDecodedMessageOutputStream, code, "mcts_tier_level_idc_present_flag");  sei.tileSetData(i).m_mcts_tier_level_idc_present_flag = (code != 0);
+
+        if(sei.tileSetData(i).m_mcts_tier_level_idc_present_flag)
+        {
+          sei_read_flag( pDecodedMessageOutputStream, code,    "mcts_tier_flag"); sei.tileSetData(i).m_mcts_tier_flag = (code != 0);
+          sei_read_code( pDecodedMessageOutputStream, 8, code, "mcts_level_idc"); sei.tileSetData(i).m_mcts_level_idc =  code;
+        }
+      }
+    }
+  }
+  else
+  {
+    sei_read_flag( pDecodedMessageOutputStream, code, "max_mcs_tier_level_idc_present_flag");  sei.m_max_mcs_tier_level_idc_present_flag = code;
+    if(sei.m_max_mcs_tier_level_idc_present_flag)
+    {
+      sei_read_flag( pDecodedMessageOutputStream, code, "max_mcts_tier_flag");  sei.m_max_mcts_tier_flag = code;
+      sei_read_code( pDecodedMessageOutputStream, 8, code, "max_mcts_level_idc"); sei.m_max_mcts_level_idc = code;
+    }
+  }
+}
+
+
 Void SEIReader::xParseSEIChromaResamplingFilterHint(SEIChromaResamplingFilterHint& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
 {
@@ -1256,28 +1579,46 @@
 }
 
-
-Void SEIReader::xParseSEIMasteringDisplayColourVolume(SEIMasteringDisplayColourVolume& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream)
-{
-  UInt code;
-  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
-
-  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_x[0]" ); sei.values.primaries[0][0] = code;
-  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_y[0]" ); sei.values.primaries[0][1] = code;
-
-  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_x[1]" ); sei.values.primaries[1][0] = code;
-  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_y[1]" ); sei.values.primaries[1][1] = code;
-
-  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_x[2]" ); sei.values.primaries[2][0] = code;
-  sei_read_code( pDecodedMessageOutputStream, 16, code, "display_primaries_y[2]" ); sei.values.primaries[2][1] = code;
-
-
-  sei_read_code( pDecodedMessageOutputStream, 16, code, "white_point_x" ); sei.values.whitePoint[0] = code;
-  sei_read_code( pDecodedMessageOutputStream, 16, code, "white_point_y" ); sei.values.whitePoint[1] = code;
-
-  sei_read_code( pDecodedMessageOutputStream, 32, code, "max_display_mastering_luminance" ); sei.values.maxLuminance = code;
-  sei_read_code( pDecodedMessageOutputStream, 32, code, "min_display_mastering_luminance" ); sei.values.minLuminance = code;
-}
-
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
+Void SEIReader::xParseSEIDeinterlaceFieldIdentification( SEIDeinterlaceFieldIdentification& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream )
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_flag(pDecodedMessageOutputStream, code, "deinterlaced_picture_source_parity_flag"); sei.m_deinterlacedPictureSourceParityFlag = code!=0;
+}
+
+
+Void SEIReader::xParseSEIContentLightLevelInfo( SEIContentLightLevelInfo& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream )
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_code(pDecodedMessageOutputStream, 16, code, "max_content_light_level");     sei.m_maxContentLightLevel    = code;
+  sei_read_code(pDecodedMessageOutputStream, 16, code, "max_pic_average_light_level"); sei.m_maxPicAverageLightLevel = code;
+}
+
+
+Void SEIReader::xParseSEIDependentRAPIndication( SEIDependentRAPIndication& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream )
+{
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+}
+
+
+Void SEIReader::xParseSEICodedRegionCompletion( SEICodedRegionCompletion& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream )
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_uvlc(pDecodedMessageOutputStream, code, "next_segment_address"); sei.m_nextSegmentAddress= code;
+  if (code)
+  {
+    sei_read_flag(pDecodedMessageOutputStream, code, "independent_slice_segment_flag"); sei.m_independentSliceSegmentFlag = code!=0;
+  }
+  else
+  {
+    sei.m_independentSliceSegmentFlag=false; // initialise to known value.
+  }
+}
+
+
 Void SEIReader::xParseSEIAlternativeTransferCharacteristics(SEIAlternativeTransferCharacteristics& sei, UInt payloadSize, ostream* pDecodedMessageOutputStream)
 {
@@ -1287,5 +1628,16 @@
   sei_read_code(pDecodedMessageOutputStream, 8, code, "preferred_transfer_characteristics"); sei.m_preferredTransferCharacteristics = code;
 }
-#endif
+
+
+Void SEIReader::xParseSEIAmbientViewingEnvironment( SEIAmbientViewingEnvironment& sei, UInt payloadSize, std::ostream *pDecodedMessageOutputStream )
+{
+  UInt code;
+  output_sei_message_header(sei, pDecodedMessageOutputStream, payloadSize);
+
+  sei_read_code(pDecodedMessageOutputStream, 32, code, "ambient_illuminance"); sei.m_ambientIlluminance= code;
+  sei_read_code(pDecodedMessageOutputStream, 16, code, "ambient_light_x");     sei.m_ambientLightX     = (UShort)code;
+  sei_read_code(pDecodedMessageOutputStream, 16, code, "ambient_light_y");     sei.m_ambientLightY     = (UShort)code;
+}
+
 
 #if NH_MV
Index: /trunk/source/Lib/TLibDecoder/SEIread.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/SEIread.h	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/SEIread.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -69,19 +69,26 @@
   Void xReadSEImessage                        (SEIMessages& seis, const NalUnitType nalUnitType, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
 #endif
-  Void xParseSEIuserDataUnregistered          (SEIuserDataUnregistered &sei,          UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIBufferingPeriod               (SEIBufferingPeriod& sei,               UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIPictureTiming                 (SEIPictureTiming& sei,                 UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIPanScanRect                   (SEIPanScanRect& sei,                   UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIFillerPayload                 (SEIFillerPayload& sei,                 UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIUserDataRegistered            (SEIUserDataRegistered& sei,            UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIUserDataUnregistered          (SEIUserDataUnregistered &sei,          UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIRecoveryPoint                 (SEIRecoveryPoint& sei,                 UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEISceneInfo                     (SEISceneInfo& sei,                     UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIPictureSnapshot               (SEIPictureSnapshot& sei,               UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIProgressiveRefinementSegmentStart(SEIProgressiveRefinementSegmentStart& sei, UInt payloadSize,              std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIProgressiveRefinementSegmentEnd(SEIProgressiveRefinementSegmentEnd& sei, UInt payloadSize,                  std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIFilmGrainCharacteristics      (SEIFilmGrainCharacteristics& sei,      UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIPostFilterHint                (SEIPostFilterHint& sei,                UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIToneMappingInfo               (SEIToneMappingInfo& sei,               UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIFramePacking                  (SEIFramePacking& sei,                  UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIDisplayOrientation            (SEIDisplayOrientation &sei,            UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIGreenMetadataInfo             (SEIGreenMetadataInfo& sei,             UInt payLoadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEISOPDescription                (SEISOPDescription &sei,                UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
   Void xParseSEIActiveParameterSets           (SEIActiveParameterSets  &sei,          UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
   Void xParseSEIDecodingUnitInfo              (SEIDecodingUnitInfo& sei,              UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEITemporalLevel0Index           (SEITemporalLevel0Index &sei,           UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
   Void xParseSEIDecodedPictureHash            (SEIDecodedPictureHash& sei,            UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
-  Void xParseSEIBufferingPeriod               (SEIBufferingPeriod& sei,               UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
-  Void xParseSEIPictureTiming                 (SEIPictureTiming& sei,                 UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
-  Void xParseSEIRecoveryPoint                 (SEIRecoveryPoint& sei,                 UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
-  Void xParseSEIFramePacking                  (SEIFramePacking& sei,                  UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
-  Void xParseSEISegmentedRectFramePacking     (SEISegmentedRectFramePacking& sei,     UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
-  Void xParseSEIDisplayOrientation            (SEIDisplayOrientation &sei,            UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
-  Void xParseSEITemporalLevel0Index           (SEITemporalLevel0Index &sei,           UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
-  Void xParseSEIRegionRefreshInfo             (SEIGradualDecodingRefreshInfo &sei,    UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
-  Void xParseSEINoDisplay                     (SEINoDisplay &sei,                     UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
-  Void xParseSEIToneMappingInfo               (SEIToneMappingInfo& sei,               UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
-  Void xParseSEISOPDescription                (SEISOPDescription &sei,                UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
 #if NH_MV
   Void xParseSEIScalableNesting               (SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, const TComVPS *vps, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
@@ -89,13 +96,19 @@
   Void xParseSEIScalableNesting               (SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, const TComSPS *sps, std::ostream *pDecodedMessageOutputStream);
 #endif
+  Void xParseSEIRegionRefreshInfo             (SEIRegionRefreshInfo &sei,             UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEINoDisplay                     (SEINoDisplay &sei,                     UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEITimeCode                      (SEITimeCode& sei,                      UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIMasteringDisplayColourVolume  (SEIMasteringDisplayColourVolume& sei,  UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEISegmentedRectFramePacking     (SEISegmentedRectFramePacking& sei,     UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
   Void xParseSEITempMotionConstraintsTileSets (SEITempMotionConstrainedTileSets& sei, UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
-  Void xParseSEITimeCode                      (SEITimeCode& sei,                      UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
   Void xParseSEIChromaResamplingFilterHint    (SEIChromaResamplingFilterHint& sei,    UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
   Void xParseSEIKneeFunctionInfo              (SEIKneeFunctionInfo& sei,              UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
-  Void xParseSEIMasteringDisplayColourVolume  (SEIMasteringDisplayColourVolume& sei,  UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
   Void xParseSEIColourRemappingInfo           (SEIColourRemappingInfo& sei,           UInt payloadSize,                     std::ostream *pDecodedMessageOutputStream);
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
-  Void xParseSEIAlternativeTransferCharacteristics(SEIAlternativeTransferCharacteristics& sei,              UInt payLoadSize,                     std::ostream *pDecodedMessageOutputStream);
-#endif
+  Void xParseSEIDeinterlaceFieldIdentification(SEIDeinterlaceFieldIdentification& sei,UInt payLoadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIContentLightLevelInfo         (SEIContentLightLevelInfo& sei,         UInt payLoadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIDependentRAPIndication        (SEIDependentRAPIndication& sei,        UInt payLoadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEICodedRegionCompletion         (SEICodedRegionCompletion& sei,         UInt payLoadSize,                     std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIAlternativeTransferCharacteristics(SEIAlternativeTransferCharacteristics& sei, UInt payLoadSize,            std::ostream *pDecodedMessageOutputStream);
+  Void xParseSEIAmbientViewingEnvironment     (SEIAmbientViewingEnvironment& sei,     UInt payLoadSize,                     std::ostream *pDecodedMessageOutputStream);
 #if NH_MV
   Void xParseSEILayersNotPresent              (SEILayersNotPresent &sei, UInt payloadSize, const TComVPS *vps ,std::ostream *pDecodedMessageOutputStream);
Index: /trunk/source/Lib/TLibDecoder/SyntaxElementParser.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/SyntaxElementParser.cpp	(revision 1413)
@@ -4,5 +4,5 @@
 * granted under this license.
 *
-* Copyright (c) 2010-2016, ITU/ISO/IEC
+* Copyright (c) 2010-2017, ITU/ISO/IEC
 * All rights reserved.
 *
@@ -49,4 +49,24 @@
 #if ENC_DEC_TRACE
 
+Void  xTraceAccessUnitDelimiter ()
+{
+  fprintf( g_hTrace, "=========== Access Unit Delimiter ===========\n");
+}
+
+Void xTraceFillerData ()
+{
+  fprintf( g_hTrace, "=========== Filler Data ===========\n");
+}
+
+#endif
+
+#if DECODER_PARTIAL_CONFORMANCE_CHECK!=0
+Void SyntaxElementParser::xReadCodeChk ( UInt   length, UInt& val, const TChar *pSymbolName, const UInt minValIncl, const UInt maxValIncl )
+{
+  READ_CODE(length, val, pSymbolName);
+  TDecConformanceCheck::checkRange(val, pSymbolName, minValIncl, maxValIncl);
+}
+#if NH_MV
+
 Void  SyntaxElementParser::xReadCodeTr           (UInt length, UInt& rValue, const TChar *pSymbolName)
 {
@@ -175,6 +195,4 @@
 }
 
-#endif
-
 
 // ====================================================================================================================
@@ -194,8 +212,59 @@
 }
 
-#if RExt__DECODER_DEBUG_BIT_STATISTICS
-Void SyntaxElementParser::xReadUvlc( UInt& ruiVal, const TChar *pSymbolName)
-#else
-Void SyntaxElementParser::xReadUvlc( UInt& ruiVal)
+#else
+
+Void SyntaxElementParser::xReadUvlcChk ( UInt&  val, const TChar *pSymbolName, const UInt minValIncl, const UInt maxValIncl )
+{
+  READ_UVLC(val, pSymbolName);
+  TDecConformanceCheck::checkRange(val, pSymbolName, minValIncl, maxValIncl);
+}
+
+Void SyntaxElementParser::xReadSvlcChk ( Int&   val, const TChar *pSymbolName, const Int  minValIncl, const Int  maxValIncl )
+{
+  READ_SVLC(val, pSymbolName);
+  TDecConformanceCheck::checkRange(val, pSymbolName, minValIncl, maxValIncl);
+}
+
+Void SyntaxElementParser::xReadFlagChk ( UInt&  val, const TChar *pSymbolName, const UInt minValIncl, const UInt maxValIncl )
+{
+  READ_FLAG(val, pSymbolName);
+  TDecConformanceCheck::checkRange(val, pSymbolName, minValIncl, maxValIncl);
+}
+#endif
+#endif
+
+// ====================================================================================================================
+// Protected member functions
+// ====================================================================================================================
+#if RExt__DECODER_DEBUG_BIT_STATISTICS || ENC_DEC_TRACE
+Void SyntaxElementParser::xReadCode (UInt uiLength, UInt& rValue, const TChar *pSymbolName)
+#else
+Void SyntaxElementParser::xReadCode (UInt uiLength, UInt& rValue)
+#endif
+{
+  assert ( uiLength > 0 );
+  m_pcBitstream->read (uiLength, rValue);
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(pSymbolName, uiLength, rValue);
+#endif
+#if ENC_DEC_TRACE
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  if (uiLength < 10)
+  {
+    fprintf( g_hTrace, "%-50s u(%d)  : %u\n", pSymbolName, uiLength, rValue );
+  }
+  else
+  {
+    fprintf( g_hTrace, "%-50s u(%d) : %u\n", pSymbolName, uiLength, rValue );
+  }
+  fflush ( g_hTrace );
+#endif
+}
+
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS || ENC_DEC_TRACE
+Void SyntaxElementParser::xReadUvlc( UInt& rValue, const TChar *pSymbolName)
+#else
+Void SyntaxElementParser::xReadUvlc( UInt& rValue)
 #endif
 {
@@ -226,14 +295,20 @@
   }
 
-  ruiVal = uiVal;
-#if RExt__DECODER_DEBUG_BIT_STATISTICS
-  TComCodingStatistics::IncrementStatisticEP(pSymbolName, Int(totalLen), ruiVal);
-#endif
-}
-
-#if RExt__DECODER_DEBUG_BIT_STATISTICS
-Void SyntaxElementParser::xReadSvlc( Int& riVal, const TChar *pSymbolName)
-#else
-Void SyntaxElementParser::xReadSvlc( Int& riVal)
+  rValue = uiVal;
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(pSymbolName, Int(totalLen), rValue);
+#endif
+
+#if ENC_DEC_TRACE
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s ue(v) : %u\n", pSymbolName, rValue );
+  fflush ( g_hTrace );
+#endif
+}
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS || ENC_DEC_TRACE
+Void SyntaxElementParser::xReadSvlc( Int& rValue, const TChar *pSymbolName)
+#else
+Void SyntaxElementParser::xReadSvlc( Int& rValue)
 #endif
 {
@@ -256,5 +331,5 @@
 
     uiBits += (1 << uiLength);
-    riVal = ( uiBits & 1) ? -(Int)(uiBits>>1) : (Int)(uiBits>>1);
+    rValue = ( uiBits & 1) ? -(Int)(uiBits>>1) : (Int)(uiBits>>1);
 #if RExt__DECODER_DEBUG_BIT_STATISTICS
     totalLen+=uiLength+uiLength;
@@ -263,28 +338,41 @@
   else
   {
-    riVal = 0;
-  }
-#if RExt__DECODER_DEBUG_BIT_STATISTICS
-  TComCodingStatistics::IncrementStatisticEP(pSymbolName, Int(totalLen), riVal);
-#endif
-}
-
-#if RExt__DECODER_DEBUG_BIT_STATISTICS
-Void SyntaxElementParser::xReadFlag (UInt& ruiCode, const TChar *pSymbolName)
-#else
-Void SyntaxElementParser::xReadFlag (UInt& ruiCode)
-#endif
-{
-  m_pcBitstream->read( 1, ruiCode );
-#if RExt__DECODER_DEBUG_BIT_STATISTICS
-  TComCodingStatistics::IncrementStatisticEP(pSymbolName, 1, Int(ruiCode));
+    rValue = 0;
+  }
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(pSymbolName, Int(totalLen), rValue);
+#endif
+
+#if ENC_DEC_TRACE
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s se(v) : %d\n", pSymbolName, rValue );
+  fflush ( g_hTrace );
+#endif
+
+}
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS || ENC_DEC_TRACE
+Void SyntaxElementParser::xReadFlag (UInt& rValue, const TChar *pSymbolName)
+#else
+Void SyntaxElementParser::xReadFlag (UInt& rValue)
+#endif
+{
+  m_pcBitstream->read( 1, rValue );
+#if RExt__DECODER_DEBUG_BIT_STATISTICS
+  TComCodingStatistics::IncrementStatisticEP(pSymbolName, 1, Int(rValue));
+#endif
+
+#if ENC_DEC_TRACE
+  fprintf( g_hTrace, "%8lld  ", g_nSymbolCounter++ );
+  fprintf( g_hTrace, "%-50s u(1)  : %d\n", pSymbolName, rValue );
+  fflush ( g_hTrace );
 #endif
 }
 
 #if NH_MV
-#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#if RExt__DECODER_DEBUG_BIT_STATISTICS || ENC_DEC_TRACE
 Void  SyntaxElementParser::xReadString  (UInt bufSize, UChar *pVal, UInt& rLength, const TChar *pSymbolName)
 #else
-Void  SyntaxElementParser::xReadString  (UInt bufSize, UChar *pVal, UInt& rLength)
+Void  SyntaxElementParser::xReadString  (UInt bufSize, UChar *pVal, UInt& rLength )
 #endif
 {
Index: /trunk/source/Lib/TLibDecoder/SyntaxElementParser.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/SyntaxElementParser.h	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/SyntaxElementParser.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -43,17 +43,23 @@
 #endif // _MSC_VER > 1000
 #include "TLibCommon/TComRom.h"
-#if ENC_DEC_TRACE
+#include "TDecConformance.h"
 
-#define READ_CODE(length, code, name)     xReadCodeTr ( length, code, name )
-#define READ_UVLC(        code, name)     xReadUvlcTr (         code, name )
-#define READ_SVLC(        code, name)     xReadSvlcTr (         code, name )
-#define READ_FLAG(        code, name)     xReadFlagTr (         code, name )
-#if NH_MV
-#define READ_STRING(bufSize, code, length, name)   xReadStringTr ( bufSize, code, length, name )
+#if DECODER_PARTIAL_CONFORMANCE_CHECK!=0
+#define READ_CODE_CHK(length, code, name, minValIncl, maxValIncl) xReadCodeChk ( length, code, name, minValIncl, maxValIncl )
+#define READ_UVLC_CHK(        code, name, minValIncl, maxValIncl) xReadUvlcChk (         code, name, minValIncl, maxValIncl )
+#define READ_SVLC_CHK(        code, name, minValIncl, maxValIncl) xReadSvlcChk (         code, name, minValIncl, maxValIncl )
+#define READ_FLAG_CHK(        code, name, minValIncl, maxValIncl) xReadFlagChk (         code, name, minValIncl, maxValIncl )
+#elif RExt__DECODER_DEBUG_BIT_STATISTICS || ENC_DEC_TRACE
+#define READ_CODE_CHK(length, code, name, minValIncl, maxValIncl) xReadCode ( length, code, name )
+#define READ_UVLC_CHK(        code, name, minValIncl, maxValIncl) xReadUvlc (         code, name )
+#define READ_SVLC_CHK(        code, name, minValIncl, maxValIncl) xReadSvlc (         code, name )
+#define READ_FLAG_CHK(        code, name, minValIncl, maxValIncl) xReadFlag (         code, name )
+#else
+#define READ_CODE_CHK(length, code, name, minValIncl, maxValIncl) xReadCode ( length, code )
+#define READ_UVLC_CHK(        code, name, minValIncl, maxValIncl) xReadUvlc (         code )
+#define READ_SVLC_CHK(        code, name, minValIncl, maxValIncl) xReadSvlc (         code )
+#define READ_FLAG_CHK(        code, name, minValIncl, maxValIncl) xReadFlag (         code )
 #endif
-#else
-
-#if RExt__DECODER_DEBUG_BIT_STATISTICS
-
+#if RExt__DECODER_DEBUG_BIT_STATISTICS || ENC_DEC_TRACE
 #define READ_CODE(length, code, name)     xReadCode ( length, code, name )
 #define READ_UVLC(        code, name)     xReadUvlc (         code, name )
@@ -64,5 +70,4 @@
 #endif
 #else
-
 #define READ_CODE(length, code, name)     xReadCode ( length, code )
 #define READ_UVLC(        code, name)     xReadUvlc (         code )
@@ -71,6 +76,4 @@
 #if NH_MV
 #define READ_STRING(bufSize, code, length, name)   xReadString ( bufSize, code, length )
-#endif
-
 #endif
 
@@ -94,5 +97,13 @@
   virtual ~SyntaxElementParser() {};
 
-#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#if DECODER_PARTIAL_CONFORMANCE_CHECK!=0
+  Void  xReadCodeChk ( UInt   length, UInt& val, const TChar *pSymbolName, const UInt minValIncl, const UInt maxValIncl );
+  Void  xReadUvlcChk ( UInt&  val, const TChar *pSymbolName, const UInt minValIncl, const UInt maxValIncl );
+  Void  xReadSvlcChk ( Int&   val, const TChar *pSymbolName, const Int  minValIncl, const Int  maxValIncl );
+  Void  xReadFlagChk ( UInt&  val, const TChar *pSymbolName, const UInt minValIncl, const UInt maxValIncl );
+#endif
+
+
+#if RExt__DECODER_DEBUG_BIT_STATISTICS || ENC_DEC_TRACE
   Void  xReadCode    ( UInt   length, UInt& val, const TChar *pSymbolName );
   Void  xReadUvlc    ( UInt&  val, const TChar *pSymbolName );
@@ -109,12 +120,4 @@
 #if NH_MV
   Void  xReadString  ( UInt bufSize, UChar *val, UInt& length);
-#endif
-#endif
-#if ENC_DEC_TRACE
-  Void  xReadCodeTr  (UInt  length, UInt& rValue, const TChar *pSymbolName);
-  Void  xReadUvlcTr  (              UInt& rValue, const TChar *pSymbolName);
-  Void  xReadSvlcTr  (               Int& rValue, const TChar *pSymbolName);
-  Void  xReadFlagTr  (              UInt& rValue, const TChar *pSymbolName);
-#if NH_MV
   Void  xReadStringTr(UInt bufSize, UChar *pValue, UInt& rLength, const TChar *pSymbolName);
 #endif
Index: /trunk/source/Lib/TLibDecoder/TDecBinCoder.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecBinCoder.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecBinCoderCABAC.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibDecoder/TDecCAVLC.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecCAVLC.cpp	(revision 1413)
@@ -4,5 +4,5 @@
 * granted under this license.
 *
-* Copyright (c) 2010-2016, ITU/ISO/IEC
+* Copyright (c) 2010-2017, ITU/ISO/IEC
 * All rights reserved.
 *
@@ -43,4 +43,6 @@
 #include "TLibCommon/TComCodingStatistics.h"
 #endif
+#include "TDecConformance.h"
+
 #if NH_MV
 #include "TDecTop.h"
@@ -244,9 +246,9 @@
   Int   iCode;
 
-  READ_UVLC( uiCode, "pps_pic_parameter_set_id");
+  READ_UVLC_CHK( uiCode, "pps_pic_parameter_set_id", 0, 63);
   assert(uiCode <= 63);
   pcPPS->setPPSId (uiCode);
 
-  READ_UVLC( uiCode, "pps_seq_parameter_set_id");
+  READ_UVLC_CHK( uiCode, "pps_seq_parameter_set_id", 0, 15);
   assert(uiCode <= 15);
   pcPPS->setSPSId (uiCode);
@@ -258,17 +260,17 @@
   READ_CODE(3, uiCode, "num_extra_slice_header_bits");                pcPPS->setNumExtraSliceHeaderBits(uiCode);
 
-  READ_FLAG ( uiCode, "sign_data_hiding_flag" ); pcPPS->setSignHideFlag( uiCode );
+  READ_FLAG ( uiCode, "sign_data_hiding_enabled_flag" );              pcPPS->setSignDataHidingEnabledFlag( uiCode );
 
   READ_FLAG( uiCode,   "cabac_init_present_flag" );            pcPPS->setCabacInitPresentFlag( uiCode ? true : false );
 
-  READ_UVLC(uiCode, "num_ref_idx_l0_default_active_minus1");
+  READ_UVLC_CHK(uiCode, "num_ref_idx_l0_default_active_minus1", 0, 14);
   assert(uiCode <= 14);
   pcPPS->setNumRefIdxL0DefaultActive(uiCode+1);
 
-  READ_UVLC(uiCode, "num_ref_idx_l1_default_active_minus1");
+  READ_UVLC_CHK(uiCode, "num_ref_idx_l1_default_active_minus1", 0, 14);
   assert(uiCode <= 14);
   pcPPS->setNumRefIdxL1DefaultActive(uiCode+1);
 
-  READ_SVLC(iCode, "init_qp_minus26" );                            pcPPS->setPicInitQPMinus26(iCode);
+  READ_SVLC_CHK(iCode, "init_qp_minus26", std::numeric_limits<Int>::min(), 25 );  pcPPS->setPicInitQPMinus26(iCode);
   READ_FLAG( uiCode, "constrained_intra_pred_flag" );              pcPPS->setConstrainedIntraPred( uiCode ? true : false );
   READ_FLAG( uiCode, "transform_skip_enabled_flag" );
@@ -285,10 +287,10 @@
     pcPPS->setMaxCuDQPDepth( 0 );
   }
-  READ_SVLC( iCode, "pps_cb_qp_offset");
+  READ_SVLC_CHK( iCode, "pps_cb_qp_offset", -12, 12);
   pcPPS->setQpOffset(COMPONENT_Cb, iCode);
   assert( pcPPS->getQpOffset(COMPONENT_Cb) >= -12 );
   assert( pcPPS->getQpOffset(COMPONENT_Cb) <=  12 );
 
-  READ_SVLC( iCode, "pps_cr_qp_offset");
+  READ_SVLC_CHK( iCode, "pps_cr_qp_offset", -12, 12);
   pcPPS->setQpOffset(COMPONENT_Cr, iCode);
   assert( pcPPS->getQpOffset(COMPONENT_Cr) >= -12 );
@@ -305,6 +307,6 @@
   pcPPS->setWPBiPred( uiCode==1 );
 
-  READ_FLAG( uiCode, "transquant_bypass_enable_flag");
-  pcPPS->setTransquantBypassEnableFlag(uiCode ? true : false);
+  READ_FLAG( uiCode, "transquant_bypass_enabled_flag");
+  pcPPS->setTransquantBypassEnabledFlag(uiCode ? true : false);
   READ_FLAG( uiCode, "tiles_enabled_flag"               );    pcPPS->setTilesEnabledFlag            ( uiCode == 1 );
   READ_FLAG( uiCode, "entropy_coding_sync_enabled_flag" );    pcPPS->setEntropyCodingSyncEnabledFlag( uiCode == 1 );
@@ -344,9 +346,7 @@
     }
 
-    if ((tileColumnsMinus1 + tileRowsMinus1) != 0)
-    {
+    assert ((tileColumnsMinus1 + tileRowsMinus1) != 0);
       READ_FLAG ( uiCode, "loop_filter_across_tiles_enabled_flag" );   pcPPS->setLoopFilterAcrossTilesEnabledFlag( uiCode ? true : false );
     }
-  }
   READ_FLAG( uiCode, "pps_loop_filter_across_slices_enabled_flag" );   pcPPS->setLoopFilterAcrossSlicesEnabledFlag( uiCode ? true : false );
   READ_FLAG( uiCode, "deblocking_filter_control_present_flag" );       pcPPS->setDeblockingFilterControlPresentFlag( uiCode ? true : false );
@@ -354,6 +354,6 @@
   {
     READ_FLAG( uiCode, "deblocking_filter_override_enabled_flag" );    pcPPS->setDeblockingFilterOverrideEnabledFlag( uiCode ? true : false );
-    READ_FLAG( uiCode, "pps_disable_deblocking_filter_flag" );         pcPPS->setPicDisableDeblockingFilterFlag(uiCode ? true : false );
-    if(!pcPPS->getPicDisableDeblockingFilterFlag())
+    READ_FLAG( uiCode, "pps_deblocking_filter_disabled_flag" );        pcPPS->setPPSDeblockingFilterDisabledFlag(uiCode ? true : false );
+    if(!pcPPS->getPPSDeblockingFilterDisabledFlag())
     {
       READ_SVLC ( iCode, "pps_beta_offset_div2" );                     pcPPS->setDeblockingFilterBetaOffsetDiv2( iCode );
@@ -502,5 +502,5 @@
                 READ_UVLC(uiCode, "diff_cu_chroma_qp_offset_depth"); ppsRangeExtension.setDiffCuChromaQpOffsetDepth(uiCode);
               UInt tableSizeMinus1 = 0;
-              READ_UVLC(tableSizeMinus1, "chroma_qp_offset_list_len_minus1");
+                READ_UVLC_CHK(tableSizeMinus1, "chroma_qp_offset_list_len_minus1", 0, MAX_QP_OFFSET_LIST_SIZE-1);
               assert(tableSizeMinus1 < MAX_QP_OFFSET_LIST_SIZE);
 
@@ -509,7 +509,7 @@
                 Int cbOffset;
                 Int crOffset;
-                READ_SVLC(cbOffset, "cb_qp_offset_list[i]");
+                  READ_SVLC_CHK(cbOffset, "cb_qp_offset_list[i]", -12, 12);
                 assert(cbOffset >= -12 && cbOffset <= 12); 
-                READ_SVLC(crOffset, "cr_qp_offset_list[i]");
+                  READ_SVLC_CHK(crOffset, "cr_qp_offset_list[i]", -12, 12);
                 assert(crOffset >= -12 && crOffset <= 12);
                 // table uses +1 for index (see comment inside the function)
@@ -546,5 +546,4 @@
 Void TDecCavlc::parsePps3dExtension( TComPPS* pcPPS )
 {
-#if NH_3D_DLT
   UInt uiCode = 0; 
   //
@@ -679,5 +678,5 @@
     }
   }
-#endif
+
 }
 #endif
@@ -885,5 +884,5 @@
   {
 #endif
-  READ_CODE( 3,  uiCode, "sps_max_sub_layers_minus1" );          pcSPS->setMaxTLayers   ( uiCode+1 );
+  READ_CODE_CHK( 3,  uiCode, "sps_max_sub_layers_minus1", 0, 6 );   pcSPS->setMaxTLayers   ( uiCode+1 );
   assert(uiCode <= 6);
 #if NH_MV
@@ -902,4 +901,5 @@
   {
     // sps_temporal_id_nesting_flag must be 1 when sps_max_sub_layers_minus1 is 0
+    TDecConformanceCheck::checkRange(uiCode, "sps_temporal_id_nesting_flag", 1U, 1U);
     assert( uiCode == 1 );
   }
@@ -911,5 +911,5 @@
   }
 #endif
-  READ_UVLC(     uiCode, "sps_seq_parameter_set_id" );           pcSPS->setSPSId( uiCode );
+  READ_UVLC_CHK( uiCode, "sps_seq_parameter_set_id", 0, 15 );           pcSPS->setSPSId( uiCode );
   assert(uiCode <= 15);
 #if NH_MV
@@ -926,13 +926,15 @@
 #endif
 
-  READ_UVLC(     uiCode, "chroma_format_idc" );                  pcSPS->setChromaFormatIdc( ChromaFormat(uiCode) );
+  READ_UVLC_CHK(     uiCode, "chroma_format_idc", 0, 3 );               pcSPS->setChromaFormatIdc( ChromaFormat(uiCode) );
   assert(uiCode <= 3);
   if( pcSPS->getChromaFormatIdc() == CHROMA_444 )
   {
-    READ_FLAG(     uiCode, "separate_colour_plane_flag");        assert(uiCode == 0);
-  }
-
-  READ_UVLC (    uiCode, "pic_width_in_luma_samples" );          pcSPS->setPicWidthInLumaSamples ( uiCode    );
-  READ_UVLC (    uiCode, "pic_height_in_luma_samples" );         pcSPS->setPicHeightInLumaSamples( uiCode    );
+    READ_FLAG_CHK(     uiCode, "separate_colour_plane_flag", 0, 0);
+    assert(uiCode == 0);
+  }
+
+  // pic_width_in_luma_samples and pic_height_in_luma_samples needs conformance checking - multiples of MinCbSizeY
+  READ_UVLC_CHK (    uiCode, "pic_width_in_luma_samples", 1, std::numeric_limits<UInt>::max()  );  pcSPS->setPicWidthInLumaSamples ( uiCode    );
+  READ_UVLC_CHK (    uiCode, "pic_height_in_luma_samples", 1, std::numeric_limits<UInt>::max() );  pcSPS->setPicHeightInLumaSamples( uiCode    );
   READ_FLAG(     uiCode, "conformance_window_flag");
   if (uiCode != 0)
@@ -948,8 +950,11 @@
   }
 #else
-    READ_UVLC(   uiCode, "conf_win_left_offset" );               conf.setWindowLeftOffset  ( uiCode * TComSPS::getWinUnitX( pcSPS->getChromaFormatIdc() ) );
-    READ_UVLC(   uiCode, "conf_win_right_offset" );              conf.setWindowRightOffset ( uiCode * TComSPS::getWinUnitX( pcSPS->getChromaFormatIdc() ) );
-    READ_UVLC(   uiCode, "conf_win_top_offset" );                conf.setWindowTopOffset   ( uiCode * TComSPS::getWinUnitY( pcSPS->getChromaFormatIdc() ) );
-    READ_UVLC(   uiCode, "conf_win_bottom_offset" );             conf.setWindowBottomOffset( uiCode * TComSPS::getWinUnitY( pcSPS->getChromaFormatIdc() ) );
+    const UInt subWidthC  = TComSPS::getWinUnitX( pcSPS->getChromaFormatIdc() );
+    const UInt subHeightC = TComSPS::getWinUnitY( pcSPS->getChromaFormatIdc() );
+    READ_UVLC(   uiCode, "conf_win_left_offset" );               conf.setWindowLeftOffset  ( uiCode * subWidthC );
+    READ_UVLC(   uiCode, "conf_win_right_offset" );              conf.setWindowRightOffset ( uiCode * subWidthC );
+    READ_UVLC(   uiCode, "conf_win_top_offset" );                conf.setWindowTopOffset   ( uiCode * subHeightC );
+    READ_UVLC(   uiCode, "conf_win_bottom_offset" );             conf.setWindowBottomOffset( uiCode * subHeightC );
+    TDecConformanceCheck::checkRange<UInt>(conf.getWindowLeftOffset()+conf.getWindowRightOffset(), "conformance window width in pixels", 0, pcSPS->getPicWidthInLumaSamples()-1);
 #endif
   }
@@ -960,5 +965,6 @@
 #endif
 
-  READ_UVLC(     uiCode, "bit_depth_luma_minus8" );
+  READ_UVLC_CHK(     uiCode, "bit_depth_luma_minus8", 0, 8 );
+  assert(uiCode <= 8);
 #if O0043_BEST_EFFORT_DECODING
   pcSPS->setStreamBitDepth(CHANNEL_TYPE_LUMA, 8 + uiCode);
@@ -968,6 +974,6 @@
     uiCode = forceDecodeBitDepth - 8;
   }
-#endif
   assert(uiCode <= 8);
+#endif
   pcSPS->setBitDepth(CHANNEL_TYPE_LUMA, 8 + uiCode);
 
@@ -978,5 +984,6 @@
 #endif
 
-  READ_UVLC( uiCode,    "bit_depth_chroma_minus8" );
+  READ_UVLC_CHK( uiCode,    "bit_depth_chroma_minus8", 0, 8 );
+  assert(uiCode <= 8);
 #if O0043_BEST_EFFORT_DECODING
   pcSPS->setStreamBitDepth(CHANNEL_TYPE_CHROMA, 8 + uiCode);
@@ -985,6 +992,6 @@
     uiCode = forceDecodeBitDepth - 8;
   }
-#endif
   assert(uiCode <= 8);
+#endif
   pcSPS->setBitDepth(CHANNEL_TYPE_CHROMA, 8 + uiCode);
 #if O0043_BEST_EFFORT_DECODING
@@ -997,6 +1004,5 @@
 #endif
 
-  READ_UVLC( uiCode,    "log2_max_pic_order_cnt_lsb_minus4" );   pcSPS->setBitsForPOC( 4 + uiCode );
-  assert(uiCode <= 12);
+  READ_UVLC_CHK( uiCode,    "log2_max_pic_order_cnt_lsb_minus4", 0, 12 );   pcSPS->setBitsForPOC( 4 + uiCode );
 
 #if NH_MV
@@ -1039,27 +1045,37 @@
 #endif
 
-  READ_UVLC( uiCode, "log2_min_luma_coding_block_size_minus3" );
-  Int log2MinCUSize = uiCode + 3;
-  pcSPS->setLog2MinCodingBlockSize(log2MinCUSize);
-  READ_UVLC( uiCode, "log2_diff_max_min_luma_coding_block_size" );
+  const UInt maxLog2CtbSize = TDecConformanceCheck::getMaxLog2CtbSize(*(pcSPS->getPTL()));
+  const UInt minLog2CtbSize = TDecConformanceCheck::getMinLog2CtbSize(*(pcSPS->getPTL()));
+  READ_UVLC_CHK( uiCode, "log2_min_luma_coding_block_size_minus3", 0, maxLog2CtbSize-3 );
+  assert(uiCode <= maxLog2CtbSize-3);
+  Int minCbLog2SizeY = uiCode + 3;
+  pcSPS->setLog2MinCodingBlockSize(minCbLog2SizeY);
+  
+    // Difference + log2MinCUSize must be <= maxLog2CtbSize
+  // Difference + log2MinCUSize must be >= minLog2CtbSize
+  const UInt minLog2DiffMaxMinLumaCodingBlockSize = minLog2CtbSize < minCbLog2SizeY ? 0 : minLog2CtbSize - minCbLog2SizeY;
+  const UInt maxLog2DiffMaxMinLumaCodingBlockSize = maxLog2CtbSize - minCbLog2SizeY;
+
+  READ_UVLC_CHK( uiCode, "log2_diff_max_min_luma_coding_block_size", minLog2DiffMaxMinLumaCodingBlockSize, maxLog2DiffMaxMinLumaCodingBlockSize);
+  assert(uiCode >= minLog2DiffMaxMinLumaCodingBlockSize && uiCode <= maxLog2DiffMaxMinLumaCodingBlockSize);
   pcSPS->setLog2DiffMaxMinCodingBlockSize(uiCode);
-  
-  if (pcSPS->getPTL()->getGeneralPTL()->getLevelIdc() >= Level::LEVEL5)
-  {
-    assert(log2MinCUSize + pcSPS->getLog2DiffMaxMinCodingBlockSize() >= 5);
-  }
-  
-  Int maxCUDepthDelta = uiCode;
-  pcSPS->setMaxCUWidth  ( 1<<(log2MinCUSize + maxCUDepthDelta) );
-  pcSPS->setMaxCUHeight ( 1<<(log2MinCUSize + maxCUDepthDelta) );
-  READ_UVLC( uiCode, "log2_min_luma_transform_block_size_minus2" );   pcSPS->setQuadtreeTULog2MinSize( uiCode + 2 );
-
-  READ_UVLC( uiCode, "log2_diff_max_min_luma_transform_block_size" ); pcSPS->setQuadtreeTULog2MaxSize( uiCode + pcSPS->getQuadtreeTULog2MinSize() );
+
+  const Int maxCUDepthDelta = uiCode;
+  const Int ctbLog2SizeY = minCbLog2SizeY + maxCUDepthDelta;
+  pcSPS->setMaxCUWidth  ( 1<<ctbLog2SizeY );
+  pcSPS->setMaxCUHeight ( 1<<ctbLog2SizeY );
+  READ_UVLC_CHK( uiCode, "log2_min_luma_transform_block_size_minus2", 0, minCbLog2SizeY-1-2 );
+  const UInt minTbLog2SizeY = uiCode + 2;
+  pcSPS->setQuadtreeTULog2MinSize( minTbLog2SizeY );
+
+  //  log2_diff <= Min(CtbLog2SizeY, 5) - minTbLog2SizeY
+  READ_UVLC_CHK( uiCode, "log2_diff_max_min_luma_transform_block_size", 0, min<UInt>(5U, ctbLog2SizeY) - minTbLog2SizeY );
+  pcSPS->setQuadtreeTULog2MaxSize( uiCode + pcSPS->getQuadtreeTULog2MinSize() );
   pcSPS->setMaxTrSize( 1<<(uiCode + pcSPS->getQuadtreeTULog2MinSize()) );
 
-  READ_UVLC( uiCode, "max_transform_hierarchy_depth_inter" );    pcSPS->setQuadtreeTUMaxDepthInter( uiCode+1 );
-  READ_UVLC( uiCode, "max_transform_hierarchy_depth_intra" );    pcSPS->setQuadtreeTUMaxDepthIntra( uiCode+1 );
-
-  Int addCuDepth = max (0, log2MinCUSize - (Int)pcSPS->getQuadtreeTULog2MinSize() );
+  READ_UVLC_CHK( uiCode, "max_transform_hierarchy_depth_inter", 0, ctbLog2SizeY - minTbLog2SizeY);    pcSPS->setQuadtreeTUMaxDepthInter( uiCode+1 );
+  READ_UVLC_CHK( uiCode, "max_transform_hierarchy_depth_intra", 0, ctbLog2SizeY - minTbLog2SizeY);    pcSPS->setQuadtreeTUMaxDepthIntra( uiCode+1 );
+
+  Int addCuDepth = max (0, minCbLog2SizeY - (Int)pcSPS->getQuadtreeTULog2MinSize() );
   pcSPS->setMaxTotalCUDepth( maxCUDepthDelta + addCuDepth  + getMaxCUDepthOffset(pcSPS->getChromaFormatIdc(), pcSPS->getQuadtreeTULog2MinSize()) );
 
@@ -1095,12 +1111,20 @@
   if( pcSPS->getUsePCM() )
   {
-    READ_CODE( 4, uiCode, "pcm_sample_bit_depth_luma_minus1" );          pcSPS->setPCMBitDepth    ( CHANNEL_TYPE_LUMA, 1 + uiCode );
-    READ_CODE( 4, uiCode, "pcm_sample_bit_depth_chroma_minus1" );        pcSPS->setPCMBitDepth    ( CHANNEL_TYPE_CHROMA, 1 + uiCode );
-    READ_UVLC( uiCode, "log2_min_pcm_luma_coding_block_size_minus3" );   pcSPS->setPCMLog2MinSize (uiCode+3);
-    READ_UVLC( uiCode, "log2_diff_max_min_pcm_luma_coding_block_size" ); pcSPS->setPCMLog2MaxSize ( uiCode+pcSPS->getPCMLog2MinSize() );
+#if O0043_BEST_EFFORT_DECODING
+    READ_CODE_CHK( 4, uiCode, "pcm_sample_bit_depth_luma_minus1",   0, pcSPS->getStreamBitDepth(CHANNEL_TYPE_LUMA) );    pcSPS->setPCMBitDepth    ( CHANNEL_TYPE_LUMA, 1 + uiCode );
+    READ_CODE_CHK( 4, uiCode, "pcm_sample_bit_depth_chroma_minus1", 0, pcSPS->getStreamBitDepth(CHANNEL_TYPE_LUMA) );    pcSPS->setPCMBitDepth    ( CHANNEL_TYPE_CHROMA, 1 + uiCode );
+#else
+    READ_CODE_CHK( 4, uiCode, "pcm_sample_bit_depth_luma_minus1",   0, pcSPS->getBitDepth(CHANNEL_TYPE_LUMA) );          pcSPS->setPCMBitDepth    ( CHANNEL_TYPE_LUMA, 1 + uiCode );
+    READ_CODE_CHK( 4, uiCode, "pcm_sample_bit_depth_chroma_minus1", 0, pcSPS->getBitDepth(CHANNEL_TYPE_CHROMA) );        pcSPS->setPCMBitDepth    ( CHANNEL_TYPE_CHROMA, 1 + uiCode );
+#endif
+    READ_UVLC_CHK( uiCode, "log2_min_pcm_luma_coding_block_size_minus3", std::min<UInt>(minCbLog2SizeY, 5 )-3, std::min<UInt>(ctbLog2SizeY, 5)-3);
+    const UInt log2MinIpcmCbSizeY = uiCode+3;
+    pcSPS->setPCMLog2MinSize (log2MinIpcmCbSizeY);
+    READ_UVLC_CHK( uiCode, "log2_diff_max_min_pcm_luma_coding_block_size", 0, (std::min<UInt>(ctbLog2SizeY,5) - log2MinIpcmCbSizeY) );
+    pcSPS->setPCMLog2MaxSize ( uiCode+pcSPS->getPCMLog2MinSize() );
     READ_FLAG( uiCode, "pcm_loop_filter_disable_flag" );                 pcSPS->setPCMFilterDisableFlag ( uiCode ? true : false );
   }
 
-  READ_UVLC( uiCode, "num_short_term_ref_pic_sets" );
+  READ_UVLC_CHK( uiCode, "num_short_term_ref_pic_sets", 0, 64 );
 
   assert(uiCode <= 64);
@@ -1132,5 +1156,5 @@
 #endif
   {
-    READ_UVLC( uiCode, "num_long_term_ref_pics_sps" );
+    READ_UVLC_CHK( uiCode, "num_long_term_ref_pics_sps", 0, 32 );
     pcSPS->setNumLongTermRefPicSPS(uiCode);
     for (UInt k = 0; k < pcSPS->getNumLongTermRefPicSPS(); k++)
@@ -1142,7 +1166,7 @@
     }
   }
-  READ_FLAG( uiCode, "sps_temporal_mvp_enable_flag" );            pcSPS->setTMVPFlagsPresent(uiCode);
-
-  READ_FLAG( uiCode, "sps_strong_intra_smoothing_enable_flag" );  pcSPS->setUseStrongIntraSmoothing(uiCode);
+  READ_FLAG( uiCode, "sps_temporal_mvp_enabled_flag" );           pcSPS->setSPSTemporalMVPEnabledFlag(uiCode);
+
+  READ_FLAG( uiCode, "strong_intra_smoothing_enable_flag" );      pcSPS->setUseStrongIntraSmoothing(uiCode);
 
   READ_FLAG( uiCode, "vui_parameters_present_flag" );             pcSPS->setVuiParametersPresentFlag(uiCode);
@@ -2135,9 +2159,5 @@
     for( Int j = 0; j  <=  vps->getMaxSubLayersInLayerSetMinus1( currLsIdx ); j++ )
     {  
-#if NH_3D_FIX_TICKET_114
       if( j > 0  &&  dpbSize.getSubLayerFlagInfoPresentFlag( i )  )  
-#else
-      if( j > 0  &&  dpbSize.getSubLayerDpbInfoPresentFlag( i, j )  )  
-#endif
       {
         READ_FLAG( uiCode, "sub_layer_dpb_info_present_flag" ); dpbSize.setSubLayerDpbInfoPresentFlag( i, j, uiCode == 1 );
@@ -2611,5 +2631,5 @@
     pcSlice->setRPS(rps);
   }
-  if (sps->getTMVPFlagsPresent())
+      if (sps->getSPSTemporalMVPEnabledFlag())
   {
     READ_FLAG( uiCode, "slice_temporal_mvp_enabled_flag" );
@@ -2881,5 +2901,5 @@
     }
 
-#if NH_3D_IC
+#if NH_3D
     else if(    pcSlice->getViewIndex() && ( pcSlice->getSliceType() == P_SLICE || pcSlice->getSliceType() == B_SLICE ) 
              && !pcSlice->getIsDepth() && vps->getNumRefListLayers( layerId ) > 0 
@@ -2903,5 +2923,5 @@
     {
       READ_UVLC( uiCode, "five_minus_max_num_merge_cand");
-#if NH_3D_IV_MERGE
+#if NH_3D
       pcSlice->setMaxNumMergeCand(( ( pcSlice->getMpiFlag() || pcSlice->getIvMvPredFlag() || pcSlice->getViewSynthesisPredFlag() ) ? MRG_MAX_NUM_CANDS_MEM : MRG_MAX_NUM_CANDS) - uiCode);
 #else
@@ -2960,5 +2980,5 @@
       if(pcSlice->getDeblockingFilterOverrideFlag())
       {
-        READ_FLAG ( uiCode, "slice_disable_deblocking_filter_flag" );   pcSlice->setDeblockingFilterDisable(uiCode ? 1 : 0);
+        READ_FLAG ( uiCode, "slice_deblocking_filter_disabled_flag" );   pcSlice->setDeblockingFilterDisable(uiCode ? 1 : 0);
         if(!pcSlice->getDeblockingFilterDisable())
         {
@@ -2973,5 +2993,5 @@
       else
       {
-        pcSlice->setDeblockingFilterDisable   ( pps->getPicDisableDeblockingFilterFlag() );
+        pcSlice->setDeblockingFilterDisable       ( pps->getPPSDeblockingFilterDisabledFlag() );
         pcSlice->setDeblockingFilterBetaOffsetDiv2( pps->getDeblockingFilterBetaOffsetDiv2() );
         pcSlice->setDeblockingFilterTcOffsetDiv2  ( pps->getDeblockingFilterTcOffsetDiv2() );
@@ -3298,7 +3318,18 @@
     ptl->setIntraConstraintFlag(false);
     ptl->setLowerBitRateConstraintFlag(true);
+    if (ptl->getProfileIdc() == Profile::MAIN10           || ptl->getProfileCompatibilityFlag(Profile::MAIN10))
+    {
+      READ_CODE(7, uiCode, PTL_TRACE_TEXT("reserved_zero_7bits"     ));
+      READ_FLAG(    uiCode, PTL_TRACE_TEXT("one_picture_only_constraint_flag")); ptl->setOnePictureOnlyConstraintFlag(uiCode != 0);
+      READ_CODE(16, uiCode, PTL_TRACE_TEXT("reserved_zero_35bits[0..15]"     ));
+      READ_CODE(16, uiCode, PTL_TRACE_TEXT("reserved_zero_35bits[16..31]"    ));
+      READ_CODE(3,  uiCode, PTL_TRACE_TEXT("reserved_zero_35bits[32..34]"    ));
+    }
+    else
+    {
     READ_CODE(16, uiCode, PTL_TRACE_TEXT("reserved_zero_43bits[0..15]"     ));
     READ_CODE(16, uiCode, PTL_TRACE_TEXT("reserved_zero_43bits[16..31]"    ));
     READ_CODE(11, uiCode, PTL_TRACE_TEXT("reserved_zero_43bits[32..42]"    ));
+  }
   }
 
@@ -3355,5 +3386,5 @@
 }
 
-#if NH_3D_DIS
+#if NH_3D
 Void TDecCavlc::parseDIS( TComDataCU* /*pcCU*/, UInt /*uiAbsPartIdx*/, UInt /*uiDepth*/ )
 {
@@ -3439,5 +3470,5 @@
   Int  iDQp;
 
-#if RExt__DECODER_DEBUG_BIT_STATISTICS
+#if RExt__DECODER_DEBUG_BIT_STATISTICS || ENC_DEC_TRACE
   READ_SVLC(iDQp, "delta_qp");
 #else
@@ -3497,17 +3528,15 @@
 }
 
-#if NH_3D_ARP
+#if NH_3D
 Void TDecCavlc::parseARPW( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
   assert(0);
 }
-#endif
-#if NH_3D_IC
+
 Void TDecCavlc::parseICFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
   assert(0);
 }
-#endif
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
+
 Void TDecCavlc::parseSDCFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
@@ -3515,10 +3544,8 @@
 }
 
-#endif
-#if NH_3D_DBBP
-  Void TDecCavlc::parseDBBPFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
-  {
-    assert(0);
-  }
+Void TDecCavlc::parseDBBPFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
+{
+  assert(0);
+}
 #endif
 // ====================================================================================================================
Index: /trunk/source/Lib/TLibDecoder/TDecCAVLC.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecCAVLC.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -121,5 +121,5 @@
         
   Void  parseSkipFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-#if NH_3D_DIS
+#if NH_3D
   Void  parseDIS             ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
 #endif
@@ -127,17 +127,9 @@
   Void parseMergeFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx );
   Void parseMergeIndex      ( TComDataCU* pcCU, UInt& ruiMergeIndex );
-#if NH_3D_ARP 
+#if NH_3D
   Void parseARPW            ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-#endif
-#if NH_3D_IC
   Void  parseICFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-#endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   Void  parseDeltaDC        ( TComDataCU* /*pcCU*/, UInt /*absPartIdx*/, UInt /*depth*/ ) { assert(0); };
-#endif
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   Void  parseSDCFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-#endif
-#if NH_3D_DBBP
   Void  parseDBBPFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
 #endif
Index: /trunk/source/Lib/TLibDecoder/TDecConformance.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecConformance.cpp	(revision 1413)
+++ /trunk/source/Lib/TLibDecoder/TDecConformance.cpp	(revision 1413)
@@ -0,0 +1,452 @@
+/* The copyright in this software is being made available under the BSD
+* License, included below. This software may be subject to other third party
+* and contributor rights, including patent rights, and no such rights are
+* granted under this license.
+*
+* Copyright (c) 2010-2017, ITU/ISO/IEC
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are met:
+*
+*  * Redistributions of source code must retain the above copyright notice,
+*    this list of conditions and the following disclaimer.
+*  * Redistributions in binary form must reproduce the above copyright notice,
+*    this list of conditions and the following disclaimer in the documentation
+*    and/or other materials provided with the distribution.
+*  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+*    be used to endorse or promote products derived from this software without
+*    specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+* THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/** \file     TDecConformance.cpp
+    \brief    Decoder conformance functions
+*/
+
+#include "TDecConformance.h"
+#include "TLibCommon/TComSlice.h"
+#include "TLibCommon/TComPic.h"
+#include "TLibCommon/TComPicSym.h"
+#include "NALread.h"
+#include <math.h>
+
+UInt
+LevelTierFeatures::getMaxPicWidthInLumaSamples()  const
+{
+  return UInt(sqrt(maxLumaPs*8.0));
+}
+
+UInt
+LevelTierFeatures::getMaxPicHeightInLumaSamples() const
+{
+  return UInt(sqrt(maxLumaPs*8.0));
+}
+
+UInt
+TDecConformanceCheck::getMinLog2CtbSize(const TComPTL &ptl,
+                                        UInt layerPlus1)
+{
+  const ProfileTierLevel *pPTL = (layerPlus1==0) ? ptl.getGeneralPTL() : ptl.getSubLayerPTL(layerPlus1-1);
+  return (pPTL->getLevelIdc() < Level::LEVEL5) ? 4 : 5;
+}
+
+
+UInt
+TDecConformanceCheck::getMaxLog2CtbSize(const TComPTL &/*ptl*/,
+                                        UInt /*layerPlus1*/)
+{
+  return MAX_CU_DEPTH;
+}
+
+
+TDecConformanceCheck::TDecConformanceCheck()
+#if MCTS_ENC_CHECK
+  :m_tmctsCheckEnabled(false)
+#if DECODER_PARTIAL_CONFORMANCE_CHECK
+  , m_numberOfSlicesInPicture(0)
+  , m_bytesInPicture(0)
+#endif
+#else
+#if DECODER_PARTIAL_CONFORMANCE_CHECK
+  : m_numberOfSlicesInPicture(0)
+  , m_bytesInPicture(0)
+#endif
+#endif
+{
+}
+
+#if DECODER_PARTIAL_CONFORMANCE_CHECK != 0
+
+static const UInt64 MAX_CNFUINT64 = std::numeric_limits<UInt64>::max();
+
+static const LevelTierFeatures mainLevelTierInfo[] =
+{
+    { Level::LEVEL1  ,    36864, {      350,        0 },       16,        1,        1,     552960ULL, {     128,        0 }, { 2, 2} },
+    { Level::LEVEL2  ,   122880, {     1500,        0 },       16,        1,        1,    3686400ULL, {    1500,        0 }, { 2, 2} },
+    { Level::LEVEL2_1,   245760, {     3000,        0 },       20,        1,        1,    7372800ULL, {    3000,        0 }, { 2, 2} },
+    { Level::LEVEL3  ,   552960, {     6000,        0 },       30,        2,        2,   16588800ULL, {    6000,        0 }, { 2, 2} },
+    { Level::LEVEL3_1,   983040, {    10000,        0 },       40,        3,        3,   33177600ULL, {   10000,        0 }, { 2, 2} },
+    { Level::LEVEL4  ,  2228224, {    12000,    30000 },       75,        5,        5,   66846720ULL, {   12000,    30000 }, { 4, 4} },
+    { Level::LEVEL4_1,  2228224, {    20000,    50000 },       75,        5,        5,  133693440ULL, {   20000,    50000 }, { 4, 4} },
+    { Level::LEVEL5  ,  8912896, {    25000,   100000 },      200,       11,       10,  267386880ULL, {   25000,   100000 }, { 6, 4} },
+    { Level::LEVEL5_1,  8912896, {    40000,   160000 },      200,       11,       10,  534773760ULL, {   40000,   160000 }, { 8, 4} },
+    { Level::LEVEL5_2,  8912896, {    60000,   240000 },      200,       11,       10, 1069547520ULL, {   60000,   240000 }, { 8, 4} },
+    { Level::LEVEL6  , 35651584, {    60000,   240000 },      600,       22,       20, 1069547520ULL, {   60000,   240000 }, { 8, 4} },
+    { Level::LEVEL6_1, 35651584, {   120000,   480000 },      600,       22,       20, 2139095040ULL, {  120000,   480000 }, { 8, 4} },
+    { Level::LEVEL6_2, 35651584, {   240000,   800000 },      600,       22,       20, 4278190080ULL, {  240000,   800000 }, { 6, 4} },
+    { Level::LEVEL8_5, MAX_UINT, { MAX_UINT, MAX_UINT }, MAX_UINT, MAX_UINT, MAX_UINT, MAX_CNFUINT64, {MAX_UINT, MAX_UINT }, { 0, 0} },
+    { Level::NONE                   }
+};
+
+static const ProfileFeatures validProfiles[] =
+{   //  profile,                   pNameString,             maxBitDepth, maxChrFmt, intra, 1pic,   lowerBR, RExtTools, ExtPrec , ChrmQPOf, align,    HBRFactor,   , wve+t,  tiles,, lvl8.5, cpbvcl, cpbnal, fcf*1000, mincr*10
+    { Profile::MAIN,               "Main",                            8, CHROMA_420, false, false, ENABLED , DISABLED, DISABLED, DISABLED, DISABLED, HBR_1        , false, 256, 64, false,   1000,   1100,     1500,   10    , mainLevelTierInfo },
+    { Profile::MAIN10,             "Main10",                         10, CHROMA_420, false, false, ENABLED , DISABLED, DISABLED, DISABLED, DISABLED, HBR_1        , false, 256, 64, false,   1000,   1100,     1875,   10    , mainLevelTierInfo },
+    { Profile::MAIN10,             "Main10 Still Picture",           10, CHROMA_420, false,  true, ENABLED , DISABLED, DISABLED, DISABLED, DISABLED, HBR_1        , false, 256, 64, true ,   1000,   1100,     1875,   10    , mainLevelTierInfo },
+    { Profile::MAINSTILLPICTURE,   "Main Still Picture",              8, CHROMA_420, false, false, ENABLED , DISABLED, DISABLED, DISABLED, DISABLED, HBR_1        , false, 256, 64, true ,   1000,   1100,     1500,   10    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Monochrome",                      8, CHROMA_400, false, false, ENABLED , DISABLED, DISABLED, DISABLED, DISABLED, HBR_1_OR_2   , false, 256, 64, false,    667,    733,     1000,   10    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Monochrome 12",                  12, CHROMA_400, false, false, ENABLED , DISABLED, DISABLED, DISABLED, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   1000,   1100,     1500,   10    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Monochrome 16",                  16, CHROMA_400, false, false, ENABLED , OPTIONAL, OPTIONAL, DISABLED, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   1333,   1467,     2000,   10    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main 12",                        12, CHROMA_420, false, false, ENABLED , DISABLED, DISABLED, DISABLED, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   1500,   1650,     2250,   10    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main 4:2:2 10",                  10, CHROMA_422, false, false, ENABLED , DISABLED, DISABLED, OPTIONAL, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   1667,   1833,     2500,    5    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main 4:2:2 12",                  12, CHROMA_422, false, false, ENABLED , DISABLED, DISABLED, OPTIONAL, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   2000,   2200,     3000,    5    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main 4:4:4",                      8, CHROMA_444, false, false, ENABLED , OPTIONAL, DISABLED, OPTIONAL, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   2000,   2200,     3000,    5    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main 4:4:4 10",                  10, CHROMA_444, false, false, ENABLED , OPTIONAL, DISABLED, OPTIONAL, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   2500,   2750,     3750,    5    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main 4:4:4 12",                  12, CHROMA_444, false, false, ENABLED , OPTIONAL, DISABLED, OPTIONAL, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   3000,   3300,     4500,    5    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main Intra",                      8, CHROMA_420, true , false, OPTIONAL, DISABLED, DISABLED, DISABLED, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   1000,   1100,     1500,   10    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main 10 Intra",                  10, CHROMA_420, true , false, OPTIONAL, DISABLED, DISABLED, DISABLED, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   1000,   1100,     1875,   10    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main 12 Intra",                  12, CHROMA_420, true , false, OPTIONAL, DISABLED, DISABLED, DISABLED, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   1500,   1650,     2250,   10    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main 4:2:2 10 Intra",            10, CHROMA_422, true , false, OPTIONAL, DISABLED, DISABLED, OPTIONAL, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   1667,   1833,     2500,    5    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main 4:2:2 12 Intra",            12, CHROMA_422, true , false, OPTIONAL, DISABLED, DISABLED, OPTIONAL, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   2000,   2200,     3000,    5    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main 4:4:4 Intra",                8, CHROMA_444, true , false, OPTIONAL, OPTIONAL, DISABLED, OPTIONAL, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   2000,   2200,     3000,    5    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main 4:4:4 10 Intra",            10, CHROMA_444, true , false, OPTIONAL, OPTIONAL, DISABLED, OPTIONAL, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   2500,   2750,     3750,    5    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main 4:4:4 12 Intra",            12, CHROMA_444, true , false, OPTIONAL, OPTIONAL, DISABLED, OPTIONAL, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   3000,   3300,     4500,    5    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main 4:4:4 16 Intra",            16, CHROMA_444, true , false, OPTIONAL, OPTIONAL, OPTIONAL, OPTIONAL, DISABLED, HBR_1_OR_2   , false, 256, 64, false,   4000,   4400,     6000,    5    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main 4:4:4 Still Picture",        8, CHROMA_444, true , true , OPTIONAL, OPTIONAL, DISABLED, OPTIONAL, DISABLED, HBR_1_OR_2   , false, 256, 64, true ,   2000,   2200,     3000,    5    , mainLevelTierInfo },
+    { Profile::MAINREXT,           "Main 4:4:4 16 Still Picture",    16, CHROMA_444, true , true , OPTIONAL, OPTIONAL, OPTIONAL, OPTIONAL, DISABLED, HBR_1_OR_2   , false, 256, 64, true ,   4000,   4400,     6000,    5    , mainLevelTierInfo },
+    { Profile::HIGHTHROUGHPUTREXT, "High Throughput 4:4:4 16 Intra", 16, CHROMA_444, true , false, OPTIONAL, OPTIONAL, OPTIONAL, OPTIONAL, ENABLED , HBR_12_OR_24 , true , 256, 64, false,   4000,   4400,     6000,    5    , mainLevelTierInfo },
+    { Profile::NONE, 0 }
+};
+
+
+
+
+static Void
+checkSPS(const TComSPS &sps,
+         const ProfileLevelTierFeatures &features)
+{
+  // sps_max_sub_layers_minus1 shall be less than or equal to vsp_max_sub_layers_minus1
+
+  // TODO - check conformance of sps_max_dec_pic_buffering_minus1, sps_max_num_reorder_pics, sps_max_latency_increase_plus1
+  //        needs VPS, which can only be done on activation.
+
+  const UInt minCbSizeY = 1<<(sps.getLog2MinCodingBlockSize());
+
+  if (sps.getPicWidthInLumaSamples() % minCbSizeY != 0 )
+  {
+    TDecConformanceCheck::getStream() << "picture width (" << sps.getPicWidthInLumaSamples() << ") must be a multiple of minCbSizeY (=" << minCbSizeY << ")\n";
+    TDecConformanceCheck::finishWarningReport();
+  }
+
+  if (sps.getPicHeightInLumaSamples() % minCbSizeY != 0 )
+  {
+    TDecConformanceCheck::getStream() << "picture height (" << sps.getPicHeightInLumaSamples() << ") must be a multiple of minCbSizeY (=" << minCbSizeY << ")\n";
+    TDecConformanceCheck::finishWarningReport();
+  }
+
+
+  if (sps.getPicWidthInLumaSamples() > features.getLevelTierFeatures()->getMaxPicWidthInLumaSamples())
+  {
+    TDecConformanceCheck::getStream() << "picture width (" << sps.getPicWidthInLumaSamples() << ") exceeds the maximum allowed by the level (" << features.getLevelTierFeatures()->getMaxPicWidthInLumaSamples() << ")\n";
+    TDecConformanceCheck::finishWarningReport();
+  }
+
+  if (sps.getPicHeightInLumaSamples() > features.getLevelTierFeatures()->getMaxPicHeightInLumaSamples())
+  {
+    TDecConformanceCheck::getStream() << "picture height (" << sps.getPicHeightInLumaSamples() << ") exceeds the maximum allowed by the level (" << features.getLevelTierFeatures()->getMaxPicHeightInLumaSamples() << ")\n";
+    TDecConformanceCheck::finishWarningReport();
+  }
+
+  if (sps.getPicWidthInLumaSamples() * sps.getPicHeightInLumaSamples() > features.getLevelTierFeatures()->maxLumaPs)
+  {
+    TDecConformanceCheck::getStream() << "picture samples (" << sps.getPicWidthInLumaSamples() << " * " << sps.getPicHeightInLumaSamples() << ") exceeds the maximum allowed by the level (" << features.getLevelTierFeatures()->maxLumaPs << ")\n";
+    TDecConformanceCheck::finishWarningReport();
+  }
+}
+
+
+static Void
+checkTiles(const TComSPS &sps,
+           const TComPPS &pps,
+           const TComPic &pic,
+           const ProfileLevelTierFeatures &features)
+{
+  if (pps.getTilesEnabledFlag())
+  {
+    // Tile size check
+    const Int minWidthInCtus  = features.getProfileFeatures()->minTileColumnWidthInLumaSamples/ sps.getMaxCUWidth();
+    const Int minHeightInCtus = features.getProfileFeatures()->minTileRowHeightInLumaSamples  / sps.getMaxCUHeight();
+
+    const Int numCols = pps.getNumTileColumnsMinus1() + 1;
+    const Int numRows = pps.getNumTileRowsMinus1() + 1;
+    if (numCols > features.getLevelTierFeatures()->maxTileCols)
+    {
+      TDecConformanceCheck::getStream() << "number of tile columns (" << numCols << ") exceeds the maximum allowed by the level (" << features.getLevelTierFeatures()->maxTileCols << ")\n";
+      TDecConformanceCheck::finishWarningReport();
+    }
+    if (numRows > features.getLevelTierFeatures()->maxTileRows)
+    {
+      TDecConformanceCheck::getStream() << "number of tile rows (" << numRows << ") exceeds the maximum allowed by the level (" << features.getLevelTierFeatures()->maxTileRows << ")\n";
+      TDecConformanceCheck::finishWarningReport();
+    }
+
+    for(Int row=0; row < numRows; row++)
+    {
+      for(Int col=0; col < numCols; col++)
+      {
+        const Int tileIdx = row * numCols + col;
+        const TComTile &tile = *(pic.getPicSym()->getTComTile(tileIdx));
+        if (tile.getTileWidthInCtus() < minWidthInCtus)
+        {
+          TDecConformanceCheck::getStream() << "width of tile (" << col << ", " << row << ") is too narrow for the profile - read " << tile.getTileWidthInCtus()*sps.getMaxCUWidth() << "must be " << minWidthInCtus*sps.getMaxCUWidth() << "\n";
+          TDecConformanceCheck::finishWarningReport();
+        }
+        if (tile.getTileHeightInCtus() < minHeightInCtus)
+        {
+          TDecConformanceCheck::getStream() << "height of tile (" << col << ", " << row << ") is too thin for the profile - read " << tile.getTileHeightInCtus()*sps.getMaxCUHeight() << " must be " << minHeightInCtus*sps.getMaxCUHeight() << "\n";
+          TDecConformanceCheck::finishWarningReport();
+        }
+      }
+    }
+
+    if (pps.getEntropyCodingSyncEnabledFlag() && !features.getProfileFeatures()->bWavefrontsAndTilesCanBeUsedSimultaneously)
+    {
+      TDecConformanceCheck::getStream() << "profile does not permit entropy coding sync and tiles to be simultaneously enabled\n";
+      TDecConformanceCheck::finishWarningReport();
+    }
+  }
+}
+
+
+static Void
+checkPPS(const TComSPS &sps,
+         const TComPPS &pps,
+         const TComPic &pic,
+         const ProfileLevelTierFeatures &features)
+{
+  TDecConformanceCheck::checkRange<Int>(pps.getPicInitQPMinus26(), "init_qp_minus26",     -(sps.getBitDepth(CHANNEL_TYPE_LUMA)-8)*6-26, 25);
+  TDecConformanceCheck::checkRange<UInt>(pps.getMaxCuDQPDepth(), "diff_cu_qp_delta_depth", 0, sps.getLog2DiffMaxMinCodingBlockSize());
+  TDecConformanceCheck::checkRange<UInt>(pps.getLog2ParallelMergeLevelMinus2(), "log2_parallel_merge_level_minus2", 0, sps.getLog2MinCodingBlockSize() + sps.getLog2DiffMaxMinCodingBlockSize() - 2);
+
+  TDecConformanceCheck::checkRange<UInt>(pps.getPpsRangeExtension().getLog2SaoOffsetScale(CHANNEL_TYPE_LUMA), "log2_sao_offset_scale_luma", 0, std::max(sps.getBitDepth(CHANNEL_TYPE_LUMA), 10)-10);
+  TDecConformanceCheck::checkRange<UInt>(pps.getPpsRangeExtension().getLog2SaoOffsetScale(CHANNEL_TYPE_CHROMA), "log2_sao_offset_scale_chroma", 0, std::max(sps.getBitDepth(CHANNEL_TYPE_CHROMA), 10)-10);
+
+  checkTiles(sps, pps, pic, features);
+}
+
+
+Void
+ProfileLevelTierFeatures::activate(const TComSPS &sps)
+{
+  const ProfileTierLevel &ptl = *(sps.getPTL()->getGeneralPTL());
+
+  m_tier = ptl.getTierFlag();
+
+  for(Int i=0; validProfiles[i].profile != Profile::NONE; i++)
+  {
+    if (ptl.getProfileIdc() == validProfiles[i].profile &&
+        ptl.getBitDepthConstraint() == validProfiles[i].maxBitDepth &&
+        ptl.getChromaFormatConstraint() == validProfiles[i].maxChromaFormat &&
+        ptl.getIntraConstraintFlag() == validProfiles[i].generalIntraConstraintFlag &&
+        ptl.getOnePictureOnlyConstraintFlag() == validProfiles[i].generalOnePictureOnlyConstraintFlag )
+    {
+      m_pProfile = &(validProfiles[i]);
+      break;
+    }
+  }
+
+  if (m_pProfile != 0)
+  {
+    // Now identify the level:
+    const LevelTierFeatures *pLTF = m_pProfile->pLevelTiersListInfo;
+    const Level::Name spsLevelName = sps.getPTL()->getGeneralPTL()->getLevelIdc();
+    if (spsLevelName!=Level::LEVEL8_5 || m_pProfile->bCanUseLevel8p5)
+    {
+      for(Int i=0; pLTF[i].level!=Level::NONE; i++)
+      {
+        if (pLTF[i].level == spsLevelName)
+        {
+          m_pLevelTier = &(pLTF[i]);
+        }
+      }
+    }
+  }
+
+  {
+    const UInt ctbSizeY   = sps.getMaxCUWidth();
+    const UInt bitDepthY  = sps.getBitDepth(CHANNEL_TYPE_LUMA);
+    const UInt ctbWidthC  = ctbSizeY >> getChannelTypeScaleX(CHANNEL_TYPE_CHROMA, sps.getChromaFormatIdc());
+    const UInt ctbHeightC = ctbSizeY >> getChannelTypeScaleY(CHANNEL_TYPE_CHROMA, sps.getChromaFormatIdc());
+    const UInt bitDepthC  = sps.getBitDepth(CHANNEL_TYPE_LUMA);
+
+    const UInt rawCtuBits = ctbSizeY*ctbSizeY*bitDepthY+2*(ctbWidthC*ctbHeightC)*bitDepthC;
+    m_maxRawCtuBits=(rawCtuBits*5)/3;
+  }
+
+}
+
+
+static Void
+checkToolAvailability(const TComSPS &sps,
+                      const TComPPS &pps,
+                      const ProfileLevelTierFeatures &features)
+{
+  const TRISTATE rextToolsEnabled = features.getProfileFeatures()->generalRExtToolsEnabled;
+  if ( rextToolsEnabled != OPTIONAL)
+  {
+    const Bool bWantedFlagState = rextToolsEnabled == ENABLED;
+    std::string flags;
+    if (sps.getSpsRangeExtension().getTransformSkipRotationEnabledFlag()      != bWantedFlagState) flags+=", transform_skip_rotation_enabled_flag";
+    if (sps.getSpsRangeExtension().getTransformSkipContextEnabledFlag()       != bWantedFlagState) flags+=", transform_skip_context_enabled_flag";
+    if (sps.getSpsRangeExtension().getRdpcmEnabledFlag(RDPCM_SIGNAL_IMPLICIT) != bWantedFlagState) flags+=", implicit_rdpcm_enabled_flag";
+    if (sps.getSpsRangeExtension().getRdpcmEnabledFlag(RDPCM_SIGNAL_EXPLICIT) != bWantedFlagState) flags+=", explicit_rdpcm_enabled_flag";
+    if (sps.getSpsRangeExtension().getIntraSmoothingDisabledFlag()            != bWantedFlagState) flags+=", intra_smoothing_disabled_flag";
+    if (sps.getSpsRangeExtension().getPersistentRiceAdaptationEnabledFlag()   != bWantedFlagState) flags+=", persistent_rice_adaptation_enabled_flag";
+    if (pps.getPpsRangeExtension().getLog2MaxTransformSkipBlockSize()         != 2 && rextToolsEnabled==DISABLED ) flags+=", log2_max_transform_skip_block_size_minus2";
+
+    if (!flags.empty())
+    {
+      TDecConformanceCheck::getStream() << "the following flags must all be " << (bWantedFlagState ? "1" : "0") << " in the profile '" << features.getProfileFeatures()->pNameString << "' conformance point: " + flags.substr(2) + "\n";
+      TDecConformanceCheck::finishWarningReport();
+    }
+  }
+  else
+  {
+    TDecConformanceCheck::checkRange<UInt>(pps.getPpsRangeExtension().getLog2MaxTransformSkipBlockSize()-2, "log2_max_transform_skip_block_size_minus2", 0, sps.getQuadtreeTULog2MaxSize()-2);
+  }
+
+  if (features.getProfileFeatures()->extendedPrecisionProcessingFlag != OPTIONAL)
+  {
+    const Bool bWantedFlagState = features.getProfileFeatures()->extendedPrecisionProcessingFlag == ENABLED;
+    if (sps.getSpsRangeExtension().getExtendedPrecisionProcessingFlag() != bWantedFlagState)
+    {
+      TDecConformanceCheck::getStream() << "extended_precision_processing_flag must be " << (bWantedFlagState ? "1" : "0") << " in the profile '" << features.getProfileFeatures()->pNameString << "' conformance point\n";
+      TDecConformanceCheck::finishWarningReport();
+    }
+  }
+
+  if (features.getProfileFeatures()->chromaQpOffsetListEnabledFlag != OPTIONAL)
+  {
+    const Bool bWantedFlagState = features.getProfileFeatures()->chromaQpOffsetListEnabledFlag == ENABLED;
+    if (pps.getPpsRangeExtension().getChromaQpOffsetListEnabledFlag() != bWantedFlagState)
+    {
+      TDecConformanceCheck::getStream() << "chroma_qp_offset_list_enabled_flag must be " << (bWantedFlagState ? "1" : "0") << " in the profile '" << features.getProfileFeatures()->pNameString << "' conformance point\n";
+      TDecConformanceCheck::finishWarningReport();
+    }
+  }
+  else if (pps.getPpsRangeExtension().getChromaQpOffsetListEnabledFlag())
+  {
+    TDecConformanceCheck::checkRange<UInt>(pps.getPpsRangeExtension().getDiffCuChromaQpOffsetDepth(), "diff_cu_chroma_qp_offset_depth", 0, sps.getLog2DiffMaxMinCodingBlockSize());
+  }
+
+  if (features.getProfileFeatures()->cabacBypassAlignmentEnabledFlag != OPTIONAL)
+  {
+    const Bool bWantedFlagState = features.getProfileFeatures()->cabacBypassAlignmentEnabledFlag == ENABLED;
+    if (sps.getSpsRangeExtension().getCabacBypassAlignmentEnabledFlag() != bWantedFlagState)
+    {
+      TDecConformanceCheck::getStream() << "cabac_bypass_alignment_enabled_flag must be " << (bWantedFlagState ? "1" : "0") << " in the profile '" << features.getProfileFeatures()->pNameString << "' conformance point\n";
+      TDecConformanceCheck::finishWarningReport();
+    }
+  }
+}
+
+
+Void
+TDecConformanceCheck::checkSliceActivation(const TComSlice &slice,
+                                           const InputNALUnit &nalu,
+                                           const TComPic &pic,
+                                           const Bool bFirstSliceInStream,
+                                           const Bool bFirstSliceInSequence,
+                                           const Bool bFirstSliceInPicture)
+{
+  const TComSPS &sps=*(slice.getSPS());
+  const TComPPS &pps=*(slice.getPPS());
+
+  if (!doChecking()) return;
+
+  m_activatedFeatures.activate(sps);
+
+  if (m_activatedFeatures.getProfileFeatures() == 0 || m_activatedFeatures.getLevelTierFeatures() == 0)
+  {
+    if (m_activatedFeatures.getProfileFeatures() == 0)
+    {
+      getStream() << "Unknown profile/constraint flag combination discovered\n";
+    }
+    else
+    {
+      getStream() << "Unknown level IDC discovered\n";
+    }
+    finishWarningReport();
+  }
+  else
+  {
+    // Most of the parameters have been individually checked prior to this as they were decoded.
+    checkSPS(sps, m_activatedFeatures);           // checks SPS limits
+    checkPPS(sps, pps, pic, m_activatedFeatures); // checks PPS limits
+    checkToolAvailability(sps, pps, m_activatedFeatures);
+
+    if (m_activatedFeatures.getProfileFeatures()->onlyIRAPPictures() && (nalu.m_nalUnitType < NAL_UNIT_CODED_SLICE_BLA_W_LP || nalu.m_nalUnitType> NAL_UNIT_RESERVED_IRAP_VCL23))
+    {
+      getStream() << "Bad NALU for an intra constrained profile\n";
+      finishWarningReport();
+    }
+
+    if (bFirstSliceInStream || bFirstSliceInSequence || bFirstSliceInPicture)
+    {
+      m_numberOfSlicesInPicture=1;
+      m_bytesInPicture=0;
+    }
+    else
+    {
+      m_numberOfSlicesInPicture++;
+      if (m_numberOfSlicesInPicture > m_activatedFeatures.getLevelTierFeatures()->maxSliceSegmentsPerPicture)
+      {
+        getStream() << "Too many slice segments in the picture\n";
+        finishWarningReport();
+      }
+    }
+
+    // Currently no HRD analysis is made. For now, just ensure access unit fits within the CPB.
+    m_bytesInPicture+=nalu.getBitstream().getFifo().size();
+    if (m_bytesInPicture*8 > m_activatedFeatures.getCpbSizeInBits())
+    {
+      getStream() << "Entire access unit must fit within the CPB even if split into multiple decoding units (section C.2.2 Timing of decoding unit arrival)\n";
+      finishWarningReport();
+    }
+  }
+}
+
+
+Void
+TDecConformanceCheck::checkCtuDecoding(const UInt numUsedBits)
+{
+  if (numUsedBits > m_activatedFeatures.getMaxRawCtuBits())
+  {
+    getStream() << "CTU exceeds maximum RAW CTU bits limits.\n";
+    finishWarningReport();
+  }
+}
+
+#endif
Index: /trunk/source/Lib/TLibDecoder/TDecConformance.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecConformance.h	(revision 1413)
+++ /trunk/source/Lib/TLibDecoder/TDecConformance.h	(revision 1413)
@@ -0,0 +1,264 @@
+/* The copyright in this software is being made available under the BSD
+ * License, included below. This software may be subject to other third party
+ * and contributor rights, including patent rights, and no such rights are
+ * granted under this license.
+ *
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ *  * Redistributions of source code must retain the above copyright notice,
+ *    this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright notice,
+ *    this list of conditions and the following disclaimer in the documentation
+ *    and/or other materials provided with the distribution.
+ *  * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
+ *    be used to endorse or promote products derived from this software without
+ *    specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** \file     TDecConformance.h
+    \brief    Decoder conformance functions (header)
+*/
+
+#ifndef __TDECCONFORMANCE__
+#define __TDECCONFORMANCE__
+
+// This can be enabled externally. Note that this is a PARTIAL CONFORMANCE CHECK - not a full check. More checks may be added later
+#ifndef DECODER_PARTIAL_CONFORMANCE_CHECK
+#define DECODER_PARTIAL_CONFORMANCE_CHECK                 0 ///< 0 (default) = do not check conformance. 1 = warn if conformance checks fail. 2 = error and quit if conformance checks fail. Note this is only a partial conformance check - not a full conformance check.
+#endif
+
+
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "TLibCommon/CommonDef.h"
+#include <stdio.h>
+#include <iostream>
+#if DECODER_PARTIAL_CONFORMANCE_CHECK == 2
+#include <stdlib.h>
+#endif
+
+
+// Forward declarations
+class TComSlice;
+class TComSPS;
+class TComPPS;
+class InputNALUnit;
+class TComPTL;
+class TComPic;
+
+typedef enum TRISTATE
+{
+  DISABLED=0,
+  OPTIONAL=1,
+  ENABLED=2
+} TRISTATE;
+
+
+typedef enum HBRFACTOREQN
+{
+  HBR_1 = 0,
+  HBR_1_OR_2 = 1,
+  HBR_12_OR_24 = 2
+} HBRFACTOREQN;
+
+
+struct LevelTierFeatures
+{
+  Level::Name level;
+  UInt        maxLumaPs;
+  UInt        maxCpb[Level::NUMBER_OF_TIERS];    // in units of CpbVclFactor or CpbNalFactor bits
+  UInt        maxSliceSegmentsPerPicture;
+  UInt        maxTileRows;
+  UInt        maxTileCols;
+  UInt64      maxLumaSr;
+  UInt        maxBr[Level::NUMBER_OF_TIERS];     // in units of BrVclFactor or BrNalFactor bits/s
+  UInt        minCrBase[Level::NUMBER_OF_TIERS];
+  UInt        getMaxPicWidthInLumaSamples()  const;
+  UInt        getMaxPicHeightInLumaSamples() const;
+};
+
+
+struct ProfileFeatures
+{
+  Profile::Name            profile;
+  const TChar            *pNameString;
+  UInt                     maxBitDepth;
+  ChromaFormat             maxChromaFormat;
+  Bool                     generalIntraConstraintFlag;
+  Bool                     generalOnePictureOnlyConstraintFlag;
+  TRISTATE                 generalLowerBitRateConstraint;
+  TRISTATE                 generalRExtToolsEnabled;
+  TRISTATE                 extendedPrecisionProcessingFlag;
+  TRISTATE                 chromaQpOffsetListEnabledFlag;
+  TRISTATE                 cabacBypassAlignmentEnabledFlag;
+  HBRFACTOREQN             hbrFactorEqn;
+  Bool                     bWavefrontsAndTilesCanBeUsedSimultaneously;
+
+  UInt                     minTileColumnWidthInLumaSamples;
+  UInt                     minTileRowHeightInLumaSamples;
+  Bool                     bCanUseLevel8p5;
+  UInt                     cpbVclFactor;
+  UInt                     cpbNalFactor;                // currently not used for checking
+  UInt                     formatCapabilityFactorx1000; // currently not used for checking
+  UInt                     minCrScaleFactorx10;         // currently not used for checking
+  const LevelTierFeatures *pLevelTiersListInfo;
+
+  Bool chromaFormatValid(ChromaFormat chFmt) const { return (profile == Profile::MAINREXT || profile == Profile::HIGHTHROUGHPUTREXT) ? chFmt<=maxChromaFormat : (chFmt == maxChromaFormat ); }
+  Bool onlyIRAPPictures()                    const { return generalIntraConstraintFlag; }
+  UInt getHbrFactor(Bool bLowerBitRateConstraintFlag) const    // currently not used for checking
+  {
+    return hbrFactorEqn==HBR_1_OR_2   ? (2-(bLowerBitRateConstraintFlag?1:0)) :
+          (hbrFactorEqn==HBR_12_OR_24 ? 12*(2-(bLowerBitRateConstraintFlag?1:0)) :
+                                        1);
+  }
+};
+
+
+class ProfileLevelTierFeatures
+{
+  private:
+    const ProfileFeatures   *m_pProfile;
+    const LevelTierFeatures *m_pLevelTier;
+    UInt                     m_hbrFactor;               // currently not used for checking
+    Level::Tier              m_tier;
+    UInt                     m_maxRawCtuBits;
+  public:
+    ProfileLevelTierFeatures() : m_pProfile(0), m_pLevelTier(0), m_hbrFactor(0), m_tier(Level::MAIN), m_maxRawCtuBits(0) { }
+
+    Void activate(const TComSPS &sps);
+
+    const ProfileFeatures     *getProfileFeatures()   const { return m_pProfile; }
+    const LevelTierFeatures   *getLevelTierFeatures() const { return m_pLevelTier; }
+    Level::Tier                getTier() const { return m_tier; }
+    UInt64 getCpbSizeInBits()            const { return (m_pLevelTier!=0 && m_pProfile!=0) ? UInt64(m_pProfile->cpbVclFactor) * m_pLevelTier->maxCpb[m_tier?1:0] : UInt64(0); }
+    Double getMinCr()                    const { return (m_pLevelTier!=0 && m_pProfile!=0) ? (m_pProfile->minCrScaleFactorx10 * m_pLevelTier->minCrBase[m_tier?1:0])/10.0 : 0.0 ; }   // currently not used for checking
+    UInt getMaxRawCtuBits()              const { return m_maxRawCtuBits; }
+};
+
+
+class TDecConformanceCheck
+{
+private:
+#if MCTS_ENC_CHECK
+  Bool m_tmctsCheckEnabled;
+#endif
+#if DECODER_PARTIAL_CONFORMANCE_CHECK
+  UInt  m_numberOfSlicesInPicture;
+  UInt64 m_bytesInPicture;
+#endif
+  ProfileLevelTierFeatures m_activatedFeatures;
+
+public:
+
+  // Static member functions
+
+  static inline Bool doChecking()
+  {
+    return DECODER_PARTIAL_CONFORMANCE_CHECK != 0;
+  }
+
+  static UInt getMinLog2CtbSize(const TComPTL &ptl, UInt layerPlus1=0);
+  static UInt getMaxLog2CtbSize(const TComPTL &ptl, UInt layerPlus1=0);
+
+
+#if DECODER_PARTIAL_CONFORMANCE_CHECK == 0
+  static inline std::ostream &getStream()  { return std::cout; }
+
+  static inline Void finishWarningReport() { }
+
+  template <class T>
+  static Void checkRange(const T& , const TChar *, const T& , const T& ) { }
+
+#else
+
+
+  static inline std::ostream &getStream()
+  {
+#if DECODER_PARTIAL_CONFORMANCE_CHECK == 1
+    std::cout << "WARNING: Conformance failure - ";
+    return std::cout;
+#else
+    std::cerr << "ERROR: Conformance failure - ";
+    return std::cerr;
+#endif
+  }
+
+  static inline Void finishWarningReport()
+  {
+#if DECODER_PARTIAL_CONFORMANCE_CHECK == 2
+    exit(1);
+#endif
+  }
+
+  template <class T>
+  static Void checkRange(const T& val, const TChar *name, const T& minValInclusive, const T& maxValInclusive)
+  {
+    if (val<minValInclusive || val>maxValInclusive)
+    {
+      getStream() << name << " must be in the range of " << minValInclusive << " to " << maxValInclusive << " (inclusive) - decoded value of " << val << "\n";
+      finishWarningReport();
+    }
+  }
+
+#endif
+
+
+  // Member functions
+
+  TDecConformanceCheck();
+
+#if DECODER_PARTIAL_CONFORMANCE_CHECK == 0
+  Void
+  checkSliceActivation(const TComSlice &/*slice*/,
+                       const InputNALUnit &/*nalu*/,
+                       const TComPic &/*pic*/,
+                       const Bool /*bFirstSliceInStream*/,
+                       const Bool /*bFirstSliceInSequence*/,
+                       const Bool /*bFirstSliceInPicture*/) { }
+
+  Void
+  checkCtuDecoding(const UInt numUsedBits) { }
+#else
+  Void
+  checkSliceActivation(const TComSlice &slice,
+                       const InputNALUnit &nalu,
+                       const TComPic &pic,
+                       const Bool bFirstSliceInStream,
+                       const Bool bFirstSliceInSequence,
+                       const Bool bFirstSliceInPicture);
+
+  Void
+  checkCtuDecoding(const UInt numUsedBits);
+#endif
+
+#if MCTS_ENC_CHECK
+  Void enableTMctsCheck(Bool enabled) { m_tmctsCheckEnabled = enabled; };
+  Bool getTMctsCheck() const { return m_tmctsCheckEnabled;  }
+  Void flagTMctsError(const char *error)
+  {
+    fprintf(stderr, "TMCTS check error: %s\n", error);
+  }
+#endif
+};
+
+
+#endif
Index: /trunk/source/Lib/TLibDecoder/TDecCu.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecCu.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecCu.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -52,5 +52,5 @@
   m_ppcYuvReco = NULL;
   m_ppcCU      = NULL;
-#if NH_3D_DBBP
+#if NH_3D
   m_ppcYuvRecoDBBP = NULL;
 #endif
@@ -61,9 +61,16 @@
 }
 
+#if MCTS_ENC_CHECK
+Void TDecCu::init( TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction, TDecConformanceCheck* pConformanceCheck)
+#else
 Void TDecCu::init( TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction)
+#endif
 {
   m_pcEntropyDecoder  = pcEntropyDecoder;
   m_pcTrQuant         = pcTrQuant;
   m_pcPrediction      = pcPrediction;
+#if MCTS_ENC_CHECK
+  m_pConformanceCheck = pConformanceCheck;
+#endif
 }
 
@@ -81,5 +88,5 @@
   m_ppcYuvReco = new TComYuv*[m_uiMaxDepth-1];
   m_ppcCU      = new TComDataCU*[m_uiMaxDepth-1];
-#if NH_3D_DBBP
+#if NH_3D
   m_ppcYuvRecoDBBP = new TComYuv*[m_uiMaxDepth-1];
 #endif
@@ -102,5 +109,5 @@
     m_ppcYuvReco[ui] = new TComYuv;    m_ppcYuvReco[ui]->create( uiWidth, uiHeight, chromaFormatIDC );
     m_ppcCU     [ui] = new TComDataCU; m_ppcCU     [ui]->create( chromaFormatIDC, uiNumPartitions, uiWidth, uiHeight, true, uiMaxWidth >> (m_uiMaxDepth - 1) );
-#if NH_3D_DBBP
+#if NH_3D
     m_ppcYuvRecoDBBP[ui] = new TComYuv;    m_ppcYuvRecoDBBP[ui]->create( uiWidth, uiHeight, chromaFormatIDC );
 #endif
@@ -126,5 +133,5 @@
     m_ppcYuvReco[ui]->destroy(); delete m_ppcYuvReco[ui]; m_ppcYuvReco[ui] = NULL;
     m_ppcCU     [ui]->destroy(); delete m_ppcCU     [ui]; m_ppcCU     [ui] = NULL;
-#if NH_3D_DBBP
+#if NH_3D
     m_ppcYuvRecoDBBP[ui]->destroy(); delete m_ppcYuvRecoDBBP[ui]; m_ppcYuvRecoDBBP[ui] = NULL;
 #endif
@@ -134,5 +141,5 @@
   delete [] m_ppcYuvReco; m_ppcYuvReco = NULL;
   delete [] m_ppcCU     ; m_ppcCU      = NULL;
-#if NH_3D_DBBP
+#if NH_3D
   delete [] m_ppcYuvRecoDBBP; m_ppcYuvRecoDBBP = NULL;
 #endif
@@ -170,5 +177,5 @@
 Void TDecCu::decompressCtu( TComDataCU* pCtu )
 {
-#if !NH_3D_IV_MERGE
+#if !NH_3D
   xDecompressCU( pCtu, 0,  0 );
 #endif
@@ -290,43 +297,13 @@
     pcCU->setQPSubParts( pcCU->getRefQP(uiAbsPartIdx), uiAbsPartIdx, uiDepth ); // set QP to default QP
   }
-#if NH_3D_NBDV 
+#if NH_3D
   DisInfo DvInfo; 
   DvInfo.m_acNBDV.setZero();
   DvInfo.m_aVIdxCan = 0;
-#if NH_3D_NBDV_REF  
   DvInfo.m_acDoNBDV.setZero();
-#endif
- 
-if(!pcCU->getSlice()->isIntra())
-  {
-#if NH_3D_ARP && NH_3D_IV_MERGE && NH_3D_VSP
+
+  if(!pcCU->getSlice()->isIntra())
+  {
     if( pcCU->getSlice()->getIvResPredFlag() || pcCU->getSlice()->getIvMvPredFlag() || pcCU->getSlice()->getViewSynthesisPredFlag() )
-#else 
-#if NH_3D_IV_MERGE && NH_3D_VSP
-    if( pcCU->getSlice()->getIvMvPredFlag() || pcCU->getSlice()->getViewSynthesisPredFlag() )
-#else
-#if NH_3D_ARP && NH_3D_VSP
-    if( pcCU->getSlice()->getIvResPredFlag() || pcCU->getSlice()->getViewSynthesisPredFlag() )
-#else
-#if NH_3D_VSP
-    if( pcCU->getSlice()->getViewSynthesisPredFlag() )
-#else
-#if H_3D_ARP
-    if( pcCU->getSlice()->getIvResPredFlag( ) )
-#else
-#if H_3D_IV_MERGE
-    if( pcCU->getSlice()->getVPS()->getIvMvPredFlag(pcCU->getSlice()->getLayerId()) )
-#else
-#if NH_3D_DBBP
-    if( pcCU->getSlice()->getDepthBasedBlkPartFlag() )
-#else
-    if (0)
-#endif
-#endif
-#endif
-#endif
-#endif
-#endif
-#endif
     {
       m_ppcCU[uiDepth]->copyInterPredInfoFrom(pcCU, uiAbsPartIdx, REF_PIC_LIST_0, true);
@@ -338,5 +315,4 @@
       m_ppcCU[uiDepth]->setHeight(0, pcCU->getSlice()->getSPS()->getMaxCUHeight() / (1 << uiDepth));
       m_ppcCU[uiDepth]->setPartSizeSubParts(SIZE_2Nx2N, 0, uiDepth);     
-#if NH_3D_IV_MERGE
       if( pcCU->getSlice()->getIsDepth())
       {
@@ -345,18 +321,13 @@
       else
       {
-#endif
-#if NH_3D_NBDV_REF
-      if( pcCU->getSlice()->getDepthBasedBlkPartFlag() )  //Notes from QC: please check the condition for DoNBDV. Remove this comment once it is done.
-      {
-        m_ppcCU[uiDepth]->getDisMvpCandNBDV(&DvInfo, true);
-      }
-      else
-#endif
-      {
-        m_ppcCU[uiDepth]->getDisMvpCandNBDV(&DvInfo);
-      }
-#if NH_3D_IV_MERGE
-      }
-#endif
+        if( pcCU->getSlice()->getDepthBasedBlkPartFlag() )  //Notes from QC: please check the condition for DoNBDV. Remove this comment once it is done.
+        {
+          m_ppcCU[uiDepth]->getDisMvpCandNBDV(&DvInfo, true);
+        }
+        else
+        {
+          m_ppcCU[uiDepth]->getDisMvpCandNBDV(&DvInfo);
+        }
+      }
 #if ENC_DEC_TRACE && NH_MV_ENC_DEC_TRAC   
       if ( g_decTraceDispDer )
@@ -373,5 +344,5 @@
       m_ppcCU[uiDepth]->setWidth(0, cWidTemp);
       m_ppcCU[uiDepth]->setHeight(0, cHeightTemp);
-     }
+    }
   }
 #endif
@@ -382,5 +353,5 @@
   }
 
-  if (pps.getTransquantBypassEnableFlag())
+  if (pps.getTransquantBypassEnabledFlag())
   {
     m_pcEntropyDecoder->decodeCUTransquantBypassFlag( pcCU, uiAbsPartIdx, uiDepth );
@@ -403,10 +374,6 @@
     m_ppcCU[uiDepth]->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_0 );
     m_ppcCU[uiDepth]->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_1 );
-#if NH_3D_IV_MERGE
+#if NH_3D
     m_ppcCU[uiDepth]->copyDVInfoFrom(pcCU, uiAbsPartIdx);
-    TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS_MEM << 1]; // double length for mv of both lists
-    UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS_MEM];
-#else
-#if NH_3D_MLC
     TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS_MEM << 1]; // double length for mv of both lists
     UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS_MEM];
@@ -415,5 +382,4 @@
     UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
 #endif
-#endif
     Int numValidMergeCand = 0;
     for( UInt ui = 0; ui < m_ppcCU[uiDepth]->getSlice()->getMaxNumMergeCand(); ++ui )
@@ -423,17 +389,11 @@
     m_pcEntropyDecoder->decodeMergeIndex( pcCU, 0, uiAbsPartIdx, uiDepth );
     UInt uiMergeIndex = pcCU->getMergeIndex(uiAbsPartIdx);
-#if NH_3D_ARP
+#if NH_3D
     m_pcEntropyDecoder->decodeARPW( pcCU , uiAbsPartIdx , uiDepth );
-#endif
-#if NH_3D_IC
     m_pcEntropyDecoder->decodeICFlag( pcCU, uiAbsPartIdx, uiDepth );
-#endif
-
-
-#if NH_3D_VSP
+
     Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
     memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
-#endif
-#if NH_3D_SPIVMP
+
     Bool bSPIVMPFlag[MRG_MAX_NUM_CANDS_MEM];
     memset(bSPIVMPFlag, false, sizeof(Bool)*MRG_MAX_NUM_CANDS_MEM);
@@ -442,27 +402,21 @@
     pcMvFieldSP = new TComMvField[pcCU->getPic()->getPicSym()->getNumPartitionsInCtu()*2]; 
     puhInterDirSP = new UChar[pcCU->getPic()->getPicSym()->getNumPartitionsInCtu()]; 
-#endif
-
-#if NH_3D_MLC
     m_ppcCU[uiDepth]->initAvailableFlags();
 #endif
+#if MCTS_ENC_CHECK
+    UInt numSpatialMergeCandidates = 0;
+    m_ppcCU[uiDepth]->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, numSpatialMergeCandidates, uiMergeIndex );
+#if MCTS_ENC_CHECK
+    if ( m_pConformanceCheck->getTMctsCheck() && m_ppcCU[uiDepth]->isLastColumnCTUInTile() && (uiMergeIndex >= numSpatialMergeCandidates) )
+    {
+      m_pConformanceCheck->flagTMctsError("Merge Index using non-spatial merge candidate (Skip)");
+    }
+#endif
+#else
     m_ppcCU[uiDepth]->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
-#if NH_3D_MLC
-    m_ppcCU[uiDepth]->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours 
-#if NH_3D_SPIVMP
-      , pcMvFieldSP, puhInterDirSP
-#endif
-      , numValidMergeCand, uiMergeIndex );
-
-    m_ppcCU[uiDepth]->buildMCL( cMvFieldNeighbours, uhInterDirNeighbours
-#if NH_3D_VSP
-      , vspFlag
-#endif
-#if NH_3D_SPIVMP
-      , bSPIVMPFlag
-#endif
-      , numValidMergeCand );
-#endif
-#if NH_3D_VSP
+#endif
+#if NH_3D
+    m_ppcCU[uiDepth]->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, pcMvFieldSP, puhInterDirSP, numValidMergeCand, uiMergeIndex );
+    m_ppcCU[uiDepth]->buildMCL( cMvFieldNeighbours, uhInterDirNeighbours, vspFlag, bSPIVMPFlag, numValidMergeCand );
     pcCU->setVSPFlagSubParts( vspFlag[uiMergeIndex], uiAbsPartIdx, 0, uiDepth );
 #endif
@@ -479,5 +433,5 @@
         pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvd( cTmpMv, SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
         pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvField( cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ], SIZE_2Nx2N, uiAbsPartIdx, uiDepth );
-#if NH_3D_VSP
+#if NH_3D
         if( pcCU->getVSPFlag( uiAbsPartIdx ) != 0 )
         {
@@ -512,5 +466,5 @@
       }
     }
-#if NH_3D_SPIVMP
+#if NH_3D
     pcCU->setSPIVMPFlagSubParts(bSPIVMPFlag[uiMergeIndex], uiAbsPartIdx, 0, uiDepth ); 
     if (bSPIVMPFlag[uiMergeIndex])
@@ -570,5 +524,5 @@
 
     xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, isLastCtuOfSliceSegment );
-#if NH_3D_IV_MERGE
+#if NH_3D
     xDecompressCU(pcCU, uiAbsPartIdx, uiDepth );
 #endif
@@ -576,5 +530,5 @@
     return;
   }
-#if NH_3D_DIS
+#if NH_3D
   m_pcEntropyDecoder->decodeDIS( pcCU, uiAbsPartIdx, uiDepth );
   if(!pcCU->getDISFlag(uiAbsPartIdx))
@@ -582,38 +536,38 @@
 #endif
 
-  m_pcEntropyDecoder->decodePredMode( pcCU, uiAbsPartIdx, uiDepth );
-  m_pcEntropyDecoder->decodePartSize( pcCU, uiAbsPartIdx, uiDepth );
-
-  if (pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
-  {
-    m_pcEntropyDecoder->decodeIPCMInfo( pcCU, uiAbsPartIdx, uiDepth );
-
-    if(pcCU->getIPCMFlag(uiAbsPartIdx))
-    {
-#if NH_3D_SDC_INTRA
-      m_pcEntropyDecoder->decodeSDCFlag( pcCU, uiAbsPartIdx, uiDepth );
-#endif
-      xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, isLastCtuOfSliceSegment );
-#if NH_3D_IV_MERGE
-      xDecompressCU(pcCU, uiAbsPartIdx, uiDepth );
-#endif
-      return;
-    }
-  }
-
-  // prediction mode ( Intra : direction mode, Inter : Mv, reference idx )
-  m_pcEntropyDecoder->decodePredInfo( pcCU, uiAbsPartIdx, uiDepth, m_ppcCU[uiDepth]);
-
-  // Coefficient decoding
-  Bool bCodeDQP = getdQPFlag();
-  Bool isChromaQpAdjCoded = getIsChromaQpAdjCoded();
-  m_pcEntropyDecoder->decodeCoeff( pcCU, uiAbsPartIdx, uiDepth, bCodeDQP, isChromaQpAdjCoded );
-  setIsChromaQpAdjCoded( isChromaQpAdjCoded );
-  setdQPFlag( bCodeDQP );
-#if NH_3D_DIS
+    m_pcEntropyDecoder->decodePredMode( pcCU, uiAbsPartIdx, uiDepth );
+    m_pcEntropyDecoder->decodePartSize( pcCU, uiAbsPartIdx, uiDepth );
+
+    if (pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
+    {
+      m_pcEntropyDecoder->decodeIPCMInfo( pcCU, uiAbsPartIdx, uiDepth );
+
+      if(pcCU->getIPCMFlag(uiAbsPartIdx))
+      {
+#if NH_3D
+        m_pcEntropyDecoder->decodeSDCFlag( pcCU, uiAbsPartIdx, uiDepth );
+#endif
+        xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, isLastCtuOfSliceSegment );
+#if NH_3D
+        xDecompressCU(pcCU, uiAbsPartIdx, uiDepth );
+#endif
+        return;
+      }
+    }
+
+    // prediction mode ( Intra : direction mode, Inter : Mv, reference idx )
+    m_pcEntropyDecoder->decodePredInfo( pcCU, uiAbsPartIdx, uiDepth, m_ppcCU[uiDepth]);
+
+    // Coefficient decoding
+    Bool bCodeDQP = getdQPFlag();
+    Bool isChromaQpAdjCoded = getIsChromaQpAdjCoded();
+    m_pcEntropyDecoder->decodeCoeff( pcCU, uiAbsPartIdx, uiDepth, bCodeDQP, isChromaQpAdjCoded );
+    setIsChromaQpAdjCoded( isChromaQpAdjCoded );
+    setdQPFlag( bCodeDQP );
+#if NH_3D
   }
 #endif
   xFinishDecodeCU( pcCU, uiAbsPartIdx, uiDepth, isLastCtuOfSliceSegment );
-#if NH_3D_IV_MERGE
+#if NH_3D
   xDecompressCU(pcCU, uiAbsPartIdx, uiDepth );
 #endif
@@ -638,5 +592,5 @@
 {
   TComPic* pcPic = pCtu->getPic();
-#if !NH_3D_IV_MERGE
+#if !NH_3D
   TComSlice * pcSlice = pCtu->getSlice();
   const TComSPS &sps=*(pcSlice->getSPS());
@@ -681,5 +635,5 @@
   {
     case MODE_INTER:
-#if NH_3D_DBBP
+#if NH_3D
     if( m_ppcCU[uiDepth]->getDBBPFlag(0) )
     {
@@ -688,6 +642,4 @@
     else
     {
-#endif
-#if NH_3D_SDC_INTER
       if( m_ppcCU[uiDepth]->getSDCFlag( 0 ) )
       {
@@ -698,8 +650,6 @@
 #endif
       xReconInter( m_ppcCU[uiDepth], uiDepth );
-#if NH_3D_SDC_INTER
-      }
-#endif
-#if NH_3D_DBBP
+#if NH_3D
+      }
     }
 #endif
@@ -707,21 +657,12 @@
     case MODE_INTRA:
 #if NH_3D
-#if NH_3D_DIS
     if( m_ppcCU[uiDepth]->getDISFlag(0) )
     {
       xReconDIS( m_ppcCU[uiDepth], 0, uiDepth );
     }
-#else
-    if(false )
-    {
-     // xReconDIS( m_ppcCU[uiDepth], 0, uiDepth );
-    }
-#endif
-#if NH_3D_SDC_INTRA
     else if( m_ppcCU[uiDepth]->getSDCFlag(0) )
     {
       xReconIntraSDC( m_ppcCU[uiDepth], 0, uiDepth );
     }
-#endif
     else
 #endif
@@ -756,4 +697,10 @@
 
   // inter prediction
+#if MCTS_ENC_CHECK
+  if (m_pConformanceCheck->getTMctsCheck()  && !m_pcPrediction->checkTMctsMvp(pcCU))
+  {
+    m_pConformanceCheck->flagTMctsError("motion vector across tile boundaries");
+  }
+#endif
   m_pcPrediction->motionCompensation( pcCU, m_ppcYuvReco[uiDepth] );
 
@@ -794,5 +741,5 @@
 }
 
-#if NH_3D_DIS
+#if NH_3D
 Void TDecCu::xReconDIS( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
@@ -869,6 +816,5 @@
   }
 }
-#endif
-#if NH_3D_SDC_INTER
+
 Void TDecCu::xReconInterSDC( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
@@ -913,7 +859,5 @@
   }
 }
-#endif
-
-#if NH_3D_DBBP
+
 Void TDecCu::xReconInterDBBP( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
@@ -926,9 +870,5 @@
   // get collocated depth block
   UInt uiDepthStride = 0;
-#if H_3D_FCO
-  Pel* pDepthPels = pcCU->getVirtualDepthBlock(pcCU->getZorderIdxInCU(), pcCU->getWidth(0), pcCU->getHeight(0), uiDepthStride);
-#else
   Pel* pDepthPels = pcCU->getVirtualDepthBlock(0, pcCU->getWidth(0), pcCU->getHeight(0), uiDepthStride);
-#endif
   AOF( pDepthPels != NULL );
   AOF( uiDepthStride != 0 );
@@ -956,11 +896,9 @@
       pcCU->getMvField(pcCU, uiPartAddr, eRefList, pDBBPTmpData->acMvField[uiSegment][eRefList]);
     }
-    
-#if NH_3D
+
     AOF( pcCU->getARPW(uiPartAddr) == 0 );
     AOF( pcCU->getICFlag(uiPartAddr) == false );
     AOF( pcCU->getSPIVMPFlag(uiPartAddr) == false );
     AOF( pcCU->getVSPFlag(uiPartAddr) == 0 );
-#endif
   }
   
@@ -1081,5 +1019,5 @@
 
   //===== get prediction signal =====
-#if NH_3D_DMM
+#if NH_3D
   if( bIsLuma && isDmmMode( uiChFinalMode ) )
   {
@@ -1090,5 +1028,5 @@
 #endif
   m_pcPrediction->predIntraAng( compID,   uiChFinalMode, 0 /* Decoder does not have an original image */, 0, piPred, uiStride, rTu, bUseFilteredPredictions );
-#if NH_3D_DMM
+#if NH_3D
   }
 #endif
@@ -1255,5 +1193,5 @@
 }
 
-#if NH_3D_SDC_INTRA
+#if NH_3D
 Void TDecCu::xReconIntraSDC( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
@@ -1284,5 +1222,4 @@
   UInt uiMaskStride = 0;
 
-#if NH_3D_DMM
   if( isDmmMode( uiLumaPredMode ) )
   {
@@ -1330,5 +1267,5 @@
   else // regular HEVC intra modes
   {
-#endif
+
     uiNumSegments = 1;
 
@@ -1389,13 +1326,10 @@
 
     m_pcPrediction->predConstantSDC( piPred, uiStride, uiWidth, apDCPredValues[0] ); apDCPredValues[1] = 0;
-#if NH_3D_DMM
-  }
-#endif
-  
+  }
+
   // reconstruct residual based on mask + DC residuals
   Pel apDCResiValues[2];
   for( UInt uiSegment = 0; uiSegment < uiNumSegments; uiSegment++ )
   {
-#if NH_3D_DLT
     Pel   pPredIdx    = pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), apDCPredValues[uiSegment] );
     Pel   pResiIdx    = pcCU->getSDCSegmentDCOffset(uiSegment, uiAbsPartIdx);
@@ -1403,7 +1337,4 @@
 
     apDCResiValues[uiSegment]  = pRecoValue - apDCPredValues[uiSegment];
-#else
-    apDCResiValues[uiSegment]  = pcCU->getSDCSegmentDCOffset(uiSegment, uiAbsPartIdx);
-#endif
   }
   
@@ -1450,7 +1381,5 @@
     pRecCr += uiStrideC;
   }
-#if NH_3D_DMM
   if( pbMask ) { delete[] pbMask; }
-#endif
 }
 #endif
Index: /trunk/source/Lib/TLibDecoder/TDecCu.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecCu.h	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecCu.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -45,4 +45,5 @@
 #include "TLibCommon/TComTrQuant.h"
 #include "TDecEntropy.h"
+#include "TDecConformance.h"
 
 //! \ingroup TLibDecoder
@@ -62,5 +63,5 @@
   TComDataCU**        m_ppcCU;            ///< CU data array
 
-#if NH_3D_DBBP
+#if NH_3D
   TComYuv**           m_ppcYuvRecoDBBP;
 #endif
@@ -70,4 +71,7 @@
   TComPrediction*     m_pcPrediction;
   TDecEntropy*        m_pcEntropyDecoder;
+#if MCTS_ENC_CHECK
+  TDecConformanceCheck* m_pConformanceCheck;
+#endif
 
   Bool                m_bDecodeDQP;
@@ -79,5 +83,9 @@
 
   /// initialize access channels
+#if MCTS_ENC_CHECK
+  Void  init                    (TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction, TDecConformanceCheck* pConformanceCheck);
+#else
   Void  init                    ( TDecEntropy* pcEntropyDecoder, TComTrQuant* pcTrQuant, TComPrediction* pcPrediction );
+#endif
 
   /// create internal buffers
@@ -102,5 +110,5 @@
   Void xReconInter              ( TComDataCU* pcCU, UInt uiDepth );
 
-#if NH_3D_DBBP
+#if NH_3D
   Void xReconInterDBBP          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
 #endif
@@ -124,11 +132,7 @@
   Void xFillPCMBuffer           (TComDataCU* pCU, UInt depth);
 
-#if NH_3D_DIS
+#if NH_3D
   Void xReconDIS               ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-#endif
-#if NH_3D_SDC_INTRA
   Void xReconIntraSDC           ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-#endif
-#if NH_3D_SDC_INTER
   Void xReconInterSDC           ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
 #endif
Index: /trunk/source/Lib/TLibDecoder/TDecEntropy.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecEntropy.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -60,5 +60,5 @@
   m_pcEntropyDecoderIf->parseSkipFlag( pcCU, uiAbsPartIdx, uiDepth );
 }
-#if NH_3D_DIS
+#if NH_3D
 Void TDecEntropy::decodeDIS( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
@@ -104,5 +104,5 @@
 }
 
-#if NH_3D_ARP
+#if NH_3D
 Void TDecEntropy::decodeARPW( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
@@ -121,16 +121,10 @@
   }
 }
-#endif
-
-#if NH_3D_IC
+
 Void TDecEntropy::decodeICFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
   pcCU->setICFlagSubParts( false , uiAbsPartIdx, 0, uiDepth );
 
-#if NH_3D_ARP
   if ( pcCU->isIntra( uiAbsPartIdx ) || ( pcCU->getSlice()->getViewIndex() == 0 ) || pcCU->getSlice()->getIsDepth() || pcCU->getARPW( uiAbsPartIdx ) > 0 )
-#else
-  if ( pcCU->isIntra( uiAbsPartIdx ) || ( pcCU->getSlice()->getViewIndex() == 0 ) || pcCU->getSlice()->getIsDepth() )
-#endif
   {
     return;
@@ -165,5 +159,5 @@
   {
     decodeIntraDirModeLuma  ( pcCU, uiAbsPartIdx, uiDepth );
-#if NH_3D_SDC_INTRA
+#if NH_3D
     decodeSDCFlag   ( pcCU, uiAbsPartIdx, uiDepth );
 #endif
@@ -239,6 +233,5 @@
   UInt uiPUOffset = ( g_auiPUOffset[UInt( ePartSize )] << ( ( pcCU->getSlice()->getSPS()->getMaxTotalCUDepth() - uiDepth ) << 1 ) ) >> 4;
 
-#if NH_3D_MLC
-//#if H_3D_IV_MERGE
+#if NH_3D
   TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS_MEM << 1]; // double length for mv of both lists
   UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS_MEM];
@@ -247,10 +240,8 @@
   UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS];
 #endif
-#if NH_3D_SPIVMP
+#if NH_3D
   Bool bSPIVMPFlag[MRG_MAX_NUM_CANDS_MEM];     
   TComMvField*  pcMvFieldSP = new TComMvField[pcCU->getPic()->getPicSym()->getNumPartitionsInCtu()*2]; 
   UChar* puhInterDirSP = new UChar[pcCU->getPic()->getPicSym()->getNumPartitionsInCtu()]; 
-#endif
-#if NH_3D_IV_MERGE
   pcSubCU->copyDVInfoFrom( pcCU, uiAbsPartIdx);
 #endif
@@ -262,4 +253,7 @@
   Bool hasMergedCandList = false;
 
+#if MCTS_ENC_CHECK
+  UInt numSpatialMergeCandidates = 0;
+#endif
   pcSubCU->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_0 );
   pcSubCU->copyInterPredInfoFrom( pcCU, uiAbsPartIdx, REF_PIC_LIST_1 );
@@ -296,16 +290,8 @@
 
   ////// Parse CUs extension syntax
-#if NH_3D_DBBP
   decodeDBBPFlag( pcCU, uiAbsPartIdx, uiDepth ); 
-#endif
-#if NH_3D_SDC_INTER
   decodeSDCFlag ( pcCU, uiAbsPartIdx, uiDepth );
-#endif
-#if NH_3D_ARP
-  decodeARPW  ( pcCU, uiAbsPartIdx, uiDepth );
-#endif
-#if NH_3D_IC
-  decodeICFlag( pcCU, uiAbsPartIdx, uiDepth );
-#endif
+  decodeARPW    ( pcCU, uiAbsPartIdx, uiDepth );
+  decodeICFlag  ( pcCU, uiAbsPartIdx, uiDepth );
 
   ////// Decode motion vectors
@@ -323,43 +309,23 @@
 #endif
 
-#if NH_3D_DBBP
       if ( pcCU->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() && ePartSize != SIZE_2Nx2N && pcSubCU->getWidth( 0 ) <= 8 && pcCU->getDBBPFlag(uiAbsPartIdx) == false )
-#else
-      if ( pcCU->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() && ePartSize != SIZE_2Nx2N && pcSubCU->getWidth( 0 ) <= 8 ) 
-#endif
       {
         if ( !hasMergedCandList )
         {
           pcSubCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth ); // temporarily set.
-
-#if NH_3D_MLC
-#if NH_3D_VSP
           Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
           memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
-#endif
-#if NH_3D_SPIVMP
           memset(bSPIVMPFlag, false, sizeof(Bool)*MRG_MAX_NUM_CANDS_MEM);
-#endif
           pcSubCU->initAvailableFlags();
-#endif
+#if MCTS_ENC_CHECK
+          numSpatialMergeCandidates = 0;
+          pcSubCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, numSpatialMergeCandidates );
+#else
           pcSubCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
-#if NH_3D_MLC
-          pcSubCU->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours
-#if NH_3D_SPIVMP
-            , pcMvFieldSP, puhInterDirSP
-#endif
-            , numValidMergeCand );
-          pcSubCU->buildMCL( cMvFieldNeighbours, uhInterDirNeighbours
-#if NH_3D_VSP
-            , vspFlag
-#endif
-#if NH_3D_SPIVMP
-            , bSPIVMPFlag
-#endif
-            , numValidMergeCand );
-#if NH_3D_VSP
+#endif
+
+          pcSubCU->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, pcMvFieldSP, puhInterDirSP, numValidMergeCand );
+          pcSubCU->buildMCL( cMvFieldNeighbours, uhInterDirNeighbours, vspFlag, bSPIVMPFlag, numValidMergeCand );
           pcCU->setVSPFlagSubParts( vspFlag[uiMergeIndex], uiSubPartIdx, uiPartIdx, uiDepth );
-#endif
-#endif
           pcSubCU->setPartSizeSubParts( ePartSize, 0, uiDepth ); // restore.
           hasMergedCandList = true;
@@ -368,33 +334,17 @@
       else
       {
-#if NH_3D_MLC
-#if NH_3D_VSP
         Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
         memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
-#endif
-#if NH_3D_SPIVMP
         memset(bSPIVMPFlag, false, sizeof(Bool)*MRG_MAX_NUM_CANDS_MEM);
-#endif
         pcSubCU->initAvailableFlags();
-#endif
+#if MCTS_ENC_CHECK
+        numSpatialMergeCandidates = 0;
+        pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, numSpatialMergeCandidates, uiMergeIndex );
+#else
         pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
-#if NH_3D_MLC
-        pcSubCU->xGetInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, cMvFieldNeighbours, uhInterDirNeighbours
-#if NH_3D_SPIVMP
-          , pcMvFieldSP, puhInterDirSP
-#endif
-          ,numValidMergeCand, uiMergeIndex );
-        pcSubCU->buildMCL( cMvFieldNeighbours, uhInterDirNeighbours
-#if NH_3D_VSP
-          , vspFlag
-#endif
-#if NH_3D_SPIVMP
-          , bSPIVMPFlag
-#endif
-          ,numValidMergeCand );
-#if NH_3D_VSP
+#endif
+        pcSubCU->xGetInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, cMvFieldNeighbours, uhInterDirNeighbours, pcMvFieldSP, puhInterDirSP ,numValidMergeCand, uiMergeIndex );
+        pcSubCU->buildMCL( cMvFieldNeighbours, uhInterDirNeighbours , vspFlag, bSPIVMPFlag ,numValidMergeCand );
         pcCU->setVSPFlagSubParts( vspFlag[uiMergeIndex], uiSubPartIdx, uiPartIdx, uiDepth );
-#endif
-#endif
       }
       pcCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeIndex], uiSubPartIdx, uiPartIdx, uiDepth );
@@ -409,10 +359,5 @@
           pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvd( cTmpMv, ePartSize, uiSubPartIdx, uiDepth, uiPartIdx );
           pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvField( cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ], ePartSize, uiSubPartIdx, uiDepth, uiPartIdx );
-#if NH_3D_VSP
-#if NH_3D_DBBP
           if( pcCU->getVSPFlag( uiSubPartIdx ) != 0 && !pcCU->getDBBPFlag( uiAbsPartIdx ) )
-#else
-          if( pcCU->getVSPFlag( uiSubPartIdx ) != 0 )
-#endif
           {
             if ( uhInterDirNeighbours[ uiMergeIndex ] & (1<<uiRefListIdx) )
@@ -426,8 +371,6 @@
             }
           }
-#endif
-        }
-      }
-#if NH_3D_SPIVMP
+        }
+      }
       pcCU->setSPIVMPFlagSubParts(bSPIVMPFlag[uiMergeIndex], uiSubPartIdx, uiPartIdx, uiDepth );  
       if (bSPIVMPFlag[uiMergeIndex] != 0)
@@ -451,5 +394,4 @@
         }
       }
-#endif
     }
     else
@@ -481,4 +423,8 @@
     }
   }
+
+  delete[] pcMvFieldSP;
+  delete[] puhInterDirSP;
+
 #else
   for ( UInt uiPartIdx = 0, uiSubPartIdx = uiAbsPartIdx; uiPartIdx < uiNumPU; uiPartIdx++, uiSubPartIdx += uiPUOffset )
@@ -501,8 +447,4 @@
       }
 #endif
-#if NH_3D_IC
-      decodeICFlag( pcCU, uiAbsPartIdx, uiDepth );
-#endif
-
       const UInt uiMergeIndex = pcCU->getMergeIndex(uiSubPartIdx);
       if ( pcCU->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() && ePartSize != SIZE_2Nx2N && pcSubCU->getWidth( 0 ) <= 8 )
@@ -512,32 +454,9 @@
           pcSubCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth ); // temporarily set.
 
-#if NH_3D_MLC
-#if NH_3D_VSP
-          Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
-          memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
-#endif
-#if NH_3D_SPIVMP
-          memset(bSPIVMPFlag, false, sizeof(Bool)*MRG_MAX_NUM_CANDS_MEM);
-#endif
-          pcSubCU->initAvailableFlags();
-#endif
+#if MCTS_ENC_CHECK
+          numSpatialMergeCandidates = 0;
+          pcSubCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, numSpatialMergeCandidates );
+#else
           pcSubCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
-#if NH_3D_MLC
-          pcSubCU->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours
-#if NH_3D_SPIVMP
-            , pcMvFieldSP, puhInterDirSP
-#endif
-            , numValidMergeCand );
-          pcSubCU->buildMCL( cMvFieldNeighbours, uhInterDirNeighbours
-#if NH_3D_VSP
-            , vspFlag
-#endif
-#if NH_3D_SPIVMP
-            , bSPIVMPFlag
-#endif
-            , numValidMergeCand );
-#if NH_3D_VSP
-          pcCU->setVSPFlagSubParts( vspFlag[uiMergeIndex], uiSubPartIdx, uiPartIdx, uiDepth );
-#endif
 #endif
           pcSubCU->setPartSizeSubParts( ePartSize, 0, uiDepth ); // restore.
@@ -547,36 +466,19 @@
       else
       {
-
-#if NH_3D_MLC
-#if NH_3D_VSP
-        Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
-        memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
-#endif
-#if NH_3D_SPIVMP
-        memset(bSPIVMPFlag, false, sizeof(Bool)*MRG_MAX_NUM_CANDS_MEM);
-#endif
-        pcSubCU->initAvailableFlags();
-#endif
+#if MCTS_ENC_CHECK
+        numSpatialMergeCandidates = 0;
+        pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, numSpatialMergeCandidates, uiMergeIndex );
+#else
+
         pcSubCU->getInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, uiMergeIndex );
-#if NH_3D_MLC
-        pcSubCU->xGetInterMergeCandidates( uiSubPartIdx-uiAbsPartIdx, uiPartIdx, cMvFieldNeighbours, uhInterDirNeighbours
-#if NH_3D_SPIVMP
-          , pcMvFieldSP, puhInterDirSP
-#endif
-          ,numValidMergeCand, uiMergeIndex );
-        pcSubCU->buildMCL( cMvFieldNeighbours, uhInterDirNeighbours
-#if NH_3D_VSP
-          , vspFlag
-#endif
-#if NH_3D_SPIVMP
-          , bSPIVMPFlag
-#endif
-          ,numValidMergeCand );
-#if NH_3D_VSP
-        pcCU->setVSPFlagSubParts( vspFlag[uiMergeIndex], uiSubPartIdx, uiPartIdx, uiDepth );
-#endif
-#endif
-      }
-
+#endif
+      }
+#if MCTS_ENC_CHECK
+      if (m_pConformanceCheck->getTMctsCheck() &&  pcSubCU->isLastColumnCTUInTile() && (uiMergeIndex >= numSpatialMergeCandidates) )
+      {
+        m_pConformanceCheck->flagTMctsError("Merge Index using non-spatial merge candidate (Merge)");
+      }
+
+#endif
       pcCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeIndex], uiSubPartIdx, uiPartIdx, uiDepth );
 
@@ -590,43 +492,6 @@
           pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvd( cTmpMv, ePartSize, uiSubPartIdx, uiDepth, uiPartIdx );
           pcCU->getCUMvField( RefPicList( uiRefListIdx ) )->setAllMvField( cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ], ePartSize, uiSubPartIdx, uiDepth, uiPartIdx );
-#if NH_3D_VSP
-          if( pcCU->getVSPFlag( uiSubPartIdx ) != 0 )
-          {
-            if ( uhInterDirNeighbours[ uiMergeIndex ] & (1<<uiRefListIdx) )
-            {
-              UInt dummy;
-              Int vspSize;
-              Int width, height;
-              pcCU->getPartIndexAndSize( uiPartIdx, dummy, width, height, uiSubPartIdx, pcCU->getTotalNumPart()==256 );
-              pcCU->setMvFieldPUForVSP( pcCU, uiSubPartIdx, width, height, RefPicList( uiRefListIdx ), cMvFieldNeighbours[ 2*uiMergeIndex + uiRefListIdx ].getRefIdx(), vspSize );
-              pcCU->setVSPFlag( uiSubPartIdx, vspSize );
-            }
-          }
-#endif
-        }
-      }
-#if NH_3D_SPIVMP
-      pcCU->setSPIVMPFlagSubParts(bSPIVMPFlag[uiMergeIndex], uiSubPartIdx, uiPartIdx, uiDepth );  
-      if (bSPIVMPFlag[uiMergeIndex] != 0)
-      {
-        Int iWidth, iHeight;
-        UInt uiIdx;
-        pcCU->getPartIndexAndSize( uiPartIdx, uiIdx, iWidth, iHeight, uiSubPartIdx, true );
-
-        UInt uiSPAddr;
-
-        Int iNumSPInOneLine, iNumSP, iSPWidth, iSPHeight;
-
-        pcCU->getSPPara(iWidth, iHeight, iNumSP, iNumSPInOneLine, iSPWidth, iSPHeight);
-
-        for (Int iPartitionIdx = 0; iPartitionIdx < iNumSP; iPartitionIdx++)
-        {
-          pcCU->getSPAbsPartIdx(uiSubPartIdx, iSPWidth, iSPHeight, iPartitionIdx, iNumSPInOneLine, uiSPAddr);
-          pcCU->setInterDirSP(puhInterDirSP[iPartitionIdx], uiSPAddr, iSPWidth, iSPHeight);
-          pcCU->getCUMvField( REF_PIC_LIST_0 )->setMvFieldSP(pcCU, uiSPAddr, pcMvFieldSP[2*iPartitionIdx], iSPWidth, iSPHeight);
-          pcCU->getCUMvField( REF_PIC_LIST_1 )->setMvFieldSP(pcCU, uiSPAddr, pcMvFieldSP[2*iPartitionIdx + 1], iSPWidth, iSPHeight);
-        }
-      }
-#endif
+        }
+      }
     }
     else
@@ -652,7 +517,4 @@
         }
       } 
-#if NH_3D_IC
-      decodeICFlag( pcCU, uiAbsPartIdx, uiDepth );
-#endif
     }
 
@@ -664,8 +526,4 @@
     }
   }
-#endif
-#if NH_3D_SPIVMP
-  delete[] pcMvFieldSP;
-  delete[] puhInterDirSP;
 #endif
   return;
@@ -812,4 +670,11 @@
   }
   pcSubCU->fillMvpCand(uiPartIdx, uiPartAddr, eRefList, iRefIdx, pAMVPInfo);
+#if MCTS_ENC_CHECK
+  if ((iRefIdx >= 0) && m_pConformanceCheck->getTMctsCheck() && pcSubCU->isLastColumnCTUInTile() && (iMVPIdx == pAMVPInfo->numSpatialMVPCandidates))
+  {
+    m_pConformanceCheck->flagTMctsError("Merge Index using non-spatial merge candidate (AMVP)");
+  }
+#endif
+
   pcSubCU->setMVPNumSubParts(pAMVPInfo->iN, eRefList, uiPartAddr, uiPartIdx, uiDepth);
   pcSubCU->setMVPIdxSubParts( iMVPIdx, eRefList, uiPartAddr, uiPartIdx, uiDepth );
@@ -1085,5 +950,5 @@
 Void TDecEntropy::decodeCoeff( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, Bool& bCodeDQP, Bool& isChromaQpAdjCoded )
 {
-#if NH_3D_SDC_INTRA
+#if NH_3D
   if( pcCU->getSDCFlag( uiAbsPartIdx ) && pcCU->isIntra( uiAbsPartIdx) )
   {
@@ -1092,6 +957,4 @@
     assert( pcCU->getCbf(uiAbsPartIdx, COMPONENT_Y) == 1 );
 }
-#endif
-#if NH_3D_SDC_INTER
   if( pcCU->getSDCFlag( uiAbsPartIdx ) && !pcCU->isIntra( uiAbsPartIdx) )
   {
@@ -1100,9 +963,6 @@
     assert( pcCU->getSlice()->getIsDepth() );
   }
-#endif
-#if NH_3D
   if( pcCU->getSlice()->getIsDepth() )
   {
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
     if( pcCU->getSDCFlag( uiAbsPartIdx ) )
     {
@@ -1110,6 +970,4 @@
       return;
     }
-#endif
-#if NH_3D_DMM
     if( pcCU->isIntra( uiAbsPartIdx ) )
     {
@@ -1124,5 +982,4 @@
       }
     }
-#endif
   }
 #endif
@@ -1162,5 +1019,5 @@
 }
 
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
+#if NH_3D
 Void TDecEntropy::decodeSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
@@ -1186,6 +1043,5 @@
   m_pcEntropyDecoderIf->parseSDCFlag( pcCU, uiAbsPartIdx, uiDepth );
 }
-#endif
-#if NH_3D_DBBP
+
 Void TDecEntropy::decodeDBBPFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
Index: /trunk/source/Lib/TLibDecoder/TDecEntropy.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecEntropy.h	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecEntropy.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -44,4 +44,6 @@
 #include "TLibCommon/TComSampleAdaptiveOffset.h"
 #include "TLibCommon/TComRectangle.h"
+#include "TDecConformance.h"
+
 class TDecSbac;
 class TDecCavlc;
@@ -81,5 +83,5 @@
 public:
   virtual Void parseSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
-#if NH_3D_DIS
+#if NH_3D
   virtual Void parseDIS           ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
 #endif
@@ -88,17 +90,9 @@
   virtual Void parseMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx ) = 0;
   virtual Void parseMergeIndex    ( TComDataCU* pcCU, UInt& ruiMergeIndex ) = 0;
-#if NH_3D_ARP
+#if NH_3D
   virtual Void parseARPW          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
-#endif
-#if NH_3D_IC
   virtual Void parseICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
-#endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   virtual Void  parseDeltaDC      ( TComDataCU* pcCU, UInt absPartIdx, UInt depth ) = 0;
-#endif
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   virtual Void parseSDCFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
-#endif
-#if NH_3D_DBBP
   virtual Void parseDBBPFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) = 0;
 #endif
@@ -139,4 +133,7 @@
   TDecEntropyIf*  m_pcEntropyDecoderIf;
   TComPrediction* m_pcPrediction;
+#if MCTS_ENC_CHECK
+  TDecConformanceCheck* m_pConformanceCheck;
+#endif
   //UInt    m_uiBakAbsPartIdx;
   //UInt    m_uiBakChromaOffset;
@@ -144,5 +141,9 @@
 
 public:
+#if MCTS_ENC_CHECK
+    Void init (TComPrediction* p, TDecConformanceCheck* pConformanceCheck) {m_pcPrediction = p; m_pConformanceCheck=pConformanceCheck;}
+#else
   Void init (TComPrediction* p) {m_pcPrediction = p;}
+#endif
   Void decodePUWise       ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, TComDataCU* pcSubCU );
   Void decodeInterDirPU   ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPartIdx );
@@ -177,5 +178,5 @@
   Void decodeSplitFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
   Void decodeSkipFlag          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-#if NH_3D_DIS
+#if NH_3D
   Void decodeDIS               ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth ) ;
 #endif
@@ -186,15 +187,8 @@
   Void decodePartSize          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
 
-#if NH_3D_ARP
+#if NH_3D
   Void decodeARPW              ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-#endif
-#if NH_3D_IC
   Void decodeICFlag            ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-#endif
-
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   Void decodeSDCFlag           ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-#endif
-#if NH_3D_DBBP
   Void decodeDBBPFlag          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
 #endif
Index: /trunk/source/Lib/TLibDecoder/TDecGop.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecGop.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecGop.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -122,5 +122,5 @@
   }
 
-#if NH_3D_NBDV 
+#if NH_3D
   if(pcSlice->getViewIndex() && !pcSlice->getIsDepth()) //Notes from QC: this condition shall be changed once the configuration is completed, e.g. in pcSlice->getSPS()->getMultiviewMvPredMode() || ARP in prev. HTM. Remove this comment once it is done.
   {
Index: /trunk/source/Lib/TLibDecoder/TDecGop.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecGop.h	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecGop.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibDecoder/TDecSbac.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecSbac.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -67,5 +67,5 @@
 , m_cCUSplitFlagSCModel                      ( 1,             1,                      NUM_SPLIT_FLAG_CTX                   , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cCUSkipFlagSCModel                       ( 1,             1,                      NUM_SKIP_FLAG_CTX                    , m_contextModels + m_numContextModels, m_numContextModels)
-#if NH_3D_DIS
+#if NH_3D
 , m_cCUDISFlagSCModel                        ( 1,             1,                      NUM_DIS_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cCUDISTypeSCModel                        ( 1,             1,                      NUM_DIS_TYPE_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
@@ -73,8 +73,6 @@
 , m_cCUMergeFlagExtSCModel                   ( 1,             1,                      NUM_MERGE_FLAG_EXT_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cCUMergeIdxExtSCModel                    ( 1,             1,                      NUM_MERGE_IDX_EXT_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
-#if NH_3D_ARP
+#if NH_3D
 , m_cCUPUARPWSCModel          ( 1,             1,               NUM_ARPW_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
-#endif
-#if NH_3D_IC
 , m_cCUICFlagSCModel          ( 1,             1,               NUM_IC_FLAG_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
 #endif
@@ -107,18 +105,12 @@
 , m_ChromaQpAdjIdcSCModel                    ( 1,             1,                      NUM_CHROMA_QP_ADJ_IDC_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
 
-#if NH_3D_DMM
+#if NH_3D
 , m_cNotDmmFlagSCModel                       ( 1,             1,                      NUM_NOTDMM_FLAG_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cDmmModeSCModel                          ( 1,             1,                      NUM_DMM_MODE_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
-#endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
 , m_cDdcDataSCModel                          ( 1,             1,                      NUM_DDC_DATA_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cSDCFlagSCModel                          ( 1,             1,                     NUM_SDC_FLAG_CTX                      , m_contextModels + m_numContextModels, m_numContextModels)
-#endif
-#if NH_3D_SDC_INTRA
 , m_cSDCResidualFlagSCModel                  ( 1,             1,                     SDC_NUM_RESIDUAL_FLAG_CTX             , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cSDCResidualSCModel                      ( 1,             1,                     SDC_NUM_RESIDUAL_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cDdcFlagSCModel                          ( 1,             1,                     NUM_DDC_FLAG_CTX                      , m_contextModels + m_numContextModels, m_numContextModels)
-#endif
-#if NH_3D_DBBP
 , m_cDBBPFlagSCModel                         ( 1,             1,                     DBBP_NUM_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
 #endif
@@ -159,5 +151,5 @@
   m_cCUSplitFlagSCModel.initBuffer                ( sliceType, qp, (UChar*)INIT_SPLIT_FLAG );
   m_cCUSkipFlagSCModel.initBuffer                 ( sliceType, qp, (UChar*)INIT_SKIP_FLAG );
-#if NH_3D_DIS
+#if NH_3D
   m_cCUDISFlagSCModel.initBuffer                  ( sliceType, qp, (UChar*)INIT_DIS_FLAG );
   m_cCUDISTypeSCModel.initBuffer                  ( sliceType, qp, (UChar*)INIT_DIS_TYPE );
@@ -165,8 +157,6 @@
   m_cCUMergeFlagExtSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_MERGE_FLAG_EXT );
   m_cCUMergeIdxExtSCModel.initBuffer              ( sliceType, qp, (UChar*)INIT_MERGE_IDX_EXT );
-#if NH_3D_ARP
+#if NH_3D
   m_cCUPUARPWSCModel.initBuffer          ( sliceType, qp, (UChar*)INIT_ARPW );
-#endif
-#if NH_3D_IC
   m_cCUICFlagSCModel.initBuffer          ( sliceType, qp, (UChar*)INIT_IC_FLAG );
 #endif
@@ -198,18 +188,12 @@
   m_ChromaQpAdjFlagSCModel.initBuffer             ( sliceType, qp, (UChar*)INIT_CHROMA_QP_ADJ_FLAG );
   m_ChromaQpAdjIdcSCModel.initBuffer              ( sliceType, qp, (UChar*)INIT_CHROMA_QP_ADJ_IDC );
-#if NH_3D_DMM
+#if NH_3D
   m_cNotDmmFlagSCModel.initBuffer                 ( sliceType, qp, (UChar*)INIT_NOTDMM_FLAG );
   m_cDmmModeSCModel.initBuffer                    ( sliceType, qp, (UChar*)INIT_DMM_MODE );
-#endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   m_cDdcDataSCModel.initBuffer                    ( sliceType, qp, (UChar*)INIT_DDC_DATA );
   m_cSDCFlagSCModel.initBuffer                    ( sliceType, qp, (UChar*)INIT_SDC_FLAG );
-#endif
-#if NH_3D_SDC_INTRA
   m_cSDCResidualFlagSCModel.initBuffer            ( sliceType, qp, (UChar*)INIT_SDC_RESIDUAL_FLAG );
   m_cSDCResidualSCModel.initBuffer                ( sliceType, qp, (UChar*)INIT_SDC_RESIDUAL );
   m_cDdcFlagSCModel.initBuffer                    ( sliceType, qp, (UChar*)INIT_DDC_FLAG );
-#endif
-#if NH_3D_DBBP
   m_cDBBPFlagSCModel.initBuffer                   ( sliceType, qp, (UChar*)INIT_DBBP_FLAG );
 #endif
@@ -512,5 +496,5 @@
 
 }
-#if NH_3D_DIS
+#if NH_3D
 Void TDecSbac::parseDIS( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
@@ -642,5 +626,5 @@
 
   UInt uiSymbol;
-#if NH_3D_QTLPC
+#if NH_3D
   Bool bParseSplitFlag    = true;
   Bool    bLimQtPredFlag = pcCU->getPic()->getSlice(0)->getQtPredFlag();
@@ -651,9 +635,5 @@
   Bool rapPic = (pcCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || pcCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP || pcCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA);
 
-#if H_3D_FCO
-  if(bDepthMapDetect && !bIntraSliceDetect && !rapPic && bLimQtPredFlag && pcTexture->getReconMark())
-#else
   if(bDepthMapDetect && !bIntraSliceDetect && !rapPic && bLimQtPredFlag)
-#endif
   {
     TComDataCU *pcTextureCU = pcTexture->getCtu(pcCU->getCtuRsAddr());
@@ -672,5 +652,5 @@
   DTRACE_CABAC_T( "\tSplitFlag\n" )
 #endif
-#if NH_3D_QTLPC
+#if NH_3D
   }
   else
@@ -704,5 +684,5 @@
   assert ( pcCU->getSlice()->getSPS()->getLog2DiffMaxMinCodingBlockSize() == log2DiffMaxMinCodingBlockSize);
 
-#if NH_3D_QTLPC
+#if NH_3D
   Bool bParsePartSize    = true;
 
@@ -717,9 +697,5 @@
   UInt uiTexturePart = uiMode;
 
-#if H_3D_FCO
-  if(bDepthMapDetect && !bIntraSliceDetect && !rapPic && bLimQtPredFlag && pcTexture->getReconMark())
-#else
   if(bDepthMapDetect && !bIntraSliceDetect && !rapPic && bLimQtPredFlag )
-#endif
   {
     TComDataCU *pcTextureCU = pcTexture->getCtu(pcCU->getCtuRsAddr());
@@ -740,18 +716,18 @@
   if ( pcCU->isIntra( uiAbsPartIdx ) )
   {
-#if NH_3D_QTLPC
+#if NH_3D
     if(bParsePartSize)
     {
 #endif
-    uiSymbol = 1;
-    if( uiDepth == log2DiffMaxMinCodingBlockSize )
-    {
-      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 0) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+      uiSymbol = 1;
+      if( uiDepth == log2DiffMaxMinCodingBlockSize )
+      {
+        m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 0) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
 #if NH_MV_ENC_DEC_TRAC          
         DTRACE_CU("part_mode", uiSymbol)
 #endif        
-    }
-    eMode = uiSymbol ? SIZE_2Nx2N : SIZE_NxN;
-#if NH_3D_QTLPC
+      }
+      eMode = uiSymbol ? SIZE_2Nx2N : SIZE_NxN;
+#if NH_3D
     }
 #endif
@@ -771,5 +747,5 @@
   else
   {
-#if NH_3D_QTLPC
+#if NH_3D
     if(bParsePartSize)
     {
@@ -777,51 +753,11 @@
       {
 #endif
-    UInt uiMaxNumBits = 2;
-
-    if( uiDepth == log2DiffMaxMinCodingBlockSize && !( cuWidth == 8 && cuHeight == 8 ) )
-    {
-      uiMaxNumBits ++;
-    }
-
-    for ( UInt ui = 0; ui < uiMaxNumBits; ui++ )
-    {
-      m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, ui) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
-      if ( uiSymbol )
-      {
-        break;
-      }
-      uiMode++;
-    }
-    eMode = (PartSize) uiMode;
-    if ( pcCU->getSlice()->getSPS()->getUseAMP() && uiDepth < log2DiffMaxMinCodingBlockSize )
-    {
-      if (eMode == SIZE_2NxN)
-      {
-        m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 3 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype));
-        if (uiSymbol == 0)
-        {
-          m_pcTDecBinIf->decodeBinEP(uiSymbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
-          eMode = (uiSymbol == 0? SIZE_2NxnU : SIZE_2NxnD);
-        }
-      }
-      else if (eMode == SIZE_Nx2N)
-      {
-        m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 3 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
-        if (uiSymbol == 0)
-        {
-          m_pcTDecBinIf->decodeBinEP(uiSymbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
-          eMode = (uiSymbol == 0? SIZE_nLx2N : SIZE_nRx2N);
-        }
-      }
-    }
-#if NH_3D_QTLPC
-      }
-      else if(uiTexturePart == SIZE_2NxN || uiTexturePart == SIZE_2NxnU || uiTexturePart == SIZE_2NxnD)
-      {
-        UInt uiMaxNumBits = 1;
-        if ( ( pcCU->getSlice()->getSPS()->getUseAMP() && uiDepth < log2DiffMaxMinCodingBlockSize ) && uiDepth < log2DiffMaxMinCodingBlockSize )
+        UInt uiMaxNumBits = 2;
+
+        if( uiDepth == log2DiffMaxMinCodingBlockSize && !( cuWidth == 8 && cuHeight == 8 ) )
         {
           uiMaxNumBits ++;
         }
+
         for ( UInt ui = 0; ui < uiMaxNumBits; ui++ )
         {
@@ -834,4 +770,44 @@
         }
         eMode = (PartSize) uiMode;
+        if ( pcCU->getSlice()->getSPS()->getUseAMP() && uiDepth < log2DiffMaxMinCodingBlockSize )
+        {
+          if (eMode == SIZE_2NxN)
+          {
+            m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 3 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype));
+            if (uiSymbol == 0)
+            {
+              m_pcTDecBinIf->decodeBinEP(uiSymbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+              eMode = (uiSymbol == 0? SIZE_2NxnU : SIZE_2NxnD);
+            }
+          }
+          else if (eMode == SIZE_Nx2N)
+          {
+            m_pcTDecBinIf->decodeBin(uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, 3 ) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+            if (uiSymbol == 0)
+            {
+              m_pcTDecBinIf->decodeBinEP(uiSymbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+              eMode = (uiSymbol == 0? SIZE_nLx2N : SIZE_nRx2N);
+            }
+          }
+        }
+#if NH_3D
+      }
+      else if(uiTexturePart == SIZE_2NxN || uiTexturePart == SIZE_2NxnU || uiTexturePart == SIZE_2NxnD)
+      {
+        UInt uiMaxNumBits = 1;
+        if ( ( pcCU->getSlice()->getSPS()->getUseAMP() && uiDepth < log2DiffMaxMinCodingBlockSize ) && uiDepth < log2DiffMaxMinCodingBlockSize )
+        {
+          uiMaxNumBits ++;
+        }
+        for ( UInt ui = 0; ui < uiMaxNumBits; ui++ )
+        {
+          m_pcTDecBinIf->decodeBin( uiSymbol, m_cCUPartSizeSCModel.get( 0, 0, ui) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+          if ( uiSymbol )
+          {
+            break;
+          }
+          uiMode++;
+        }
+        eMode = (PartSize) uiMode;
         if(uiMode && ( ( pcCU->getSlice()->getSPS()->getUseAMP() && uiDepth < log2DiffMaxMinCodingBlockSize ) && uiDepth < log2DiffMaxMinCodingBlockSize ) && uiSymbol==1 )
         {
@@ -887,5 +863,5 @@
       DTRACE_CU("part_mode", eMode )
 #endif
-#if NH_3D_QTLPC
+#if NH_3D
     }
 #endif
@@ -937,5 +913,5 @@
   for (j=0;j<partNum;j++)
   {
-#if NH_3D_DMM
+#if NH_3D
     if( pcCU->getSlice()->getIntraSdcWedgeFlag() || pcCU->getSlice()->getIntraContourFlag() )
     {
@@ -946,10 +922,10 @@
     {
 #endif
-    m_pcTDecBinIf->decodeBin( symbol, m_cCUIntraPredSCModel.get( 0, 0, 0) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
-    mpmPred[j] = symbol;
+      m_pcTDecBinIf->decodeBin( symbol, m_cCUIntraPredSCModel.get( 0, 0, 0) RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+      mpmPred[j] = symbol;
 #if NH_MV_ENC_DEC_TRAC          
       DTRACE_CU("prev_intra_luma_pred_flag", symbol)
 #endif
-#if NH_3D_DMM
+#if NH_3D
     }
 #endif
@@ -957,51 +933,51 @@
   for (j=0;j<partNum;j++)
   {
-#if NH_3D_DMM
+#if NH_3D
     if( pcCU->getIntraDir( CHANNEL_TYPE_LUMA, absPartIdx+partOffset*j ) < NUM_INTRA_MODE )
     {
 #endif
-    Int preds[NUM_MOST_PROBABLE_MODES] = {-1, -1, -1};
-    pcCU->getIntraDirPredictor(absPartIdx+partOffset*j, preds, COMPONENT_Y);
-    if (mpmPred[j])
-    {
-      m_pcTDecBinIf->decodeBinEP( symbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
-      if (symbol)
+      Int preds[NUM_MOST_PROBABLE_MODES] = {-1, -1, -1};
+      pcCU->getIntraDirPredictor(absPartIdx+partOffset*j, preds, COMPONENT_Y);
+      if (mpmPred[j])
       {
         m_pcTDecBinIf->decodeBinEP( symbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
-        symbol++;
-      }
+        if (symbol)
+        {
+          m_pcTDecBinIf->decodeBinEP( symbol RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+          symbol++;
+        }
 #if NH_MV_ENC_DEC_TRAC          
         DTRACE_CU("mpm_idx", symbol)
 #endif
-      intraPredMode = preds[symbol];
-    }
-    else
-    {
-      m_pcTDecBinIf->decodeBinsEP( symbol, 5 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
-      intraPredMode = symbol;
+          intraPredMode = preds[symbol];
+      }
+      else
+      {
+        m_pcTDecBinIf->decodeBinsEP( symbol, 5 RExt__DECODER_DEBUG_BIT_STATISTICS_PASS_OPT_ARG(ctype) );
+        intraPredMode = symbol;
 #if NH_MV_ENC_DEC_TRAC          
         DTRACE_CU("rem_intra_luma_pred_mode", symbol)
 #endif        
 
-      //postponed sorting of MPMs (only in remaining branch)
-      if (preds[0] > preds[1])
-      {
-        std::swap(preds[0], preds[1]);
-      }
-      if (preds[0] > preds[2])
-      {
-        std::swap(preds[0], preds[2]);
-      }
-      if (preds[1] > preds[2])
-      {
-        std::swap(preds[1], preds[2]);
-      }
-      for ( UInt i = 0; i < NUM_MOST_PROBABLE_MODES; i++ )
-      {
-        intraPredMode += ( intraPredMode >= preds[i] );
-      }
-    }
-    pcCU->setIntraDirSubParts(CHANNEL_TYPE_LUMA, (UChar)intraPredMode, absPartIdx+partOffset*j, depth );
-#if NH_3D_DMM
+          //postponed sorting of MPMs (only in remaining branch)
+          if (preds[0] > preds[1])
+          {
+            std::swap(preds[0], preds[1]);
+          }
+          if (preds[0] > preds[2])
+          {
+            std::swap(preds[0], preds[2]);
+          }
+          if (preds[1] > preds[2])
+          {
+            std::swap(preds[1], preds[2]);
+          }
+          for ( UInt i = 0; i < NUM_MOST_PROBABLE_MODES; i++ )
+          {
+            intraPredMode += ( intraPredMode >= preds[i] );
+          }
+      }
+      pcCU->setIntraDirSubParts(CHANNEL_TYPE_LUMA, (UChar)intraPredMode, absPartIdx+partOffset*j, depth );
+#if NH_3D
     }
 #endif
@@ -1679,5 +1655,5 @@
   else
   {
-    beValid = pcCU->getSlice()->getPPS()->getSignHideFlag();
+    beValid = pcCU->getSlice()->getPPS()->getSignDataHidingEnabledFlag();
   }
 
@@ -2269,5 +2245,5 @@
 }
 
-#if NH_3D_ARP
+#if NH_3D
 Void TDecSbac::parseARPW( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
@@ -2289,7 +2265,5 @@
   pcCU->setARPWSubParts( ( UChar )( uiW ) , uiAbsPartIdx, uiDepth );  
 }
-#endif
-
-#if NH_3D_IC
+
 /** parse illumination compensation flag
  * \param pcCU
@@ -2317,19 +2291,12 @@
   pcCU->setICFlagSubParts( uiSymbol ? true : false , uiAbsPartIdx, 0, uiDepth );
 }
-#endif
-
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
+
 Void TDecSbac::parseDeltaDC( TComDataCU* pcCU, UInt absPartIdx, UInt depth )
 {
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   if( !(pcCU->getSDCFlag( absPartIdx )) )
-#endif
-#if NH_3D_DMM
-  if( !(pcCU->isIntra( absPartIdx ) && isDmmMode( pcCU->getIntraDir( CHANNEL_TYPE_LUMA, absPartIdx ) )) )
-#endif
-    assert( 0 );
+    if( !(pcCU->isIntra( absPartIdx ) && isDmmMode( pcCU->getIntraDir( CHANNEL_TYPE_LUMA, absPartIdx ) )) )
+      assert( 0 );
 
   UInt symbol = 1;
-#if NH_3D_SDC_INTRA
   if( pcCU->isIntra( absPartIdx ) && pcCU->getSDCFlag( absPartIdx ))
   {
@@ -2338,10 +2305,6 @@
     assert( pcCU->getTransformIdx(absPartIdx) == 0 );
     assert( pcCU->getCbf(absPartIdx, COMPONENT_Y) == 1 );
-    }
-#endif
-  UInt uiNumSegments = 1;
-#if NH_3D_DMM
-  uiNumSegments = isDmmMode( pcCU->getIntraDir( CHANNEL_TYPE_LUMA, absPartIdx ) ) ? 2 : 1;
-#endif
+  }
+  UInt uiNumSegments = isDmmMode( pcCU->getIntraDir( CHANNEL_TYPE_LUMA, absPartIdx ) ) ? 2 : 1;
 
   for( UInt segment = 0; segment < uiNumSegments; segment++ )
@@ -2355,5 +2318,4 @@
     if( pcCU->isIntra( absPartIdx ) )
     {
-#if NH_3D_SDC_INTRA
       if( pcCU->getSDCFlag( absPartIdx ) )
       {
@@ -2362,18 +2324,11 @@
       else
       {
-#endif
-#if NH_3D_DMM
         pcCU->setDmmDeltaDC( getDmmType( pcCU->getIntraDir( CHANNEL_TYPE_LUMA, absPartIdx ) ), segment, absPartIdx, valDeltaDC );
-#endif
-#if NH_3D_SDC_INTRA
-      }
-#endif
-    }
-#if NH_3D_SDC_INTER
+      }
+    }
     else
     {
       pcCU->setSDCSegmentDCOffset( valDeltaDC, segment, absPartIdx );
     }
-#endif
   }
 }
@@ -2419,6 +2374,5 @@
   return;
 }
-#endif
-#if NH_3D_DMM
+
 Void TDecSbac::xParseIntraDepthMode( TComDataCU* pcCU, UInt absPartIdx, UInt depth )
 {
@@ -2488,6 +2442,5 @@
   ruiTabIdx = uiIdx;
 }
-#endif
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
+
 Void TDecSbac::parseSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
@@ -2510,7 +2463,4 @@
 }
 
-#endif
-
-#if NH_3D_DBBP
 Void TDecSbac::parseDBBPFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth )
 {
Index: /trunk/source/Lib/TLibDecoder/TDecSbac.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecSbac.h	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecSbac.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -108,21 +108,13 @@
   Void  xReadCoefRemainExGolomb ( UInt &rSymbol, UInt &rParam, const Bool useLimitedPrefixLength, const Int maxLog2TrDynamicRange );
 #endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
+#if NH_3D
   Void  xReadExGolombLevelDdc( UInt& ruiSymbol );
   Void  xParseDeltaDC        ( Pel& rValDeltaDC, UInt uiNumSeg );
-#endif
-#if NH_3D_DMM
   Void  xParseIntraDepthMode ( TComDataCU* pcCU, UInt absPartIdx, UInt depth );
   Void  xParseDmmData        ( TComDataCU* pcCU, UInt absPartIdx, UInt depth );
   Void  xParseDmm1WedgeIdx   ( UInt& ruiTabIdx, Int iNumBit );
-#endif
-#if NH_3D_SDC_INTRA
   Void  xParseSDCResidualData     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPart );
-#endif
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   Void  parseSDCFlag         ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-#endif
-#if NH_3D_DBBP
-  Void parseDBBPFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
+  Void  parseDBBPFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
 #endif
 
@@ -134,8 +126,6 @@
 
   Void parseSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-#if NH_3D_DIS
+#if NH_3D
   Void parseDIS          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-#endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   Void  parseDeltaDC      ( TComDataCU* pcCU, UInt absPartIdx, UInt depth );
 #endif
@@ -144,8 +134,6 @@
   Void parseMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth, UInt uiPUIdx );
   Void parseMergeIndex    ( TComDataCU* pcCU, UInt& ruiMergeIndex );
-#if NH_3D_ARP
+#if NH_3D
   Void parseARPW          ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
-#endif
-#if NH_3D_IC
   Void parseICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx, UInt uiDepth );
 #endif
@@ -183,5 +171,5 @@
   ContextModel3DBuffer m_cCUSplitFlagSCModel;
   ContextModel3DBuffer m_cCUSkipFlagSCModel;
-#if NH_3D_DIS
+#if NH_3D
   ContextModel3DBuffer m_cCUDISFlagSCModel;
   ContextModel3DBuffer m_cCUDISTypeSCModel;
@@ -189,8 +177,6 @@
   ContextModel3DBuffer m_cCUMergeFlagExtSCModel;
   ContextModel3DBuffer m_cCUMergeIdxExtSCModel;
-#if NH_3D_ARP
+#if NH_3D
   ContextModel3DBuffer m_cCUPUARPWSCModel;
-#endif
-#if NH_3D_IC
   ContextModel3DBuffer m_cCUICFlagSCModel;
 #endif
@@ -226,18 +212,12 @@
   ContextModel3DBuffer m_ChromaQpAdjFlagSCModel;
   ContextModel3DBuffer m_ChromaQpAdjIdcSCModel;
-#if NH_3D_DMM
+#if NH_3D
   ContextModel3DBuffer m_cNotDmmFlagSCModel;
   ContextModel3DBuffer m_cDmmModeSCModel;
-#endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   ContextModel3DBuffer m_cDdcDataSCModel;
   ContextModel3DBuffer m_cSDCFlagSCModel;
-#endif
-#if NH_3D_SDC_INTRA  
   ContextModel3DBuffer m_cSDCResidualFlagSCModel;
   ContextModel3DBuffer m_cSDCResidualSCModel;
   ContextModel3DBuffer m_cDdcFlagSCModel;
-#endif
-#if NH_3D_DBBP
   ContextModel3DBuffer m_cDBBPFlagSCModel;
 #endif
Index: /trunk/source/Lib/TLibDecoder/TDecSlice.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecSlice.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -37,4 +37,5 @@
 
 #include "TDecSlice.h"
+#include "TDecConformance.h"
 
 //! \ingroup TLibDecoder
@@ -61,8 +62,9 @@
 }
 
-Void TDecSlice::init(TDecEntropy* pcEntropyDecoder, TDecCu* pcCuDecoder)
+Void TDecSlice::init(TDecEntropy* pcEntropyDecoder, TDecCu* pcCuDecoder, TDecConformanceCheck *pDecConformanceCheck)
 {
   m_pcEntropyDecoder  = pcEntropyDecoder;
   m_pcCuDecoder       = pcCuDecoder;
+  m_pDecConformanceCheck = pDecConformanceCheck;
 }
 
@@ -130,5 +132,5 @@
     }
   }
-#if  NH_3D_DLT
+#if  NH_3D
   if( pcSlice->getPPS()->getDLT() != NULL )
   {
@@ -186,4 +188,8 @@
 #endif
 
+#if DECODER_PARTIAL_CONFORMANCE_CHECK != 0
+    const UInt numRemainingBitsPriorToCtu=ppcSubstreams[uiSubStrm]->getNumBitsLeft();
+#endif
+
     if ( pcSlice->getSPS()->getUseSAO() )
     {
@@ -224,4 +230,13 @@
 
     m_pcCuDecoder->decodeCtu     ( pCtu, isLastCtuOfSliceSegment );
+
+#if DECODER_PARTIAL_CONFORMANCE_CHECK != 0
+    const UInt numRemainingBitsPostCtu=ppcSubstreams[uiSubStrm]->getNumBitsLeft(); // NOTE: Does not account for changes in buffered bits in CABAC decoder, although it's probably good enough.
+    if (TDecConformanceCheck::doChecking() && m_pDecConformanceCheck)
+    {
+      m_pDecConformanceCheck->checkCtuDecoding(numRemainingBitsPriorToCtu-numRemainingBitsPostCtu);
+    }
+#endif
+
     m_pcCuDecoder->decompressCtu ( pCtu );
 
Index: /trunk/source/Lib/TLibDecoder/TDecSlice.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecSlice.h	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecSlice.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -58,4 +58,6 @@
 // ====================================================================================================================
 
+class TDecConformanceCheck;
+
 /// slice decoder class
 class TDecSlice
@@ -65,4 +67,5 @@
   TDecEntropy*    m_pcEntropyDecoder;
   TDecCu*         m_pcCuDecoder;
+  TDecConformanceCheck *m_pDecConformanceCheck;
 
   TDecSbac        m_lastSliceSegmentEndContextState;    ///< context storage for state at the end of the previous slice-segment (used for dependent slices only).
@@ -73,5 +76,5 @@
   virtual ~TDecSlice();
 
-  Void  init              ( TDecEntropy* pcEntropyDecoder, TDecCu* pcMbDecoder );
+  Void  init              ( TDecEntropy* pcEntropyDecoder, TDecCu* pcMbDecoder, TDecConformanceCheck *pDecConformanceCheck );
   Void  create            ();
   Void  destroy           ();
Index: /trunk/source/Lib/TLibDecoder/TDecTop.cpp
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecTop.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecTop.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -37,4 +37,6 @@
 #include "NALread.h"
 #include "TDecTop.h"
+#include "TDecConformance.h"
+
 #if NH_MV
 ParameterSetManager TDecTop::m_parameterSetManager;
@@ -227,10 +229,8 @@
   }
 
-#if !H_3D_FCO
   if ( pcSlice->getIsDepth())
   {
     return;
   }
-#endif
 
   Int curPoc = pcSlice->getPOC();
@@ -376,4 +376,7 @@
   , m_warningMessageSkipPicture(false)
 #endif
+#if MCTS_ENC_CHECK
+  , m_tmctsCheckEnabled(false)
+#endif
   , m_prefixSEINALUs()
 {
@@ -471,6 +474,10 @@
 #endif
   m_cGopDecoder.init( &m_cEntropyDecoder, &m_cSbacDecoder, &m_cBinCABAC, &m_cCavlcDecoder, &m_cSliceDecoder, &m_cLoopFilter, &m_cSAO);
-  m_cSliceDecoder.init( &m_cEntropyDecoder, &m_cCuDecoder );
+  m_cSliceDecoder.init( &m_cEntropyDecoder, &m_cCuDecoder, &m_conformanceCheck );
+#if MCTS_ENC_CHECK
+  m_cEntropyDecoder.init(&m_cPrediction, &m_conformanceCheck );
+#else
   m_cEntropyDecoder.init(&m_cPrediction);
+#endif
 }
 
@@ -506,5 +513,9 @@
     rpcPic = new TComPic();
 
+#if REDUCED_ENCODER_MEMORY
+    rpcPic->create ( sps, pps, false, true);
+#else
     rpcPic->create ( sps, pps, true);
+#endif
 
     m_cListPic.pushBack( rpcPic );
@@ -543,5 +554,9 @@
   }
   rpcPic->destroy();
+#if REDUCED_ENCODER_MEMORY
+  rpcPic->create ( sps, pps, false, true);
+#else
   rpcPic->create ( sps, pps, true);
+#endif
 }
 
@@ -692,4 +707,7 @@
 
     xParsePrefixSEImessages();
+#if MCTS_ENC_CHECK
+    xAnalysePrefixSEImessages();
+#endif
 
 #if RExt__HIGH_BIT_DEPTH_SUPPORT==0
@@ -726,5 +744,5 @@
     sps=pSlice->getSPS();
 
-#if NH_MV
+#if NH_MV    
     pSlice->setPic( m_pcPic );
     vps=pSlice->getVPS();
@@ -772,5 +790,9 @@
     // Recursive structure
     m_cCuDecoder.create ( sps->getMaxTotalCUDepth(), sps->getMaxCUWidth(), sps->getMaxCUHeight(), sps->getChromaFormatIdc() );
+#if MCTS_ENC_CHECK
+    m_cCuDecoder.init   ( &m_cEntropyDecoder, &m_cTrQuant, &m_cPrediction, &m_conformanceCheck );
+#else
     m_cCuDecoder.init   ( &m_cEntropyDecoder, &m_cTrQuant, &m_cPrediction );
+#endif
     m_cTrQuant.init     ( sps->getMaxTrSize() );
 
@@ -807,4 +829,7 @@
     xParsePrefixSEImessages();
 
+#if MCTS_ENC_CHECK
+    xAnalysePrefixSEImessages();
+#endif
     // Check if any new SEI has arrived
     if(!m_SEIs.empty())
@@ -845,4 +870,29 @@
   }
 }
+
+#if MCTS_ENC_CHECK
+Void TDecTop::xAnalysePrefixSEImessages()
+{
+  if (m_tmctsCheckEnabled)
+  {
+    SEIMessages mctsSEIs = getSeisByType(m_SEIs, SEI::TEMP_MOTION_CONSTRAINED_TILE_SETS);
+    for (SEIMessages::iterator it = mctsSEIs.begin(); it != mctsSEIs.end(); it++)
+    {
+      SEITempMotionConstrainedTileSets *mcts = (SEITempMotionConstrainedTileSets*)(*it);
+      if (!mcts->m_each_tile_one_tile_set_flag)
+      {
+        printf("cannot (yet) check Temporal constrained MCTS if each_tile_one_tile_set_flag is not enabled\n");
+        exit(1);
+      }
+      else
+      {
+        printf("MCTS check enabled!\n");
+        m_conformanceCheck.enableTMctsCheck(true);
+      }
+    }
+  }
+}
+#endif
+
 
 #if !NH_MV
@@ -1023,9 +1073,15 @@
   xActivateParameterSets();
 
+
+
+  TComSlice* pcSlice = m_pcPic->getPicSym()->getSlice(m_uiSliceIdx);
+
+  if (TDecConformanceCheck::doChecking())
+  {
+    m_conformanceCheck.checkSliceActivation(*pcSlice, nalu, *m_pcPic, m_bFirstSliceInBitstream, m_bFirstSliceInSequence, m_bFirstSliceInPicture);
+  }
+
   m_bFirstSliceInSequence = false;
   m_bFirstSliceInBitstream  = false;
-
-
-  TComSlice* pcSlice = m_pcPic->getPicSym()->getSlice(m_uiSliceIdx);
 
 #endif
@@ -1105,8 +1161,6 @@
         }
       }
-#if NH_3D_NBDV
+#if NH_3D
       pcSlice->setDefaultRefView();
-#endif
-#if NH_3D_ARP
       pcSlice->setPocsInCurrRPSs();
       pcSlice->setARPStepNum(m_dpb);
@@ -1155,5 +1209,5 @@
       //---------------
       pcSlice->setRefPOCList();
-#if  NH_3D_TMVP
+#if  NH_3D
       if(pcSlice->getLayerId())
       {
@@ -1253,5 +1307,5 @@
   pps->setLayerId( getLayerId() );
 #endif
-#if NH_3D_DLT
+#if NH_3D
   // create mapping from depth layer indexes to layer ids
   Int j=0;
@@ -1863,7 +1917,16 @@
     {
       Int profileIdc = vps->getPTL( vps->getProfileTierLevelIdx( m_targetOlsIdx, lIdx ) )->getGeneralPTL()->getProfileIdc();
-      assert( profileIdc == 1 || profileIdc == 6 || profileIdc == 8 );
-
-      if (  profileIdc == 6 )
+
+#if !NH_MV_ALLOW_NON_CONFORMING
+      assert( profileIdc == Profile::MAIN || profileIdc == Profile::MULTIVIEWMAIN|| profileIdc == Profile::MAIN3D );
+#else
+      assert( profileIdc == Profile::MAIN || profileIdc == Profile::MAIN10 || profileIdc == Profile::MULTIVIEWMAIN|| profileIdc == Profile::MAIN3D || profileIdc == Profile::NONE || profileIdc == Profile::MULTIVIEWMAIN_NONCONFORMING || profileIdc == Profile::MAIN3D_NONCONFORMING  );
+#endif 
+
+      if (   profileIdc == Profile::MULTIVIEWMAIN
+#if NH_MV_ALLOW_NON_CONFORMING
+      ||     profileIdc == Profile::MULTIVIEWMAIN_NONCONFORMING
+#endif
+        )
       {
         m_decodingProcess = ANNEX_G;
@@ -1873,5 +1936,9 @@
         m_decodingProcess = ANNEX_H;
       }
-      else if (profileIdc == 8 )
+      else if (profileIdc == Profile::MAIN3D 
+#if NH_MV_ALLOW_NON_CONFORMING
+      ||     profileIdc == Profile::MAIN3D_NONCONFORMING
+#endif  
+        )
       {
         m_decodingProcess = ANNEX_I;
Index: /trunk/source/Lib/TLibDecoder/TDecTop.h
===================================================================
--- /trunk/source/Lib/TLibDecoder/TDecTop.h	(revision 1412)
+++ /trunk/source/Lib/TLibDecoder/TDecTop.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -52,4 +52,5 @@
 #include "TDecCAVLC.h"
 #include "SEIread.h"
+#include "TDecConformance.h"
 
 class InputNALUnit;
@@ -204,4 +205,5 @@
   TComLoopFilter          m_cLoopFilter;
   TComSampleAdaptiveOffset m_cSAO;
+  TDecConformanceCheck    m_conformanceCheck;
 
   Bool isSkipPictureForBLA(Int& iPOCLastDisplay);
@@ -236,4 +238,9 @@
 #endif
 
+#if MCTS_ENC_CHECK
+  Bool                    m_tmctsCheckEnabled;
+
+#endif
+
 #if NH_MV
   // Class interface 
@@ -286,5 +293,7 @@
 
   Void setDecodedPictureHashSEIEnabled(Int enabled) { m_cGopDecoder.setDecodedPictureHashSEIEnabled(enabled); }
-
+#if MCTS_ENC_CHECK
+  Void setTMctsCheckEnabled(Bool enabled) { m_tmctsCheckEnabled = enabled; }
+#endif
   Void  init();
 #if !NH_MV
@@ -405,4 +414,7 @@
 
   Void      xParsePrefixSEImessages();
+#if MCTS_ENC_CHECK
+  Void      xAnalysePrefixSEImessages();
+#endif
   Void      xParsePrefixSEIsForUnknownVCLNal();
 
Index: /trunk/source/Lib/TLibEncoder/AnnexBwrite.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/AnnexBwrite.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibEncoder/NALwrite.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/NALwrite.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/NALwrite.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibEncoder/NALwrite.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/NALwrite.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/NALwrite.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibEncoder/SEIEncoder.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/SEIEncoder.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/SEIEncoder.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -346,4 +346,16 @@
   if(pps->getTilesEnabledFlag())
   {
+#if MCTS_ENC_CHECK
+    if (m_pcCfg->getTMCTSSEITileConstraint())
+    {
+      sei->m_mc_all_tiles_exact_sample_value_match_flag = true;
+      sei->m_each_tile_one_tile_set_flag = true;
+      sei->m_limited_tile_set_display_flag = false;
+      sei->m_max_mcs_tier_level_idc_present_flag = false;
+      sei->setNumberOfTileSets(0);
+    }
+    else
+    {
+#endif
     sei->m_mc_all_tiles_exact_sample_value_match_flag = false;
     sei->m_each_tile_one_tile_set_flag                = false;
@@ -365,4 +377,7 @@
       sei->tileSetData(i).m_mcts_tier_level_idc_present_flag = false;
     }
+#if MCTS_ENC_CHECK
+    }
+#endif
   }
   else
@@ -651,5 +666,4 @@
   }
 }
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
 Void SEIEncoder::initSEIAlternativeTransferCharacteristics(SEIAlternativeTransferCharacteristics *seiAltTransCharacteristics)
 {
@@ -659,5 +673,15 @@
   seiAltTransCharacteristics->m_preferredTransferCharacteristics = m_pcCfg->getSEIPreferredTransferCharacteristics();
 }
-#endif
+
+Void SEIEncoder::initSEIGreenMetadataInfo(SEIGreenMetadataInfo *seiGreenMetadataInfo, UInt u)
+{
+    assert (m_isInitialized);
+    assert (seiGreenMetadataInfo!=NULL);
+
+    seiGreenMetadataInfo->m_greenMetadataType = m_pcCfg->getSEIGreenMetadataType();
+    seiGreenMetadataInfo->m_xsdMetricType = m_pcCfg->getSEIXSDMetricType();
+    seiGreenMetadataInfo->m_xsdMetricValue = u;
+}
+
 
 #if NH_MV
Index: /trunk/source/Lib/TLibEncoder/SEIEncoder.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/SEIEncoder.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/SEIEncoder.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -82,11 +82,11 @@
   Void initSEITimeCode(SEITimeCode *sei);
   Bool initSEIColourRemappingInfo(SEIColourRemappingInfo *sei, Int currPOC); // returns true on success, false on failure.
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
   Void initSEIAlternativeTransferCharacteristics(SEIAlternativeTransferCharacteristics *sei);
-#endif
 
   // trailing SEIs
   Void initDecodedPictureHashSEI(SEIDecodedPictureHash *sei, TComPic *pcPic, std::string &rHashString, const BitDepths &bitDepths);
   Void initTemporalLevel0IndexSEI(SEITemporalLevel0Index *sei, TComSlice *slice);
+  Void initSEIGreenMetadataInfo(SEIGreenMetadataInfo *sei, UInt u);
+
 #if NH_MV
   Void createAnnexFGISeiMessages( SEIMessages& seiMessage, const TComSlice* slice );;
Index: /trunk/source/Lib/TLibEncoder/SEIwrite.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/SEIwrite.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -58,6 +58,57 @@
   switch (sei.payloadType())
   {
+  case SEI::BUFFERING_PERIOD:
+    xWriteSEIBufferingPeriod(*static_cast<const SEIBufferingPeriod*>(&sei), sps);
+    break;
+  case SEI::PICTURE_TIMING:
+    xWriteSEIPictureTiming(*static_cast<const SEIPictureTiming*>(&sei), sps);
+    break;
+  case SEI::PAN_SCAN_RECT:
+    xWriteSEIPanScanRect(*static_cast<const SEIPanScanRect*>(&sei));
+    break;
+  case SEI::FILLER_PAYLOAD:
+    xWriteSEIFillerPayload(*static_cast<const SEIFillerPayload*>(&sei));
+    break;
+  case SEI::USER_DATA_REGISTERED_ITU_T_T35:
+    xWriteSEIUserDataRegistered(*static_cast<const SEIUserDataRegistered*>(&sei));
+    break;
   case SEI::USER_DATA_UNREGISTERED:
-    xWriteSEIuserDataUnregistered(*static_cast<const SEIuserDataUnregistered*>(&sei));
+    xWriteSEIUserDataUnregistered(*static_cast<const SEIUserDataUnregistered*>(&sei));
+    break;
+  case SEI::RECOVERY_POINT:
+    xWriteSEIRecoveryPoint(*static_cast<const SEIRecoveryPoint*>(&sei));
+    break;
+  case SEI::SCENE_INFO:
+    xWriteSEISceneInfo(*static_cast<const SEISceneInfo*>(&sei));
+    break;
+  case SEI::PICTURE_SNAPSHOT:
+    xWriteSEIPictureSnapshot(*static_cast<const SEIPictureSnapshot*>(&sei));
+    break;
+  case SEI::PROGRESSIVE_REFINEMENT_SEGMENT_START:
+    xWriteSEIProgressiveRefinementSegmentStart(*static_cast<const SEIProgressiveRefinementSegmentStart*>(&sei));
+    break;
+  case SEI::PROGRESSIVE_REFINEMENT_SEGMENT_END:
+    xWriteSEIProgressiveRefinementSegmentEnd(*static_cast<const SEIProgressiveRefinementSegmentEnd*>(&sei));
+    break;
+  case SEI::FILM_GRAIN_CHARACTERISTICS:
+    xWriteSEIFilmGrainCharacteristics(*static_cast<const SEIFilmGrainCharacteristics*>(&sei));
+    break;
+  case SEI::POST_FILTER_HINT:
+    xWriteSEIPostFilterHint(*static_cast<const SEIPostFilterHint*>(&sei), sps);
+    break;
+  case SEI::TONE_MAPPING_INFO:
+    xWriteSEIToneMappingInfo(*static_cast<const SEIToneMappingInfo*>(&sei));
+    break;
+  case SEI::FRAME_PACKING:
+    xWriteSEIFramePacking(*static_cast<const SEIFramePacking*>(&sei));
+    break;
+  case SEI::DISPLAY_ORIENTATION:
+    xWriteSEIDisplayOrientation(*static_cast<const SEIDisplayOrientation*>(&sei));
+    break;
+  case SEI::GREEN_METADATA:
+      xWriteSEIGreenMetadataInfo(*static_cast<const SEIGreenMetadataInfo*>(&sei));
+    break;
+  case SEI::SOP_DESCRIPTION:
+    xWriteSEISOPDescription(*static_cast<const SEISOPDescription*>(&sei));
     break;
   case SEI::ACTIVE_PARAMETER_SETS:
@@ -67,52 +118,34 @@
     xWriteSEIDecodingUnitInfo(*static_cast<const SEIDecodingUnitInfo*>(& sei), sps);
     break;
+  case SEI::TEMPORAL_LEVEL0_INDEX:
+    xWriteSEITemporalLevel0Index(*static_cast<const SEITemporalLevel0Index*>(&sei));
+    break;
   case SEI::DECODED_PICTURE_HASH:
     xWriteSEIDecodedPictureHash(*static_cast<const SEIDecodedPictureHash*>(&sei));
     break;
-  case SEI::BUFFERING_PERIOD:
-    xWriteSEIBufferingPeriod(*static_cast<const SEIBufferingPeriod*>(&sei), sps);
-    break;
-  case SEI::PICTURE_TIMING:
-    xWriteSEIPictureTiming(*static_cast<const SEIPictureTiming*>(&sei), sps);
-    break;
-  case SEI::RECOVERY_POINT:
-    xWriteSEIRecoveryPoint(*static_cast<const SEIRecoveryPoint*>(&sei));
-    break;
-  case SEI::FRAME_PACKING:
-    xWriteSEIFramePacking(*static_cast<const SEIFramePacking*>(&sei));
+  case SEI::SCALABLE_NESTING:
+    xWriteSEIScalableNesting(bs, *static_cast<const SEIScalableNesting*>(&sei), sps);
+    break;
+  case SEI::REGION_REFRESH_INFO:
+    xWriteSEIRegionRefreshInfo(*static_cast<const SEIRegionRefreshInfo*>(&sei));
+    break;
+  case SEI::NO_DISPLAY:
+    xWriteSEINoDisplay(*static_cast<const SEINoDisplay*>(&sei));
+    break;
+  case SEI::TIME_CODE:
+    xWriteSEITimeCode(*static_cast<const SEITimeCode*>(&sei));
+    break;
+  case SEI::MASTERING_DISPLAY_COLOUR_VOLUME:
+    xWriteSEIMasteringDisplayColourVolume(*static_cast<const SEIMasteringDisplayColourVolume*>(&sei));
     break;
   case SEI::SEGM_RECT_FRAME_PACKING:
     xWriteSEISegmentedRectFramePacking(*static_cast<const SEISegmentedRectFramePacking*>(&sei));
     break;
-  case SEI::DISPLAY_ORIENTATION:
-    xWriteSEIDisplayOrientation(*static_cast<const SEIDisplayOrientation*>(&sei));
-    break;
-  case SEI::TEMPORAL_LEVEL0_INDEX:
-    xWriteSEITemporalLevel0Index(*static_cast<const SEITemporalLevel0Index*>(&sei));
-    break;
-  case SEI::REGION_REFRESH_INFO:
-    xWriteSEIGradualDecodingRefreshInfo(*static_cast<const SEIGradualDecodingRefreshInfo*>(&sei));
-    break;
-  case SEI::NO_DISPLAY:
-    xWriteSEINoDisplay(*static_cast<const SEINoDisplay*>(&sei));
-    break;
-  case SEI::TONE_MAPPING_INFO:
-    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);
+  case SEI::TEMP_MOTION_CONSTRAINED_TILE_SETS:
+    xWriteSEITempMotionConstrainedTileSets(*static_cast<const SEITempMotionConstrainedTileSets*>(&sei));
     break;
   case SEI::CHROMA_RESAMPLING_FILTER_HINT:
     xWriteSEIChromaResamplingFilterHint(*static_cast<const SEIChromaResamplingFilterHint*>(&sei));
     break;
-  case SEI::TEMP_MOTION_CONSTRAINED_TILE_SETS:
-    xWriteSEITempMotionConstrainedTileSets(*static_cast<const SEITempMotionConstrainedTileSets*>(&sei));
-    break;
-  case SEI::TIME_CODE:
-    xWriteSEITimeCode(*static_cast<const SEITimeCode*>(&sei));
-    break;
   case SEI::KNEE_FUNCTION_INFO:
     xWriteSEIKneeFunctionInfo(*static_cast<const SEIKneeFunctionInfo*>(&sei));
@@ -121,12 +154,22 @@
     xWriteSEIColourRemappingInfo(*static_cast<const SEIColourRemappingInfo*>(&sei));
     break;
-  case SEI::MASTERING_DISPLAY_COLOUR_VOLUME:
-    xWriteSEIMasteringDisplayColourVolume(*static_cast<const SEIMasteringDisplayColourVolume*>(&sei));
-    break;
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
+  case SEI::DEINTERLACE_FIELD_IDENTIFICATION:
+    xWriteSEIDeinterlaceFieldIdentification(*static_cast<const SEIDeinterlaceFieldIdentification*>(&sei));
+    break;
+  case SEI::CONTENT_LIGHT_LEVEL_INFO:
+    xWriteSEIContentLightLevelInfo(*static_cast<const SEIContentLightLevelInfo*>(&sei));
+    break;
+  case SEI::DEPENDENT_RAP_INDICATION:
+    xWriteSEIDependentRAPIndication(*static_cast<const SEIDependentRAPIndication*>(&sei));
+    break;
+  case SEI::CODED_REGION_COMPLETION:
+    xWriteSEICodedRegionCompletion(*static_cast<const SEICodedRegionCompletion*>(&sei));
+    break;
   case SEI::ALTERNATIVE_TRANSFER_CHARACTERISTICS:
     xWriteSEIAlternativeTransferCharacteristics(*static_cast<const SEIAlternativeTransferCharacteristics*>(&sei));
     break;
-#endif
+  case SEI::AMBIENT_VIEWING_ENVIRONMENT:
+    xWriteSEIAmbientViewingEnvironment(*static_cast<const SEIAmbientViewingEnvironment*>(&sei));
+    break;
 
 #if NH_MV
@@ -252,75 +295,4 @@
 }
 
-/**
- * marshal a user_data_unregistered SEI message sei, storing the marshalled
- * representation in bitstream bs.
- */
-Void SEIWriter::xWriteSEIuserDataUnregistered(const SEIuserDataUnregistered &sei)
-{
-  for (UInt i = 0; i < ISO_IEC_11578_LEN; i++)
-  {
-    WRITE_CODE(sei.uuid_iso_iec_11578[i], 8 , "sei.uuid_iso_iec_11578[i]");
-  }
-
-  for (UInt i = 0; i < sei.userDataLength; i++)
-  {
-    WRITE_CODE(sei.userData[i], 8 , "user_data");
-  }
-}
-
-/**
- * marshal a decoded picture hash SEI message, storing the marshalled
- * representation in bitstream bs.
- */
-Void SEIWriter::xWriteSEIDecodedPictureHash(const SEIDecodedPictureHash& sei)
-{
-  const TChar *traceString="\0";
-  switch (sei.method)
-  {
-    case HASHTYPE_MD5: traceString="picture_md5"; break;
-    case HASHTYPE_CRC: traceString="picture_crc"; break;
-    case HASHTYPE_CHECKSUM: traceString="picture_checksum"; break;
-    default: assert(false); break;
-  }
-
-  if (traceString != 0) //use of this variable is needed to avoid a compiler error with G++ 4.6.1
-  {
-    WRITE_CODE(sei.method, 8, "hash_type");
-    for(UInt i=0; i<UInt(sei.m_pictureHash.hash.size()); i++)
-    {
-      WRITE_CODE(sei.m_pictureHash.hash[i], 8, traceString);
-    }
-  }
-}
-
-Void SEIWriter::xWriteSEIActiveParameterSets(const SEIActiveParameterSets& sei)
-{
-  WRITE_CODE(sei.activeVPSId,     4,         "active_video_parameter_set_id");
-  WRITE_FLAG(sei.m_selfContainedCvsFlag,     "self_contained_cvs_flag");
-  WRITE_FLAG(sei.m_noParameterSetUpdateFlag, "no_parameter_set_update_flag");
-  WRITE_UVLC(sei.numSpsIdsMinus1,            "num_sps_ids_minus1");
-
-  assert (sei.activeSeqParameterSetId.size() == (sei.numSpsIdsMinus1 + 1));
-
-  for (Int i = 0; i < sei.activeSeqParameterSetId.size(); i++)
-  {
-    WRITE_UVLC(sei.activeSeqParameterSetId[i], "active_seq_parameter_set_id");
-  }
-}
-
-Void SEIWriter::xWriteSEIDecodingUnitInfo(const SEIDecodingUnitInfo& sei, const TComSPS *sps)
-{
-  const TComVUI *vui = sps->getVuiParameters();
-  WRITE_UVLC(sei.m_decodingUnitIdx, "decoding_unit_idx");
-  if(vui->getHrdParameters()->getSubPicCpbParamsInPicTimingSEIFlag())
-  {
-    WRITE_CODE( sei.m_duSptCpbRemovalDelay, (vui->getHrdParameters()->getDuCpbRemovalDelayLengthMinus1() + 1), "du_spt_cpb_removal_delay_increment");
-  }
-  WRITE_FLAG( sei.m_dpbOutputDuDelayPresentFlag, "dpb_output_du_delay_present_flag");
-  if(sei.m_dpbOutputDuDelayPresentFlag)
-  {
-    WRITE_CODE(sei.m_picSptDpbOutputDuDelay, vui->getHrdParameters()->getDpbOutputDelayDuLengthMinus1() + 1, "pic_spt_dpb_output_du_delay");
-  }
-}
 
 Void SEIWriter::xWriteSEIBufferingPeriod(const SEIBufferingPeriod& sei, const TComSPS *sps)
@@ -400,4 +372,65 @@
   }
 }
+
+
+Void SEIWriter::xWriteSEIPanScanRect(const SEIPanScanRect &sei)
+{
+  WRITE_UVLC( sei.m_panScanRectId,         "pan_scan_rect_id" );
+  const UInt numRegions = (UInt) sei.m_panScanRectRegions.size();
+  if ( !sei.m_panScanRectCancelFlag && numRegions>0 )
+  {
+    WRITE_FLAG( sei.m_panScanRectCancelFlag, "pan_scan_rect_cancel_flag" );
+    WRITE_UVLC( numRegions - 1, "pan_scan_cnt_minus1" );
+    for(UInt region=0; region<numRegions; region++)
+    {
+      const SEIPanScanRect::PanScanRect &rect=sei.m_panScanRectRegions[region];
+      WRITE_SVLC( rect.leftOffset,   "pan_scan_rect_left_offset[i]"   );
+      WRITE_SVLC( rect.rightOffset,  "pan_scan_rect_rioht_offset[i]"  );
+      WRITE_SVLC( rect.topOffset,    "pan_scan_rect_top_offset[i]"    );
+      WRITE_SVLC( rect.bottomOffset, "pan_scan_rect_bottom_offset[i]" );
+    }
+    WRITE_FLAG( sei.m_panScanRectPersistenceFlag, "pan_scan_rect_persistence_flag" );
+  }
+}
+
+
+Void SEIWriter::xWriteSEIFillerPayload(const SEIFillerPayload &sei)
+{
+  for(UInt k=0; k<sei.m_numFillerFFBytes; k++)
+  {
+    WRITE_CODE( 0xff, 8, "ff_byte" );
+  }
+}
+
+
+Void SEIWriter::xWriteSEIUserDataRegistered(const SEIUserDataRegistered &sei)
+{
+  WRITE_CODE( (sei.m_ituCountryCode>255) ? 0xff : sei.m_ituCountryCode, 8, "itu_t_t35_country_code" );
+  if (sei.m_ituCountryCode>=255)
+  {
+    assert(sei.m_ituCountryCode < 255+256);
+    WRITE_CODE( sei.m_ituCountryCode-255, 8, "itu_t_t35_country_code_extension_byte" );
+  }
+  for(UInt i=0; i<sei.m_userData.size(); i++)
+  {
+    WRITE_CODE( sei.m_userData[i], 8, "itu_t_t35_payload_byte" );
+  }
+}
+
+
+Void SEIWriter::xWriteSEIUserDataUnregistered(const SEIUserDataUnregistered &sei)
+{
+  for (UInt i = 0; i < ISO_IEC_11578_LEN; i++)
+  {
+    WRITE_CODE(sei.m_uuid_iso_iec_11578[i], 8 , "sei.uuid_iso_iec_11578[i]");
+  }
+
+  for (std::size_t i = 0; i < sei.m_userData.size(); i++)
+  {
+    WRITE_CODE(sei.m_userData[i], 8 , "user_data");
+  }
+}
+
+
 Void SEIWriter::xWriteSEIRecoveryPoint(const SEIRecoveryPoint& sei)
 {
@@ -406,45 +439,105 @@
   WRITE_FLAG( sei.m_brokenLinkFlag,    "broken_link_flag"    );
 }
-Void SEIWriter::xWriteSEIFramePacking(const SEIFramePacking& sei)
-{
-  WRITE_UVLC( sei.m_arrangementId,                  "frame_packing_arrangement_id" );
-  WRITE_FLAG( sei.m_arrangementCancelFlag,          "frame_packing_arrangement_cancel_flag" );
-
-  if( sei.m_arrangementCancelFlag == 0 )
-  {
-    WRITE_CODE( sei.m_arrangementType, 7,           "frame_packing_arrangement_type" );
-
-    WRITE_FLAG( sei.m_quincunxSamplingFlag,         "quincunx_sampling_flag" );
-    WRITE_CODE( sei.m_contentInterpretationType, 6, "content_interpretation_type" );
-    WRITE_FLAG( sei.m_spatialFlippingFlag,          "spatial_flipping_flag" );
-    WRITE_FLAG( sei.m_frame0FlippedFlag,            "frame0_flipped_flag" );
-    WRITE_FLAG( sei.m_fieldViewsFlag,               "field_views_flag" );
-    WRITE_FLAG( sei.m_currentFrameIsFrame0Flag,     "current_frame_is_frame0_flag" );
-
-    WRITE_FLAG( sei.m_frame0SelfContainedFlag,      "frame0_self_contained_flag" );
-    WRITE_FLAG( sei.m_frame1SelfContainedFlag,      "frame1_self_contained_flag" );
-
-    if(sei.m_quincunxSamplingFlag == 0 && sei.m_arrangementType != 5)
-    {
-      WRITE_CODE( sei.m_frame0GridPositionX, 4,     "frame0_grid_position_x" );
-      WRITE_CODE( sei.m_frame0GridPositionY, 4,     "frame0_grid_position_y" );
-      WRITE_CODE( sei.m_frame1GridPositionX, 4,     "frame1_grid_position_x" );
-      WRITE_CODE( sei.m_frame1GridPositionY, 4,     "frame1_grid_position_y" );
-    }
-
-    WRITE_CODE( sei.m_arrangementReservedByte, 8,   "frame_packing_arrangement_reserved_byte" );
-    WRITE_FLAG( sei.m_arrangementPersistenceFlag,   "frame_packing_arrangement_persistence_flag" );
-  }
-
-  WRITE_FLAG( sei.m_upsampledAspectRatio,           "upsampled_aspect_ratio" );
-}
-
-Void SEIWriter::xWriteSEISegmentedRectFramePacking(const SEISegmentedRectFramePacking& sei)
-{
-  WRITE_FLAG( sei.m_arrangementCancelFlag,          "segmented_rect_frame_packing_arrangement_cancel_flag" );
-  if( sei.m_arrangementCancelFlag == 0 )
-  {
-    WRITE_CODE( sei.m_contentInterpretationType, 2, "segmented_rect_content_interpretation_type" );
-    WRITE_FLAG( sei.m_arrangementPersistenceFlag,   "segmented_rect_frame_packing_arrangement_persistence" );
+
+
+Void SEIWriter::xWriteSEISceneInfo(const SEISceneInfo &sei)
+  {
+  WRITE_FLAG( sei.m_bSceneInfoPresentFlag, "scene_info_present_flag" );
+  if (sei.m_bSceneInfoPresentFlag)
+  {
+    WRITE_FLAG( sei.m_bPrevSceneIdValidFlag, "prev_scene_id_valid_flag" );
+    WRITE_UVLC( sei.m_sceneId,               "scene_id" );
+    WRITE_UVLC( sei.m_sceneTransitionType,   "scene_transition_type" );
+    if (sei.m_sceneTransitionType > 3)
+    {
+      WRITE_UVLC( sei.m_secondSceneId,       "second_scene_id" );
+    }
+  }
+}
+
+
+Void SEIWriter::xWriteSEIPictureSnapshot(const SEIPictureSnapshot &sei)
+{
+  WRITE_UVLC( sei.m_snapshotId, "snapshot_id" );
+}
+
+Void SEIWriter::xWriteSEIProgressiveRefinementSegmentStart(const SEIProgressiveRefinementSegmentStart &sei)
+
+    {
+  WRITE_UVLC( sei.m_progressiveRefinementId, "progressive_refinement_id" );
+  WRITE_UVLC( sei.m_picOrderCntDelta,        "pic_order_cnt_delta"       );
+    }
+
+
+Void SEIWriter::xWriteSEIProgressiveRefinementSegmentEnd(const SEIProgressiveRefinementSegmentEnd &sei)
+{
+  WRITE_UVLC( sei.m_progressiveRefinementId, "progressive_refinement_id" );
+  }
+
+
+Void SEIWriter::xWriteSEIFilmGrainCharacteristics(const SEIFilmGrainCharacteristics &sei)
+{
+  WRITE_FLAG( sei.m_filmGrainCharacteristicsCancelFlag, "film_grain_characteristics_cancel_flag" );
+  if (!sei.m_filmGrainCharacteristicsCancelFlag)
+  {
+    WRITE_CODE( sei.m_filmGrainModelId, 2,                  "film_grain_model_id" );
+    WRITE_FLAG( sei.m_separateColourDescriptionPresentFlag, "separate_colour_description_present_flag" );
+    if (sei.m_separateColourDescriptionPresentFlag)
+    {
+      WRITE_CODE( sei.m_filmGrainBitDepthLumaMinus8,      3, "film_grain_bit_depth_luma_minus8" );
+      WRITE_CODE( sei.m_filmGrainBitDepthChromaMinus8,    3, "film_grain_bit_depth_chroma_minus8" );
+      WRITE_FLAG( sei.m_filmGrainFullRangeFlag,              "film_grain_full_range_flag" );
+      WRITE_CODE( sei.m_filmGrainColourPrimaries,         8, "film_grain_colour_primaries" );
+      WRITE_CODE( sei.m_filmGrainTransferCharacteristics, 8, "film_grain_transfer_characteristics" );
+      WRITE_CODE( sei.m_filmGrainMatrixCoeffs,            8, "film_grain_matrix_coeffs" );
+    }
+    WRITE_CODE( sei.m_blendingModeId,  2, "blending_mode_id" );
+    WRITE_CODE( sei.m_log2ScaleFactor, 4, "log2_scale_factor" );
+    for(Int c=0; c<3; c++)
+    {
+      const SEIFilmGrainCharacteristics::CompModel &cm=sei.m_compModel[c];
+      const UInt numIntensityIntervals = (UInt) cm.intensityValues.size();
+      const UInt numModelValues        = cm.numModelValues;
+      WRITE_FLAG( sei.m_compModel[c].bPresentFlag && numIntensityIntervals>0 && numModelValues>0, "comp_model_present_flag[c]" );
+    }
+    for(Int c=0; c<3; c++)
+    {
+      const SEIFilmGrainCharacteristics::CompModel &cm=sei.m_compModel[c];
+      const UInt numIntensityIntervals = (UInt) cm.intensityValues.size();
+      const UInt numModelValues        = cm.numModelValues;
+      if (cm.bPresentFlag && numIntensityIntervals>0 && numModelValues>0)
+      {
+        assert(numIntensityIntervals<=256);
+        assert(numModelValues<=256);
+        WRITE_CODE( numIntensityIntervals-1, 8, "num_intensity_intervals_minus1[c]");
+        WRITE_CODE( numModelValues-1,        8, "num_model_values_minus1[c]");
+        for(UInt interval=0; interval<numIntensityIntervals; interval++)
+        {
+          const SEIFilmGrainCharacteristics::CompModelIntensityValues &cmiv=cm.intensityValues[interval];
+          WRITE_CODE( cmiv.intensityIntervalLowerBound, 8, "intensity_interval_lower_bound[c][i]" );
+          WRITE_CODE( cmiv.intensityIntervalUpperBound, 8, "intensity_interval_upper_bound[c][i]" );
+          assert(cmiv.compModelValue.size() == numModelValues);
+          for(UInt j=0; j<cm.numModelValues; j++)
+          {
+            WRITE_SVLC(cmiv.compModelValue[j], "comp_model_value[c][i]" );
+          }
+        }
+      }
+    } // for c
+    WRITE_FLAG( sei.m_filmGrainCharacteristicsPersistenceFlag, "film_grain_characteristics_persistence_flag" );
+  } // cancel flag
+}
+
+Void SEIWriter::xWriteSEIPostFilterHint(const SEIPostFilterHint& sei, const TComSPS *sps)
+{
+  WRITE_UVLC( sei.m_filterHintSizeY,   "filter_hint_size_y" );
+  WRITE_UVLC( sei.m_filterHintSizeX,   "filter_hint_size_x" );
+  WRITE_CODE( sei.m_filterHintType, 2, "filter_hint_type"   );
+  assert( (sps->getChromaFormatIdc() == CHROMA_400) == sei.m_bIsMonochrome );
+  const UInt numChromaChannels = sei.m_bIsMonochrome ? 1:3;
+  assert( sei.m_filterHintValues.size() == numChromaChannels*sei.m_filterHintSizeX*sei.m_filterHintSizeY );
+  for(std::size_t i=0; i<sei.m_filterHintValues.size(); i++)
+  {
+    WRITE_SVLC( sei.m_filterHintValues[i], "filter_hint_value[][][]" );
   }
 }
@@ -525,4 +618,40 @@
 }
 
+
+Void SEIWriter::xWriteSEIFramePacking(const SEIFramePacking& sei)
+{
+  WRITE_UVLC( sei.m_arrangementId,                  "frame_packing_arrangement_id" );
+  WRITE_FLAG( sei.m_arrangementCancelFlag,          "frame_packing_arrangement_cancel_flag" );
+
+  if( sei.m_arrangementCancelFlag == 0 )
+  {
+    WRITE_CODE( sei.m_arrangementType, 7,           "frame_packing_arrangement_type" );
+
+    WRITE_FLAG( sei.m_quincunxSamplingFlag,         "quincunx_sampling_flag" );
+    WRITE_CODE( sei.m_contentInterpretationType, 6, "content_interpretation_type" );
+    WRITE_FLAG( sei.m_spatialFlippingFlag,          "spatial_flipping_flag" );
+    WRITE_FLAG( sei.m_frame0FlippedFlag,            "frame0_flipped_flag" );
+    WRITE_FLAG( sei.m_fieldViewsFlag,               "field_views_flag" );
+    WRITE_FLAG( sei.m_currentFrameIsFrame0Flag,     "current_frame_is_frame0_flag" );
+
+    WRITE_FLAG( sei.m_frame0SelfContainedFlag,      "frame0_self_contained_flag" );
+    WRITE_FLAG( sei.m_frame1SelfContainedFlag,      "frame1_self_contained_flag" );
+
+    if(sei.m_quincunxSamplingFlag == 0 && sei.m_arrangementType != 5)
+    {
+      WRITE_CODE( sei.m_frame0GridPositionX, 4,     "frame0_grid_position_x" );
+      WRITE_CODE( sei.m_frame0GridPositionY, 4,     "frame0_grid_position_y" );
+      WRITE_CODE( sei.m_frame1GridPositionX, 4,     "frame1_grid_position_x" );
+      WRITE_CODE( sei.m_frame1GridPositionY, 4,     "frame1_grid_position_y" );
+    }
+
+    WRITE_CODE( sei.m_arrangementReservedByte, 8,   "frame_packing_arrangement_reserved_byte" );
+    WRITE_FLAG( sei.m_arrangementPersistenceFlag,   "frame_packing_arrangement_persistence_flag" );
+  }
+
+  WRITE_FLAG( sei.m_upsampledAspectRatio,           "upsampled_aspect_ratio" );
+}
+
+
 Void SEIWriter::xWriteSEIDisplayOrientation(const SEIDisplayOrientation &sei)
 {
@@ -537,18 +666,13 @@
 }
 
-Void SEIWriter::xWriteSEITemporalLevel0Index(const SEITemporalLevel0Index &sei)
-{
-  WRITE_CODE( sei.tl0Idx, 8 , "tl0_idx" );
-  WRITE_CODE( sei.rapIdx, 8 , "rap_idx" );
-}
-
-Void SEIWriter::xWriteSEIGradualDecodingRefreshInfo(const SEIGradualDecodingRefreshInfo &sei)
-{
-  WRITE_FLAG( sei.m_gdrForegroundFlag, "gdr_foreground_flag");
-}
-
-Void SEIWriter::xWriteSEINoDisplay(const SEINoDisplay& /*sei*/)
-{
-}
+
+Void SEIWriter::xWriteSEIGreenMetadataInfo(const SEIGreenMetadataInfo& sei)
+{
+  WRITE_CODE(sei.m_greenMetadataType, 8, "green_metadata_type");
+
+  WRITE_CODE(sei.m_xsdMetricType, 8, "xsd_metric_type");
+  WRITE_CODE(sei.m_xsdMetricValue, 16, "xsd_metric_value");
+}
+
 
 Void SEIWriter::xWriteSEISOPDescription(const SEISOPDescription& sei)
@@ -571,4 +695,66 @@
 }
 
+
+Void SEIWriter::xWriteSEIActiveParameterSets(const SEIActiveParameterSets& sei)
+{
+  WRITE_CODE(sei.activeVPSId,     4,         "active_video_parameter_set_id");
+  WRITE_FLAG(sei.m_selfContainedCvsFlag,     "self_contained_cvs_flag");
+  WRITE_FLAG(sei.m_noParameterSetUpdateFlag, "no_parameter_set_update_flag");
+  WRITE_UVLC(sei.numSpsIdsMinus1,            "num_sps_ids_minus1");
+
+  assert (sei.activeSeqParameterSetId.size() == (sei.numSpsIdsMinus1 + 1));
+
+  for (Int i = 0; i < sei.activeSeqParameterSetId.size(); i++)
+  {
+    WRITE_UVLC(sei.activeSeqParameterSetId[i], "active_seq_parameter_set_id");
+  }
+}
+
+
+Void SEIWriter::xWriteSEIDecodingUnitInfo(const SEIDecodingUnitInfo& sei, const TComSPS *sps)
+{
+  const TComVUI *vui = sps->getVuiParameters();
+  WRITE_UVLC(sei.m_decodingUnitIdx, "decoding_unit_idx");
+  if(vui->getHrdParameters()->getSubPicCpbParamsInPicTimingSEIFlag())
+  {
+    WRITE_CODE( sei.m_duSptCpbRemovalDelay, (vui->getHrdParameters()->getDuCpbRemovalDelayLengthMinus1() + 1), "du_spt_cpb_removal_delay_increment");
+  }
+  WRITE_FLAG( sei.m_dpbOutputDuDelayPresentFlag, "dpb_output_du_delay_present_flag");
+  if(sei.m_dpbOutputDuDelayPresentFlag)
+  {
+    WRITE_CODE(sei.m_picSptDpbOutputDuDelay, vui->getHrdParameters()->getDpbOutputDelayDuLengthMinus1() + 1, "pic_spt_dpb_output_du_delay");
+  }
+}
+
+
+Void SEIWriter::xWriteSEITemporalLevel0Index(const SEITemporalLevel0Index &sei)
+{
+  WRITE_CODE( sei.tl0Idx, 8 , "tl0_idx" );
+  WRITE_CODE( sei.rapIdx, 8 , "rap_idx" );
+}
+
+
+Void SEIWriter::xWriteSEIDecodedPictureHash(const SEIDecodedPictureHash& sei)
+{
+  const TChar *traceString="\0";
+  switch (sei.method)
+  {
+    case HASHTYPE_MD5: traceString="picture_md5"; break;
+    case HASHTYPE_CRC: traceString="picture_crc"; break;
+    case HASHTYPE_CHECKSUM: traceString="picture_checksum"; break;
+    default: assert(false); break;
+  }
+
+  if (traceString != 0) //use of this variable is needed to avoid a compiler error with G++ 4.6.1
+  {
+    WRITE_CODE(sei.method, 8, "hash_type");
+    for(UInt i=0; i<UInt(sei.m_pictureHash.hash.size()); i++)
+    {
+      WRITE_CODE(sei.m_pictureHash.hash[i], 8, traceString);
+    }
+  }
+}
+
+
 Void SEIWriter::xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, const TComSPS *sps)
 {
@@ -609,60 +795,15 @@
 }
 
-Void SEIWriter::xWriteSEITempMotionConstrainedTileSets(const SEITempMotionConstrainedTileSets& sei)
-{
-  //UInt code;
-  WRITE_FLAG((sei.m_mc_all_tiles_exact_sample_value_match_flag ? 1 : 0), "mc_all_tiles_exact_sample_value_match_flag");
-  WRITE_FLAG((sei.m_each_tile_one_tile_set_flag                ? 1 : 0), "each_tile_one_tile_set_flag"               );
-
-  if(!sei.m_each_tile_one_tile_set_flag)
-  {
-    WRITE_FLAG((sei.m_limited_tile_set_display_flag ? 1 : 0), "limited_tile_set_display_flag");
-    WRITE_UVLC((sei.getNumberOfTileSets() - 1),               "num_sets_in_message_minus1"   );
-
-    if(sei.getNumberOfTileSets() > 0)
-    {
-      for(Int i = 0; i < sei.getNumberOfTileSets(); i++)
-      {
-        WRITE_UVLC(sei.tileSetData(i).m_mcts_id, "mcts_id");
-
-        if(sei.m_limited_tile_set_display_flag)
-        {
-          WRITE_FLAG((sei.tileSetData(i).m_display_tile_set_flag ? 1 : 0), "display_tile_set_flag");
-        }
-
-        WRITE_UVLC((sei.tileSetData(i).getNumberOfTileRects() - 1), "num_tile_rects_in_set_minus1");
-
-        for(Int j = 0; j < sei.tileSetData(i).getNumberOfTileRects(); j++)
-        {
-          WRITE_UVLC(sei.tileSetData(i).topLeftTileIndex    (j), "top_left_tile_index");
-          WRITE_UVLC(sei.tileSetData(i).bottomRightTileIndex(j), "bottom_right_tile_index");
-        }
-
-        if(!sei.m_mc_all_tiles_exact_sample_value_match_flag)
-        {
-          WRITE_FLAG((sei.tileSetData(i).m_exact_sample_value_match_flag ? 1 : 0), "exact_sample_value_match_flag");
-        }
-
-        WRITE_FLAG((sei.tileSetData(i).m_mcts_tier_level_idc_present_flag ? 1 : 0), "mcts_tier_level_idc_present_flag");
-
-        if(sei.tileSetData(i).m_mcts_tier_level_idc_present_flag)
-        {
-          WRITE_FLAG((sei.tileSetData(i).m_mcts_tier_flag ? 1 : 0), "mcts_tier_flag");
-          WRITE_CODE( sei.tileSetData(i).m_mcts_level_idc, 8,       "mcts_level_idc");
-        }
-      }
-    }
-  }
-  else
-  {
-    WRITE_FLAG((sei.m_max_mcs_tier_level_idc_present_flag ? 1 : 0), "max_mcs_tier_level_idc_present_flag");
-
-    if(sei.m_max_mcs_tier_level_idc_present_flag)
-    {
-      WRITE_FLAG((sei.m_max_mcts_tier_flag ? 1 : 0), "max_mcts_tier_flag");
-      WRITE_CODE( sei.m_max_mcts_level_idc, 8,       "max_mcts_level_idc");
-    }
-  }
-}
+Void SEIWriter::xWriteSEIRegionRefreshInfo(const SEIRegionRefreshInfo &sei)
+        {
+  WRITE_FLAG( sei.m_gdrForegroundFlag, "gdr_foreground_flag");
+        }
+
+
+Void SEIWriter::xWriteSEINoDisplay(const SEINoDisplay& /*sei*/)
+        {
+  // intentionally empty
+    }
+
 
 Void SEIWriter::xWriteSEITimeCode(const SEITimeCode& sei)
@@ -724,4 +865,93 @@
 }
 
+
+Void SEIWriter::xWriteSEIMasteringDisplayColourVolume(const SEIMasteringDisplayColourVolume& sei)
+{
+  WRITE_CODE( sei.values.primaries[0][0],  16,  "display_primaries_x[0]" );
+  WRITE_CODE( sei.values.primaries[0][1],  16,  "display_primaries_y[0]" );
+
+  WRITE_CODE( sei.values.primaries[1][0],  16,  "display_primaries_x[1]" );
+  WRITE_CODE( sei.values.primaries[1][1],  16,  "display_primaries_y[1]" );
+
+  WRITE_CODE( sei.values.primaries[2][0],  16,  "display_primaries_x[2]" );
+  WRITE_CODE( sei.values.primaries[2][1],  16,  "display_primaries_y[2]" );
+
+  WRITE_CODE( sei.values.whitePoint[0],    16,  "white_point_x" );
+  WRITE_CODE( sei.values.whitePoint[1],    16,  "white_point_y" );
+
+  WRITE_CODE( sei.values.maxLuminance,     32,  "max_display_mastering_luminance" );
+  WRITE_CODE( sei.values.minLuminance,     32,  "min_display_mastering_luminance" );
+}
+
+
+Void SEIWriter::xWriteSEISegmentedRectFramePacking(const SEISegmentedRectFramePacking& sei)
+{
+  WRITE_FLAG( sei.m_arrangementCancelFlag,          "segmented_rect_frame_packing_arrangement_cancel_flag" );
+  if( sei.m_arrangementCancelFlag == 0 )
+  {
+    WRITE_CODE( sei.m_contentInterpretationType, 2, "segmented_rect_content_interpretation_type" );
+    WRITE_FLAG( sei.m_arrangementPersistenceFlag,   "segmented_rect_frame_packing_arrangement_persistence" );
+  }
+}
+
+
+Void SEIWriter::xWriteSEITempMotionConstrainedTileSets(const SEITempMotionConstrainedTileSets& sei)
+{
+  //UInt code;
+  WRITE_FLAG((sei.m_mc_all_tiles_exact_sample_value_match_flag ? 1 : 0), "mc_all_tiles_exact_sample_value_match_flag");
+  WRITE_FLAG((sei.m_each_tile_one_tile_set_flag                ? 1 : 0), "each_tile_one_tile_set_flag"               );
+
+  if(!sei.m_each_tile_one_tile_set_flag)
+  {
+    WRITE_FLAG((sei.m_limited_tile_set_display_flag ? 1 : 0), "limited_tile_set_display_flag");
+    WRITE_UVLC((sei.getNumberOfTileSets() - 1),               "num_sets_in_message_minus1"   );
+
+    if(sei.getNumberOfTileSets() > 0)
+    {
+      for(Int i = 0; i < sei.getNumberOfTileSets(); i++)
+      {
+        WRITE_UVLC(sei.tileSetData(i).m_mcts_id, "mcts_id");
+
+        if(sei.m_limited_tile_set_display_flag)
+        {
+          WRITE_FLAG((sei.tileSetData(i).m_display_tile_set_flag ? 1 : 0), "display_tile_set_flag");
+        }
+
+        WRITE_UVLC((sei.tileSetData(i).getNumberOfTileRects() - 1), "num_tile_rects_in_set_minus1");
+
+        for(Int j = 0; j < sei.tileSetData(i).getNumberOfTileRects(); j++)
+        {
+          WRITE_UVLC(sei.tileSetData(i).topLeftTileIndex    (j), "top_left_tile_index");
+          WRITE_UVLC(sei.tileSetData(i).bottomRightTileIndex(j), "bottom_right_tile_index");
+        }
+
+        if(!sei.m_mc_all_tiles_exact_sample_value_match_flag)
+        {
+          WRITE_FLAG((sei.tileSetData(i).m_exact_sample_value_match_flag ? 1 : 0), "exact_sample_value_match_flag");
+        }
+
+        WRITE_FLAG((sei.tileSetData(i).m_mcts_tier_level_idc_present_flag ? 1 : 0), "mcts_tier_level_idc_present_flag");
+
+        if(sei.tileSetData(i).m_mcts_tier_level_idc_present_flag)
+        {
+          WRITE_FLAG((sei.tileSetData(i).m_mcts_tier_flag ? 1 : 0), "mcts_tier_flag");
+          WRITE_CODE( sei.tileSetData(i).m_mcts_level_idc, 8,       "mcts_level_idc");
+        }
+      }
+    }
+  }
+  else
+  {
+    WRITE_FLAG((sei.m_max_mcs_tier_level_idc_present_flag ? 1 : 0), "max_mcs_tier_level_idc_present_flag");
+
+    if(sei.m_max_mcs_tier_level_idc_present_flag)
+    {
+      WRITE_FLAG((sei.m_max_mcts_tier_flag ? 1 : 0), "max_mcts_tier_flag");
+      WRITE_CODE( sei.m_max_mcts_level_idc, 8,       "max_mcts_level_idc");
+    }
+  }
+}
+
+
 Void SEIWriter::xWriteSEIChromaResamplingFilterHint(const SEIChromaResamplingFilterHint &sei)
 {
@@ -846,20 +1076,44 @@
 }
 
-Void SEIWriter::xWriteSEIMasteringDisplayColourVolume(const SEIMasteringDisplayColourVolume& sei)
-{
-  WRITE_CODE( sei.values.primaries[0][0],  16,  "display_primaries_x[0]" );
-  WRITE_CODE( sei.values.primaries[0][1],  16,  "display_primaries_y[0]" );
-
-  WRITE_CODE( sei.values.primaries[1][0],  16,  "display_primaries_x[1]" );
-  WRITE_CODE( sei.values.primaries[1][1],  16,  "display_primaries_y[1]" );
-
-  WRITE_CODE( sei.values.primaries[2][0],  16,  "display_primaries_x[2]" );
-  WRITE_CODE( sei.values.primaries[2][1],  16,  "display_primaries_y[2]" );
-
-  WRITE_CODE( sei.values.whitePoint[0],    16,  "white_point_x" );
-  WRITE_CODE( sei.values.whitePoint[1],    16,  "white_point_y" );
-    
-  WRITE_CODE( sei.values.maxLuminance,     32,  "max_display_mastering_luminance" );
-  WRITE_CODE( sei.values.minLuminance,     32,  "min_display_mastering_luminance" );
+Void SEIWriter::xWriteSEIDeinterlaceFieldIdentification(const SEIDeinterlaceFieldIdentification& sei)
+{
+  WRITE_FLAG( sei.m_deinterlacedPictureSourceParityFlag, "deinterlaced_picture_source_parity_flag" );
+}
+
+
+Void SEIWriter::xWriteSEIContentLightLevelInfo(const SEIContentLightLevelInfo& sei)
+{
+  WRITE_CODE( sei.m_maxContentLightLevel,    16, "max_content_light_level"     );
+  WRITE_CODE( sei.m_maxPicAverageLightLevel, 16, "max_pic_average_light_level" );
+}
+
+
+Void SEIWriter::xWriteSEIDependentRAPIndication(const SEIDependentRAPIndication& /*sei*/)
+{
+  // intentionally empty
+}
+
+
+Void SEIWriter::xWriteSEICodedRegionCompletion(const SEICodedRegionCompletion& sei)
+{
+  WRITE_UVLC( sei.m_nextSegmentAddress, "next_segment_address" );
+  if (sei.m_nextSegmentAddress)
+  {
+    WRITE_FLAG( sei.m_independentSliceSegmentFlag, "independent_slice_segment_flag" );
+  }
+}
+
+
+Void SEIWriter::xWriteSEIAlternativeTransferCharacteristics(const SEIAlternativeTransferCharacteristics& sei)
+{
+  WRITE_CODE(sei.m_preferredTransferCharacteristics, 8, "preferred_transfer_characteristics");
+}
+
+
+Void SEIWriter::xWriteSEIAmbientViewingEnvironment(const SEIAmbientViewingEnvironment& sei)
+{
+  WRITE_CODE(sei.m_ambientIlluminance, 32, "ambient_illuminance" );
+  WRITE_CODE(sei.m_ambientLightX,      16, "ambient_light_x" );
+  WRITE_CODE(sei.m_ambientLightY,      16, "ambient_light_y" );
 }
 
@@ -876,11 +1130,4 @@
   }
 }
-
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
-Void SEIWriter::xWriteSEIAlternativeTransferCharacteristics(const SEIAlternativeTransferCharacteristics& sei)
-{
-  WRITE_CODE(sei.m_preferredTransferCharacteristics, 8, "preferred_transfer_characteristics");
-}
-#endif
 
 #if NH_MV
Index: /trunk/source/Lib/TLibEncoder/SEIwrite.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/SEIwrite.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/SEIwrite.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -53,30 +53,42 @@
 
 protected:
-  Void xWriteSEIuserDataUnregistered(const SEIuserDataUnregistered &sei);
-  Void xWriteSEIActiveParameterSets(const SEIActiveParameterSets& sei);
-  Void xWriteSEIDecodingUnitInfo(const SEIDecodingUnitInfo& sei, const TComSPS *sps);
-  Void xWriteSEIDecodedPictureHash(const SEIDecodedPictureHash& sei);
-  Void xWriteSEIBufferingPeriod(const SEIBufferingPeriod& sei, const TComSPS *sps);
-  Void xWriteSEIPictureTiming(const SEIPictureTiming& sei, const TComSPS *sps);
-  Void xWriteSEIRecoveryPoint(const SEIRecoveryPoint& sei);
-  Void xWriteSEIFramePacking(const SEIFramePacking& sei);
-  Void xWriteSEISegmentedRectFramePacking(const SEISegmentedRectFramePacking& sei);
-  Void xWriteSEIDisplayOrientation(const SEIDisplayOrientation &sei);
-  Void xWriteSEITemporalLevel0Index(const SEITemporalLevel0Index &sei);
-  Void xWriteSEIGradualDecodingRefreshInfo(const SEIGradualDecodingRefreshInfo &sei);
-  Void xWriteSEINoDisplay(const SEINoDisplay &sei);
-  Void xWriteSEIToneMappingInfo(const SEIToneMappingInfo& sei);
-  Void xWriteSEISOPDescription(const SEISOPDescription& sei);
-  Void xWriteSEIScalableNesting(TComBitIf& bs, const SEIScalableNesting& sei, const TComSPS *sps);
-  Void xWriteSEITempMotionConstrainedTileSets(const SEITempMotionConstrainedTileSets& sei);
-  Void xWriteSEITimeCode(const SEITimeCode& sei);
-  Void xWriteSEIChromaResamplingFilterHint(const SEIChromaResamplingFilterHint& sei);
-  Void xWriteSEIKneeFunctionInfo(const SEIKneeFunctionInfo &sei);
-  Void xWriteSEIColourRemappingInfo(const SEIColourRemappingInfo& sei);
-  Void xWriteSEIMasteringDisplayColourVolume( const SEIMasteringDisplayColourVolume& sei);
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
+  Void xWriteSEIBufferingPeriod                   (const SEIBufferingPeriod& sei, const TComSPS *sps);
+  Void xWriteSEIPictureTiming                     (const SEIPictureTiming& sei, const TComSPS *sps);
+  Void xWriteSEIPanScanRect                       (const SEIPanScanRect& sei);
+  Void xWriteSEIFillerPayload                     (const SEIFillerPayload& sei);
+  Void xWriteSEIUserDataRegistered                (const SEIUserDataRegistered& sei);
+  Void xWriteSEIUserDataUnregistered              (const SEIUserDataUnregistered &sei);
+  Void xWriteSEIRecoveryPoint                     (const SEIRecoveryPoint& sei);
+  Void xWriteSEISceneInfo                         (const SEISceneInfo& sei);
+  Void xWriteSEIPictureSnapshot                   (const SEIPictureSnapshot& sei);
+  Void xWriteSEIProgressiveRefinementSegmentStart (const SEIProgressiveRefinementSegmentStart& sei);
+  Void xWriteSEIProgressiveRefinementSegmentEnd   (const SEIProgressiveRefinementSegmentEnd& sei);
+  Void xWriteSEIFilmGrainCharacteristics          (const SEIFilmGrainCharacteristics& sei);
+  Void xWriteSEIPostFilterHint                    (const SEIPostFilterHint& sei, const TComSPS *sps);
+  Void xWriteSEIToneMappingInfo                   (const SEIToneMappingInfo& sei);
+  Void xWriteSEIFramePacking                      (const SEIFramePacking& sei);
+  Void xWriteSEIDisplayOrientation                (const SEIDisplayOrientation &sei);
+  Void xWriteSEIGreenMetadataInfo                 (const SEIGreenMetadataInfo &sei);
+  Void xWriteSEISOPDescription                    (const SEISOPDescription& sei);
+  Void xWriteSEIActiveParameterSets               (const SEIActiveParameterSets& sei);
+  Void xWriteSEIDecodingUnitInfo                  (const SEIDecodingUnitInfo& sei, const TComSPS *sps);
+  Void xWriteSEITemporalLevel0Index               (const SEITemporalLevel0Index &sei);
+  Void xWriteSEIDecodedPictureHash                (const SEIDecodedPictureHash& sei);
+  Void xWriteSEIScalableNesting                   (TComBitIf& bs, const SEIScalableNesting& sei, const TComSPS *sps);
+  Void xWriteSEIRegionRefreshInfo                 (const SEIRegionRefreshInfo &sei);
+  Void xWriteSEINoDisplay                         (const SEINoDisplay &sei);
+  Void xWriteSEITimeCode                          (const SEITimeCode& sei);
+  Void xWriteSEIMasteringDisplayColourVolume      (const SEIMasteringDisplayColourVolume& sei);
+  Void xWriteSEISegmentedRectFramePacking         (const SEISegmentedRectFramePacking& sei);
+  Void xWriteSEITempMotionConstrainedTileSets     (const SEITempMotionConstrainedTileSets& sei);
+  Void xWriteSEIChromaResamplingFilterHint        (const SEIChromaResamplingFilterHint& sei);
+  Void xWriteSEIKneeFunctionInfo                  (const SEIKneeFunctionInfo &sei);
+  Void xWriteSEIColourRemappingInfo               (const SEIColourRemappingInfo& sei);
+  Void xWriteSEIDeinterlaceFieldIdentification    (const SEIDeinterlaceFieldIdentification& sei);
+  Void xWriteSEIContentLightLevelInfo             (const SEIContentLightLevelInfo& sei);
+  Void xWriteSEIDependentRAPIndication            (const SEIDependentRAPIndication& sei);
+  Void xWriteSEICodedRegionCompletion             (const SEICodedRegionCompletion& sei);
   Void xWriteSEIAlternativeTransferCharacteristics(const SEIAlternativeTransferCharacteristics& sei);
-#endif
-
+  Void xWriteSEIAmbientViewingEnvironment         (const SEIAmbientViewingEnvironment& sei);
 #if NH_MV
   Void xWriteSEILayersNotPresent              ( const SEILayersNotPresent& sei);
Index: /trunk/source/Lib/TLibEncoder/SyntaxElementWriter.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/SyntaxElementWriter.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibEncoder/SyntaxElementWriter.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/SyntaxElementWriter.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibEncoder/TEncAnalyze.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncAnalyze.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -49,4 +49,7 @@
 #include "TLibCommon/TComChromaFormat.h"
 #include "math.h"
+#if EXTENSION_360_VIDEO
+#include "TAppEncHelper360/TExt360EncAnalyze.h"
+#endif
 
 //! \ingroup TLibEncoder
@@ -66,4 +69,11 @@
   Double    m_dFrmRate; //--CFG_KDY
   Double    m_MSEyuvframe[MAX_NUM_COMPONENT]; // sum of MSEs
+#if JVET_F0064_MSSSIM
+  Double    m_MSSSIM[MAX_NUM_COMPONENT];
+#endif
+
+#if EXTENSION_360_VIDEO
+  TExt360EncAnalyze m_ext360;
+#endif
 
 public:
@@ -71,6 +81,9 @@
   TEncAnalyze() { clear(); }
 
-  Void  addResult( Double psnr[MAX_NUM_COMPONENT], Double bits, const Double MSEyuvframe[MAX_NUM_COMPONENT])
-  {
+#if JVET_F0064_MSSSIM
+  Void  addResult( Double psnr[MAX_NUM_COMPONENT], Double bits, const Double MSEyuvframe[MAX_NUM_COMPONENT], const Double MSSSIM[MAX_NUM_COMPONENT] )  {
+#else
+  Void  addResult( Double psnr[MAX_NUM_COMPONENT], Double bits, const Double MSEyuvframe[MAX_NUM_COMPONENT] )  {
+#endif
     m_dAddBits  += bits;
     for(UInt i=0; i<MAX_NUM_COMPONENT; i++)
@@ -78,4 +91,7 @@
       m_dPSNRSum[i] += psnr[i];
       m_MSEyuvframe[i] += MSEyuvframe[i];
+#if JVET_F0064_MSSSIM
+      m_MSSSIM[i] += MSSSIM[i];
+#endif
     }
 
@@ -84,7 +100,13 @@
 
   Double  getPsnr(ComponentID compID) const { return  m_dPSNRSum[compID];  }
+#if JVET_F0064_MSSSIM
+  Double  getMsssim(ComponentID compID) const { return  m_MSSSIM[compID];  }
+#endif
   Double  getBits()                   const { return  m_dAddBits;   }
   Void    setBits(Double numBits)     { m_dAddBits=numBits; }
   UInt    getNumPic()                 const { return  m_uiNumPic;   }
+#if EXTENSION_360_VIDEO
+  TExt360EncAnalyze& getExt360Info() { return m_ext360; }
+#endif
 
   Void    setFrmRate  (Double dFrameRate) { m_dFrmRate = dFrameRate; } //--CFG_KDY
@@ -96,6 +118,12 @@
       m_dPSNRSum[i] = 0;
       m_MSEyuvframe[i] = 0;
+#if JVET_F0064_MSSSIM
+      m_MSSSIM[i] = 0;
+#endif
     }
     m_uiNumPic = 0;
+#if EXTENSION_360_VIDEO
+    m_ext360.clear();
+#endif
   }
 
@@ -137,5 +165,9 @@
 
 
+#if JVET_F0064_MSSSIM
+  Void    printOut ( TChar cDelim, const ChromaFormat chFmt, const Bool printMSEBasedSNR, const Bool printSequenceMSE, const Bool printMSSSIM, const BitDepths &bitDepths )
+#else
   Void    printOut ( TChar cDelim, const ChromaFormat chFmt, const Bool printMSEBasedSNR, const Bool printSequenceMSE, const BitDepths &bitDepths )
+#endif
   {
     Double dFps     =   m_dFrmRate; //--CFG_KDY
@@ -171,4 +203,10 @@
           printf( "         \tTotal Frames |   "   "Bitrate     "  "Y-PSNR" );
 
+#if JVET_F0064_MSSSIM
+          if (printMSSSIM)
+          {
+            printf( "    Y-MS-SSIM");
+          }
+#endif
           if (printSequenceMSE)
           {
@@ -186,4 +224,11 @@
                  getPsnr(COMPONENT_Y) / (Double)getNumPic() );
 
+#if JVET_F0064_MSSSIM
+          if (printMSSSIM)
+          {
+            printf("    %8.6lf", getMsssim(COMPONENT_Y) / (Double)getNumPic());
+          }
+#endif
+
           if (printSequenceMSE)
           {
@@ -203,4 +248,11 @@
         {
           printf( "\tTotal Frames |   "   "Bitrate     "  "Y-PSNR" );
+
+#if JVET_F0064_MSSSIM
+          if (printMSSSIM)
+          {
+            printf( "Y-MS-SSIM");
+          }
+#endif
 
           if (printSequenceMSE)
@@ -219,4 +271,10 @@
                  getPsnr(COMPONENT_Y) / (Double)getNumPic() );
 
+#if JVET_F0064_MSSSIM
+          if (printMSSSIM)
+          {
+            printf("%8.6lf", getMsssim(COMPONENT_Y) / (Double)getNumPic());
+          }
+#endif
           if (printSequenceMSE)
           {
@@ -242,4 +300,10 @@
             printf( "         \tTotal Frames |   "   "Bitrate     "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR    "  "YUV-PSNR " );
 
+#if JVET_F0064_MSSSIM
+            if (printMSSSIM)
+            {
+              printf("   Y-MS-SSIM    " "U-MS-SSIM    " "V-MS-SSIM ");
+            }
+#endif
             if (printSequenceMSE)
             {
@@ -260,4 +324,13 @@
                    PSNRyuv );
 
+#if JVET_F0064_MSSSIM
+            if (printMSSSIM)
+            {
+              printf("    %8.6lf     " "%8.6lf     " "%8.6lf ",
+                     getMsssim(COMPONENT_Y) / (Double)getNumPic(),
+                     getMsssim(COMPONENT_Cb) / (Double)getNumPic(),
+                     getMsssim(COMPONENT_Cr) / (Double)getNumPic());
+            }
+#endif
             if (printSequenceMSE)
             {
@@ -285,4 +358,15 @@
             printf( "\tTotal Frames |   "   "Bitrate     "  "Y-PSNR    "  "U-PSNR    "  "V-PSNR    "  "YUV-PSNR " );
             
+#if JVET_F0064_MSSSIM
+            if (printMSSSIM)
+            {
+              printf("   Y-MS-SSIM    " "U-MS-SSIM    " "V-MS-SSIM ");
+            }
+#endif
+
+#if EXTENSION_360_VIDEO
+            m_ext360.printHeader();
+#endif
+
             if (printSequenceMSE)
             {
@@ -303,4 +387,18 @@
                    PSNRyuv );
 
+#if JVET_F0064_MSSSIM
+            if (printMSSSIM)
+            {
+              printf("    %8.6lf     " "%8.6lf     " "%8.6lf ",
+                     getMsssim(COMPONENT_Y) / (Double)getNumPic(),
+                     getMsssim(COMPONENT_Cb) / (Double)getNumPic(),
+                     getMsssim(COMPONENT_Cr) / (Double)getNumPic());
+            }
+#endif
+
+#if EXTENSION_360_VIDEO
+            m_ext360.printPSNRs(getNumPic());
+#endif
+
             if (printSequenceMSE)
             {
Index: /trunk/source/Lib/TLibEncoder/TEncBinCoder.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncBinCoder.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncBinCoderCABAC.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncBinCoderCABACCounter.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibEncoder/TEncCavlc.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncCavlc.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -184,5 +184,5 @@
   WRITE_FLAG( pcPPS->getOutputFlagPresentFlag() ? 1 : 0,     "output_flag_present_flag" );
   WRITE_CODE( pcPPS->getNumExtraSliceHeaderBits(), 3,        "num_extra_slice_header_bits");
-  WRITE_FLAG( pcPPS->getSignHideFlag(), "sign_data_hiding_flag" );
+  WRITE_FLAG( pcPPS->getSignDataHidingEnabledFlag(),         "sign_data_hiding_enabled_flag" );
   WRITE_FLAG( pcPPS->getCabacInitPresentFlag() ? 1 : 0,   "cabac_init_present_flag" );
 #if H_3D_PPS_FIX_DEPTH
@@ -216,5 +216,5 @@
   WRITE_FLAG( pcPPS->getUseWP() ? 1 : 0,  "weighted_pred_flag" );   // Use of Weighting Prediction (P_SLICE)
   WRITE_FLAG( pcPPS->getWPBiPred() ? 1 : 0, "weighted_bipred_flag" );  // Use of Weighting Bi-Prediction (B_SLICE)
-  WRITE_FLAG( pcPPS->getTransquantBypassEnableFlag() ? 1 : 0, "transquant_bypass_enable_flag" );
+  WRITE_FLAG( pcPPS->getTransquantBypassEnabledFlag()  ? 1 : 0, "transquant_bypass_enabled_flag" );
   WRITE_FLAG( pcPPS->getTilesEnabledFlag()             ? 1 : 0, "tiles_enabled_flag" );
   WRITE_FLAG( pcPPS->getEntropyCodingSyncEnabledFlag() ? 1 : 0, "entropy_coding_sync_enabled_flag" );
@@ -235,9 +235,7 @@
       }
     }
-    if(pcPPS->getNumTileColumnsMinus1() !=0 || pcPPS->getNumTileRowsMinus1() !=0)
-    {
+    assert ((pcPPS->getNumTileColumnsMinus1() + pcPPS->getNumTileRowsMinus1()) != 0);
       WRITE_FLAG( pcPPS->getLoopFilterAcrossTilesEnabledFlag()?1 : 0,          "loop_filter_across_tiles_enabled_flag");
     }
-  }
   WRITE_FLAG( pcPPS->getLoopFilterAcrossSlicesEnabledFlag()?1 : 0,        "pps_loop_filter_across_slices_enabled_flag");
   WRITE_FLAG( pcPPS->getDeblockingFilterControlPresentFlag()?1 : 0,       "deblocking_filter_control_present_flag");
@@ -245,6 +243,6 @@
   {
     WRITE_FLAG( pcPPS->getDeblockingFilterOverrideEnabledFlag() ? 1 : 0,  "deblocking_filter_override_enabled_flag" );
-    WRITE_FLAG( pcPPS->getPicDisableDeblockingFilterFlag() ? 1 : 0,       "pps_disable_deblocking_filter_flag" );
-    if(!pcPPS->getPicDisableDeblockingFilterFlag())
+    WRITE_FLAG( pcPPS->getPPSDeblockingFilterDisabledFlag() ? 1 : 0,      "pps_deblocking_filter_disabled_flag" );
+    if(!pcPPS->getPPSDeblockingFilterDisabledFlag())
     {
       WRITE_SVLC( pcPPS->getDeblockingFilterBetaOffsetDiv2(),             "pps_beta_offset_div2" );
@@ -392,5 +390,4 @@
 Void  TEncCavlc::codePps3dExtension        ( const TComPPS* pcPPS )
 {
-#if NH_3D_DLT
   WRITE_FLAG( pcPPS->getDLT()->getDltPresentFlag() ? 1 : 0, "dlts_present_flag" );
 
@@ -510,5 +507,4 @@
     }
   }
-#endif
 }
 #endif
@@ -849,7 +845,7 @@
     }
   }
-  WRITE_FLAG( pcSPS->getTMVPFlagsPresent()  ? 1 : 0,           "sps_temporal_mvp_enable_flag" );
-
-  WRITE_FLAG( pcSPS->getUseStrongIntraSmoothing(),             "sps_strong_intra_smoothing_enable_flag" );
+  WRITE_FLAG( pcSPS->getSPSTemporalMVPEnabledFlag()  ? 1 : 0,  "sps_temporal_mvp_enabled_flag" );
+
+  WRITE_FLAG( pcSPS->getUseStrongIntraSmoothing(),             "strong_intra_smoothing_enable_flag" );
 
   WRITE_FLAG( pcSPS->getVuiParametersPresentFlag(),             "vui_parameters_present_flag" );
@@ -1428,9 +1424,5 @@
     for( Int j = 0; j  <=  vps->getMaxSubLayersInLayerSetMinus1( currLsIdx ); j++ )
     {  
-#if NH_3D_FIX_TICKET_114
       if( j > 0  &&  dpbSize->getSubLayerFlagInfoPresentFlag( i )  )  
-#else
-      if( j > 0  &&  dpbSize->getSubLayerDpbInfoPresentFlag( i, j )  )  
-#endif
       {
         WRITE_FLAG( dpbSize->getSubLayerDpbInfoPresentFlag( i, j ) ? 1 : 0 , "sub_layer_dpb_info_present_flag" );
@@ -1982,5 +1974,5 @@
         }
       }
-      if (pcSlice->getSPS()->getTMVPFlagsPresent())
+      if (pcSlice->getSPS()->getSPSTemporalMVPEnabledFlag())
       {
 #if NH_MV
@@ -2166,5 +2158,5 @@
       xCodePredWeightTable( pcSlice );
     }
-#if NH_3D_IC
+#if NH_3D
     else if( pcSlice->getViewIndex() && ( pcSlice->getSliceType() == P_SLICE || pcSlice->getSliceType() == B_SLICE )
       && !pcSlice->getIsDepth() && vps->getNumRefListLayers( layerId ) > 0 
@@ -2178,6 +2170,4 @@
       }
     }
-#endif
-#if NH_3D_IV_MERGE
     assert(pcSlice->getMaxNumMergeCand()<=MRG_MAX_NUM_CANDS_MEM);
 #else
@@ -2186,5 +2176,5 @@
     if (!pcSlice->isIntra())
     {
-#if NH_3D_IV_MERGE
+#if NH_3D
       WRITE_UVLC( ( ( pcSlice->getMpiFlag( ) || pcSlice->getIvMvPredFlag( ) || pcSlice->getViewSynthesisPredFlag( ) ) ? MRG_MAX_NUM_CANDS_MEM : MRG_MAX_NUM_CANDS ) - pcSlice->getMaxNumMergeCand(), "five_minus_max_num_merge_cand");
 #else
@@ -2220,5 +2210,5 @@
       if (pcSlice->getDeblockingFilterOverrideFlag())
       {
-        WRITE_FLAG(pcSlice->getDeblockingFilterDisable(), "slice_disable_deblocking_filter_flag");
+        WRITE_FLAG(pcSlice->getDeblockingFilterDisable(), "slice_deblocking_filter_disabled_flag");
         if(!pcSlice->getDeblockingFilterDisable())
         {
@@ -2428,13 +2418,13 @@
   if( ptl->getV2ConstraintsPresentFlag() ) 
   {
-    WRITE_FLAG( ptl->getMax12bitConstraintFlag( ) ? 1 : 0 , "max_12bit_constraint_flag" );
-    WRITE_FLAG( ptl->getMax10bitConstraintFlag( ) ? 1 : 0 , "max_10bit_constraint_flag" );
-    WRITE_FLAG( ptl->getMax8bitConstraintFlag( ) ? 1 : 0 , "max_8bit_constraint_flag" );
-    WRITE_FLAG( ptl->getMax422chromaConstraintFlag( ) ? 1 : 0 , "max_422chroma_constraint_flag" );
-    WRITE_FLAG( ptl->getMax420chromaConstraintFlag( ) ? 1 : 0 , "max_420chroma_constraint_flag" );
-    WRITE_FLAG( ptl->getMaxMonochromeConstraintFlag( ) ? 1 : 0 , "max_monochrome_constraint_flag" );
-    WRITE_FLAG( ptl->getIntraConstraintFlag( ) ? 1 : 0 , "intra_constraint_flag" );
-    WRITE_FLAG( ptl->getOnePictureOnlyConstraintFlag( ) ? 1 : 0 , "one_picture_only_constraint_flag" );
-    WRITE_FLAG( ptl->getLowerBitRateConstraintFlag( ) ? 1 : 0 , "lower_bit_rate_constraint_flag" );
+    WRITE_FLAG( ptl->getMax12bitConstraintFlag       ( ) ? 1 : 0 , "max_12bit_constraint_flag" );
+    WRITE_FLAG( ptl->getMax10bitConstraintFlag       ( ) ? 1 : 0 , "max_10bit_constraint_flag" );
+    WRITE_FLAG( ptl->getMax8bitConstraintFlag        ( ) ? 1 : 0 , "max_8bit_constraint_flag" );
+    WRITE_FLAG( ptl->getMax422chromaConstraintFlag   ( ) ? 1 : 0 , "max_422chroma_constraint_flag" );
+    WRITE_FLAG( ptl->getMax420chromaConstraintFlag   ( ) ? 1 : 0 , "max_420chroma_constraint_flag" );
+    WRITE_FLAG( ptl->getMaxMonochromeConstraintFlag  ( ) ? 1 : 0 , "max_monochrome_constraint_flag" );
+    WRITE_FLAG( ptl->getIntraConstraintFlag          ( ) ? 1 : 0 , "intra_constraint_flag" );
+    WRITE_FLAG( ptl->getOnePictureOnlyConstraintFlag ( ) ? 1 : 0 , "one_picture_only_constraint_flag" );
+    WRITE_FLAG( ptl->getLowerBitRateConstraintFlag   ( ) ? 1 : 0 , "lower_bit_rate_constraint_flag" );
     WRITE_CODE( 0, 16, "XXX_reserved_zero_34bits[0..15]");
     WRITE_CODE( 0, 16, "XXX_reserved_zero_34bits[16..31]");
@@ -2473,4 +2463,12 @@
     WRITE_CODE(0 ,  2, PTL_TRACE_TEXT("reserved_zero_34bits[32..33]"    ));
   }
+  else if (ptl->getProfileIdc() == Profile::MAIN10)
+  {
+    WRITE_CODE(0x00   ,  7, PTL_TRACE_TEXT("reserved_zero_7bits"     ));
+    WRITE_FLAG(ptl->getOnePictureOnlyConstraintFlag(), PTL_TRACE_TEXT("one_picture_only_constraint_flag"));
+    WRITE_CODE(0x0000 , 16, PTL_TRACE_TEXT("reserved_zero_35bits[0..15]"     ));
+    WRITE_CODE(0x0000 , 16, PTL_TRACE_TEXT("reserved_zero_35bits[16..31]"    ));
+    WRITE_CODE(0x0    ,  3, PTL_TRACE_TEXT("reserved_zero_35bits[32..34]"    ));
+  }
   else
   {
@@ -2558,12 +2556,10 @@
 }
 
-#if NH_3D_ARP
+#if NH_3D
 Void TEncCavlc::codeARPW( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
   assert(0);
 }
-#endif
-
-#if NH_3D_IC
+
 Void TEncCavlc::codeICFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
@@ -2586,5 +2582,5 @@
   assert(0);
 }
-#if NH_3D_DIS
+#if NH_3D
 Void TEncCavlc::codeDIS( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
@@ -2689,5 +2685,5 @@
 }
 
-Void TEncCavlc::estBit( estBitsSbacStruct* /*pcEstBitsCabac*/, Int /*width*/, Int /*height*/, ChannelType /*chType*/ )
+Void TEncCavlc::estBit( estBitsSbacStruct* /*pcEstBitsCabac*/, Int /*width*/, Int /*height*/, ChannelType /*chType*/, COEFF_SCAN_TYPE /*scanType*/ )
 {
   // printf("error : no VLC mode support in this version\n");
@@ -2867,12 +2863,10 @@
    assert(0);
  }
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
+#if NH_3D
 Void TEncCavlc::codeSDCFlag ( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
   assert(0);
 }
-#endif
-    
-#if NH_3D_DBBP
+
 Void TEncCavlc::codeDBBPFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
Index: /trunk/source/Lib/TLibEncoder/TEncCavlc.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncCavlc.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncCavlc.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -130,23 +130,14 @@
   Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
-#if NH_3D_DIS
+#if NH_3D
   Void codeDIS           ( TComDataCU* pcCU, UInt uiAbsPartIdx );
 #endif
   Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx );
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
-  Void  codeDeltaDC      ( TComDataCU* /*pcCU*/, UInt /*absPartIdx*/ ) { assert(0); };
-#endif
-#if NH_3D_ARP
+#if NH_3D
+  Void codeDeltaDC      ( TComDataCU* /*pcCU*/, UInt /*absPartIdx*/ ) { assert(0); };
   Void codeARPW          ( TComDataCU* pcCU, UInt uiAbsPartIdx );
-#endif
-#if NH_3D_IC
   Void codeICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx );
-#endif
-
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   Void codeSDCFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
-#endif
-#if NH_3D_DBBP
   Void codeDBBPFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
 #endif
@@ -179,5 +170,5 @@
   Void codeTransformSkipFlags ( TComTU &rTu, ComponentID component );
 
-  Void estBit            ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType );
+  Void estBit            ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType, COEFF_SCAN_TYPE scanType );
 
   Void xCodePredWeightTable          ( TComSlice* pcSlice );
Index: /trunk/source/Lib/TLibEncoder/TEncCfg.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncCfg.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncCfg.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -62,8 +62,10 @@
   Int m_POC;
   Int m_QPOffset;
-#if W0038_CQP_ADJ
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+  Double m_QPOffsetModelOffset;
+  Double m_QPOffsetModelScale;
+#endif
   Int m_CbQPoffset;
   Int m_CrQPoffset;
-#endif
   Double m_QPFactor;
   Int m_tcOffsetDiv2;
@@ -93,8 +95,10 @@
   : m_POC(-1)
   , m_QPOffset(0)
-#if W0038_CQP_ADJ
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+  , m_QPOffsetModelOffset(0)
+  , m_QPOffsetModelScale(0)
+#endif
   , m_CbQPoffset(0)
   , m_CrQPoffset(0)
-#endif
   , m_QPFactor(0)
   , m_tcOffsetDiv2(0)
@@ -155,4 +159,7 @@
   Bool      m_printFrameMSE;
   Bool      m_printSequenceMSE;
+#if JVET_F0064_MSSSIM
+  Bool      m_printMSSSIM;
+#endif
   Bool      m_cabacZeroWordPaddingEnabled;
 
@@ -174,4 +181,8 @@
   UInt      m_uiIntraPeriod;                    // TODO: make this an Int - it can be -1!
   UInt      m_uiDecodingRefreshType;            ///< the type of decoding refresh employed for the random access.
+#if JCTVC_Y0038_PARAMS
+  Bool      m_bReWriteParamSetsFlag;
+#endif
+
   Int       m_iGOPSize;
 #if NH_MV
@@ -186,4 +197,8 @@
   Int       m_iQP;                              //  if (AdaptiveQP == OFF)
 
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+  Int       m_intraQPOffset;                    ///< QP offset for intra slice (integer)
+  Int       m_lambdaFromQPEnable;               ///< enable lambda derivation from QP
+#endif
   Int       m_aiPad[2];
 
@@ -211,9 +226,5 @@
   Int       m_loopFilterBetaOffsetDiv2;
   Int       m_loopFilterTcOffsetDiv2;
-#if W0038_DB_OPT
   Int       m_deblockingFilterMetric;
-#else
-  Bool      m_DeblockingFilterMetric;
-#endif
   Bool      m_bUseSAO;
   Bool      m_bTestSAODisableAtPictureLevel;
@@ -222,7 +233,5 @@
   Int       m_maxNumOffsetsPerPic;
   Bool      m_saoCtuBoundary;
-#if OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP
   Bool      m_saoResetEncoderStateAfterIRAP;
-#endif
 
   //====== Motion search ========
@@ -247,8 +256,7 @@
   Int       m_chromaCbQpOffset;                 //  Chroma Cb QP Offset (0:default)
   Int       m_chromaCrQpOffset;                 //  Chroma Cr Qp Offset (0:default)
-#if W0038_CQP_ADJ
+  WCGChromaQPControl m_wcgChromaQpControl;                    ///< Wide-colour-gamut chroma QP control.
   UInt      m_sliceChromaQpOffsetPeriodicity;                 ///< Used in conjunction with Slice Cb/Cr QpOffsetIntraOrPeriodic. Use 0 (default) to disable periodic nature.
   Int       m_sliceChromaQpOffsetIntraOrPeriodic[2/*Cb,Cr*/]; ///< Chroma Cb QP Offset at slice level for I slice or for periodic inter slices as defined by SliceChromaQPOffsetPeriodicity. Replaces offset in the GOP table.
-#endif
 
   ChromaFormat m_chromaFormatIDC;
@@ -268,7 +276,5 @@
   Bool      m_useRDOQ;
   Bool      m_useRDOQTS;
-#if T0196_SELECTIVE_RDOQ
   Bool      m_useSelectiveRDOQ;
-#endif
   UInt      m_rdPenalty;
   FastInterSearchMode m_fastInterSearchMode;
@@ -288,4 +294,5 @@
   Bool      m_cabacBypassAlignmentEnabledFlag;
   Bool      m_rdpcmEnabledFlag[NUMBER_OF_RDPCM_SIGNALLING_MODES];
+  LumaLevelToDeltaQPMapping m_lumaLevelToDeltaQPMapping; ///< mapping from luma level to delta QP.
   Int*      m_aidQP;
   UInt      m_uiDeltaQpRD;
@@ -368,4 +375,7 @@
   Bool      m_scalableNestingSEIEnabled;
   Bool      m_tmctsSEIEnabled;
+#if MCTS_ENC_CHECK
+  Bool      m_tmctsSEITileConstraint;
+#endif
   Bool      m_timeCodeSEIEnabled;
   Int       m_timeCodeSEINumTs;
@@ -384,11 +394,14 @@
   std::string m_colourRemapSEIFileRoot;          ///< SEI Colour Remapping File (initialized from external file)
   TComSEIMasteringDisplay m_masteringDisplay;
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
   Bool      m_alternativeTransferCharacteristicsSEIEnabled;
   UChar     m_preferredTransferCharacteristics;
-#endif
+  Bool      m_greenMetadataInfoSEIEnabled;
+  UChar     m_greenMetadataType;
+  UChar     m_xsdMetricType;
 
 #if NH_MV
   SEIMessages* m_seiMessages; 
+  Bool         m_sendParameterSets;
+  Int          m_parameterSetId; 
 #endif
   //====== Weighted Prediction ========
@@ -401,5 +414,5 @@
   std::string m_scalingListFileName;              ///< quantization matrix file name
   Int       m_TMVPModeId;
-  Bool      m_signHideFlag;
+  Bool      m_SignDataHidingEnabledFlag;
   Bool      m_RCEnableRateControl;
   Int       m_RCTargetBitrate;
@@ -409,10 +422,7 @@
   Int       m_RCInitialQP;
   Bool      m_RCForceIntraQP;
-#if U0132_TARGET_BITS_SATURATION
   Bool      m_RCCpbSaturationEnabled;                   
   UInt      m_RCCpbSize;
   Double    m_RCInitialCpbFullness;
-#endif
-
 #if KWU_RC_MADPRED_E0227
   UInt       m_depthMADPred;
@@ -421,16 +431,17 @@
   Bool      m_bViewWiseRateCtrl;
 #endif
-  Bool      m_TransquantBypassEnableFlag;                     ///< transquant_bypass_enable_flag setting in PPS.
-  Bool      m_CUTransquantBypassFlagForce;                    ///< if transquant_bypass_enable_flag, then, if true, all CU transquant bypass flags will be set to true.
+  Bool      m_TransquantBypassEnabledFlag;                     ///< transquant_bypass_enabled_flag setting in PPS.
+  Bool      m_CUTransquantBypassFlagForce;                    ///< if transquant_bypass_enabled_flag, then, if true, all CU transquant bypass flags will be set to true.
 
   CostMode  m_costMode;                                       ///< The cost function to use, primarily when considering lossless coding.
 #if NH_MV
   TComVPS*  m_cVPS;                                           ///< pointer to VPS, same for all layers
+  TComSPS   m_activeSps;                                      /// Keep local copy; since syntax elements can be changed by layer specific inference. 
+  TComPPS   m_activePps;                                      /// Keep local copy; since syntax elements can be changed by layer specific inference. 
 #else
-
   TComVPS   m_cVPS;
 #endif
 
-#if NH_3D_DLT
+#if NH_3D
   TComDLT   m_cDLT;
 #endif
@@ -519,9 +530,5 @@
   Bool      m_useSDC;
   Bool      m_useDLT;
-#endif
-#if NH_3D_QTL
   Bool      m_bUseQTL;
-#endif
-#if NH_3D
   Int       m_profileIdc;
 #endif
@@ -578,18 +585,32 @@
   Void      setPrintSequenceMSE             (Bool value)     { m_printSequenceMSE = value;          }
 
+#if JVET_F0064_MSSSIM
+  Bool      getPrintMSSSIM                  ()         const { return m_printMSSSIM;               }
+  Void      setPrintMSSSIM                  (Bool value)     { m_printMSSSIM = value;              }
+#endif
+
   Bool      getCabacZeroWordPaddingEnabled()           const { return m_cabacZeroWordPaddingEnabled;  }
   Void      setCabacZeroWordPaddingEnabled(Bool value)       { m_cabacZeroWordPaddingEnabled = value; }
 #if NH_MV
   Void      setLayerId                       ( Int layerId )      { m_layerId = layerId; }
-  Int       getLayerId                       ()                   { return m_layerId;    }
-  Int       getLayerIdInVps                  ()                   { return m_layerIdInVps; }
+  Int       getLayerId                       ()         const     { return m_layerId;    }
+  Int       getLayerIdInVps                  ()         const     { return m_layerIdInVps; }
   Void      setLayerIdInVps                  ( Int layerIdInVps)  { m_layerIdInVps = layerIdInVps; }
   Void      setViewId                        ( Int viewId  )      { m_viewId  = viewId;  }
-  Int       getViewId                        ()                   { return m_viewId;    }
+  Int       getViewId                        ()         const     { return m_viewId;    }
   Void      setViewIndex                     ( Int viewIndex  )   { m_viewIndex  = viewIndex;  }
-  Int       getViewIndex                     ()                   { return m_viewIndex;    }
+  Int       getViewIndex                     ()         const     { return m_viewIndex;    }
+#if NH_MV
+  Void      setSendParameterSets            ( Bool value )       { m_sendParameterSets = value; }; 
+  Bool      getSendParameterSets            (  )                 { return m_sendParameterSets; }; 
+
+  Void      setParameterSetId               ( Int  value )       { m_parameterSetId = value; }; 
+  Int       getParameterSetId               (  )                 { return m_parameterSetId;  }; 
+
+
+#endif
 #if NH_3D_VSO || NH_3D
-  Void      setIsDepth                       ( Bool isDepth )   { m_isDepth = isDepth; }
-  Bool      getIsDepth                       ()                 { return m_isDepth; }
+  Void      setIsDepth                       ( Bool isDepth )    { m_isDepth = isDepth; }
+  Bool      getIsDepth                       ()         const    { return m_isDepth; }
   Void      setIsAuxDepth                    ( Bool isAuxDepth ) { m_isAuxDepth = isAuxDepth; }
   Bool      getIsAuxDepth                       ()               { return m_isAuxDepth; }
@@ -601,12 +622,16 @@
   Void      setIntraPeriod                  ( Int   i )      { m_uiIntraPeriod = (UInt)i; }
   Void      setDecodingRefreshType          ( Int   i )      { m_uiDecodingRefreshType = (UInt)i; }
+#if JCTVC_Y0038_PARAMS
+  Void      setReWriteParamSetsFlag         ( Bool  b )      { m_bReWriteParamSetsFlag = b; }
+#endif
+
   Void      setGOPSize                      ( Int   i )      { m_iGOPSize = i; }
 #if NH_MV
   Void      setGopList                      ( GOPEntry*  GOPList ) {  for ( Int i = 0; i < MAX_GOP+1; i++ ) m_GOPList[i] = GOPList[i]; }
 #else
-  Void      setGopList                      ( GOPEntry*  GOPList ) {  for ( Int i = 0; i < MAX_GOP; i++ ) m_GOPList[i] = GOPList[i]; }
+  Void      setGopList                      ( const GOPEntry GOPList[MAX_GOP] ) {  for ( Int i = 0; i < MAX_GOP; i++ ) m_GOPList[i] = GOPList[i]; }
 #endif
   Void      setExtraRPSs                    ( Int   i )      { m_extraRPSs = i; }
-  GOPEntry  getGOPEntry                     ( Int   i )      { return m_GOPList[i]; }
+  const GOPEntry &getGOPEntry               ( Int   i ) const { return m_GOPList[i]; }
   Void      setEncodedFlag                  ( Int  i, Bool value )  { m_GOPList[i].m_isEncoded = value; }
   Void      setMaxDecPicBuffering           ( UInt u, UInt tlayer ) { m_maxDecPicBuffering[tlayer] = u;    }
@@ -615,4 +640,8 @@
   Void      setQP                           ( Int   i )      { m_iQP = i; }
 
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+  Void      setIntraQPOffset                ( Int   i )         { m_intraQPOffset = i; }
+  Void      setLambdaFromQPEnable           ( Bool  b )         { m_lambdaFromQPEnable = b; }
+#endif
   Void      setPad                          ( Int*  iPad                   )      { for ( Int i = 0; i < 2; i++ ) m_aiPad[i] = iPad[i]; }
 
@@ -626,5 +655,5 @@
   Void      setMaxTotalCUDepth              ( UInt  u )      { m_maxTotalCUDepth = u; }
   Void      setLog2DiffMaxMinCodingBlockSize( UInt  u )      { m_log2DiffMaxMinCodingBlockSize = u; }
-#if NH_3D_IC
+#if NH_3D
   Void       setUseIC                       ( Bool bVal )    { m_bUseIC = bVal; }
   Bool       getUseIC                       ()               { return m_bUseIC; }
@@ -646,9 +675,6 @@
   Void      setLoopFilterBetaOffset         ( Int   i )      { m_loopFilterBetaOffsetDiv2  = i; }
   Void      setLoopFilterTcOffset           ( Int   i )      { m_loopFilterTcOffsetDiv2    = i; }
-#if W0038_DB_OPT
   Void      setDeblockingFilterMetric       ( Int   i )      { m_deblockingFilterMetric = i; }
-#else
-  Void      setDeblockingFilterMetric       ( Bool  b )      { m_DeblockingFilterMetric = b; }
-#endif
+
   //====== Motion search ========
   Void      setDisableIntraPUsInInterSlices ( Bool  b )      { m_bDisableIntraPUsInInterSlices = b; }
@@ -675,12 +701,15 @@
   Void      setChromaCbQpOffset             ( Int   i )      { m_chromaCbQpOffset = i; }
   Void      setChromaCrQpOffset             ( Int   i )      { m_chromaCrQpOffset = i; }
-#if W0038_CQP_ADJ
+  Void      setWCGChromaQpControl           ( const WCGChromaQPControl &ctrl )     { m_wcgChromaQpControl = ctrl; }
+  const WCGChromaQPControl &getWCGChromaQPControl () const { return m_wcgChromaQpControl; }
   Void      setSliceChromaOffsetQpIntraOrPeriodic( UInt periodicity, Int sliceChromaQpOffsetIntraOrPeriodic[2]) { m_sliceChromaQpOffsetPeriodicity = periodicity; memcpy(m_sliceChromaQpOffsetIntraOrPeriodic, sliceChromaQpOffsetIntraOrPeriodic, sizeof(m_sliceChromaQpOffsetIntraOrPeriodic)); }
   Int       getSliceChromaOffsetQpIntraOrPeriodic( Bool bIsCr) const                                            { return m_sliceChromaQpOffsetIntraOrPeriodic[bIsCr?1:0]; }
   UInt      getSliceChromaOffsetQpPeriodicity() const                                                           { return m_sliceChromaQpOffsetPeriodicity; }
-#endif
 
   Void      setChromaFormatIdc              ( ChromaFormat cf ) { m_chromaFormatIDC = cf; }
   ChromaFormat  getChromaFormatIdc          ( )              { return m_chromaFormatIDC; }
+
+  Void      setLumaLevelToDeltaQPControls( const LumaLevelToDeltaQPMapping &lumaLevelToDeltaQPMapping ) { m_lumaLevelToDeltaQPMapping=lumaLevelToDeltaQPMapping; }
+  const LumaLevelToDeltaQPMapping& getLumaLevelToDeltaQPMapping() const { return m_lumaLevelToDeltaQPMapping; }
 
 #if ADAPTIVE_QP_SELECTION
@@ -717,9 +746,24 @@
   UInt      getIntraPeriod                  ()      { return  m_uiIntraPeriod; }
   UInt      getDecodingRefreshType          ()      { return  m_uiDecodingRefreshType; }
-  Int       getGOPSize                      ()      { return  m_iGOPSize; }
+#if JCTVC_Y0038_PARAMS
+  Bool      getReWriteParamSetsFlag         ()      { return m_bReWriteParamSetsFlag; }
+#endif
+  #if NH_MV
+Int       getGOPSize                      ()    const  { return  m_iGOPSize; }
+#else
+Int       getGOPSize                      ()      { return  m_iGOPSize; }
+#endif
   Int       getMaxDecPicBuffering           (UInt tlayer) { return m_maxDecPicBuffering[tlayer]; }
   Int       getNumReorderPics               (UInt tlayer) { return m_numReorderPics[tlayer]; }
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+  Int       getIntraQPOffset                () const    { return  m_intraQPOffset; }
+  Int       getLambdaFromQPEnable           () const    { return  m_lambdaFromQPEnable; }
+protected:
+  Int       getBaseQP                       () const { return  m_iQP; } // public should use getQPForPicture.
+public:
+  Int       getQPForPicture                 (const UInt gopIndex, const TComSlice *pSlice) const; // Function actually defined in TEncTop.cpp
+#else
   Int       getQP                           ()      { return  m_iQP; }
-
+#endif
   Int       getPad                          ( Int i )      { assert (i < 2 );                      return  m_aiPad[i]; }
 
@@ -734,12 +778,16 @@
 
   //==== Loop/Deblock Filter ========
+#if NH_MV
+  Bool      getLoopFilterDisable            ()      const { return  m_bLoopFilterDisable;       }
+  Bool      getLoopFilterOffsetInPPS        ()      const { return m_loopFilterOffsetInPPS; }
+  Int       getLoopFilterBetaOffset         ()      const { return m_loopFilterBetaOffsetDiv2; }
+  Int       getLoopFilterTcOffset           ()      const { return m_loopFilterTcOffsetDiv2; }
+  Int       getDeblockingFilterMetric       ()      const { return m_deblockingFilterMetric; }
+#else
   Bool      getLoopFilterDisable            ()      { return  m_bLoopFilterDisable;       }
   Bool      getLoopFilterOffsetInPPS        ()      { return m_loopFilterOffsetInPPS; }
   Int       getLoopFilterBetaOffset         ()      { return m_loopFilterBetaOffsetDiv2; }
   Int       getLoopFilterTcOffset           ()      { return m_loopFilterTcOffsetDiv2; }
-#if W0038_DB_OPT
   Int       getDeblockingFilterMetric       ()      { return m_deblockingFilterMetric; }
-#else
-  Bool      getDeblockingFilterMetric       ()      { return m_DeblockingFilterMetric; }
 #endif
 
@@ -759,8 +807,8 @@
 
   //==== Quality control ========
-  Int       getMaxDeltaQP                   ()      { return  m_iMaxDeltaQP; }
-  Int       getMaxCuDQPDepth                ()      { return  m_iMaxCuDQPDepth; }
-  Bool      getUseAdaptiveQP                ()      { return  m_bUseAdaptiveQP; }
-  Int       getQPAdaptationRange            ()      { return  m_iQPAdaptationRange; }
+  Int       getMaxDeltaQP                   () const { return  m_iMaxDeltaQP; }
+  Int       getMaxCuDQPDepth                () const { return  m_iMaxCuDQPDepth; }
+  Bool      getUseAdaptiveQP                () const { return  m_bUseAdaptiveQP; }
+  Int       getQPAdaptationRange            () const { return  m_iQPAdaptationRange; }
 
   //==== Tool list ========
@@ -770,7 +818,5 @@
   Void      setUseRDOQ                      ( Bool  b )     { m_useRDOQ    = b; }
   Void      setUseRDOQTS                    ( Bool  b )     { m_useRDOQTS  = b; }
-#if T0196_SELECTIVE_RDOQ
   Void      setUseSelectiveRDOQ             ( Bool b )      { m_useSelectiveRDOQ = b; }
-#endif
   Void      setRDpenalty                    ( UInt  u )     { m_rdPenalty  = u; }
   Void      setFastInterSearchMode          ( FastInterSearchMode m ) { m_fastInterSearchMode = m; }
@@ -797,7 +843,5 @@
   Bool      getUseRDOQ                      ()      { return m_useRDOQ;    }
   Bool      getUseRDOQTS                    ()      { return m_useRDOQTS;  }
-#if T0196_SELECTIVE_RDOQ
   Bool      getUseSelectiveRDOQ             ()      { return m_useSelectiveRDOQ; }
-#endif
   Int       getRDpenalty                    ()      { return m_rdPenalty;  }
   FastInterSearchMode getFastInterSearchMode() const{ return m_fastInterSearchMode;  }
@@ -841,5 +885,5 @@
   Void setIntraSmoothingDisabledFlag               (Bool bValue) { m_intraSmoothingDisabledFlag=bValue; }
 
-  Int*      getdQPs                         ()       { return m_aidQP;       }
+  const Int* getdQPs                        () const { return m_aidQP;       }
   UInt      getDeltaQpRD                    () const { return m_uiDeltaQpRD; }
   Bool      getFastDeltaQp                  () const { return m_bFastDeltaQP; }
@@ -871,8 +915,6 @@
   Void  setSaoCtuBoundary              (Bool val)                    { m_saoCtuBoundary = val; }
   Bool  getSaoCtuBoundary              ()                            { return m_saoCtuBoundary; }
-#if OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP
   Void  setSaoResetEncoderStateAfterIRAP(Bool b)                     { m_saoResetEncoderStateAfterIRAP = b; }
   Bool  getSaoResetEncoderStateAfterIRAP() const                     { return m_saoResetEncoderStateAfterIRAP; }
-#endif
   Void  setLFCrossTileBoundaryFlag               ( Bool   val  )     { m_loopFilterAcrossTilesEnabledFlag = val; }
   Bool  getLFCrossTileBoundaryFlag               ()                  { return m_loopFilterAcrossTilesEnabledFlag;   }
@@ -986,4 +1028,8 @@
   Void  setTMCTSSEIEnabled(Bool b)                                   { m_tmctsSEIEnabled = b; }
   Bool  getTMCTSSEIEnabled()                                         { return m_tmctsSEIEnabled; }
+#if MCTS_ENC_CHECK
+  Void  setTMCTSSEITileConstraint(Bool b)                            { m_tmctsSEITileConstraint = b; }
+  Bool  getTMCTSSEITileConstraint()                                  { return m_tmctsSEITileConstraint; }
+#endif
   Void  setTimeCodeSEIEnabled(Bool b)                                { m_timeCodeSEIEnabled = b; }
   Bool  getTimeCodeSEIEnabled()                                      { return m_timeCodeSEIEnabled; }
@@ -1019,10 +1065,15 @@
 
   Void  setMasteringDisplaySEI(const TComSEIMasteringDisplay &src)   { m_masteringDisplay = src; }
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
   Void  setSEIAlternativeTransferCharacteristicsSEIEnable( Bool b)   { m_alternativeTransferCharacteristicsSEIEnabled = b;    }
   Bool  getSEIAlternativeTransferCharacteristicsSEIEnable( ) const   { return m_alternativeTransferCharacteristicsSEIEnabled; }
   Void  setSEIPreferredTransferCharacteristics(UChar v)              { m_preferredTransferCharacteristics = v;    }
   UChar getSEIPreferredTransferCharacteristics() const               { return m_preferredTransferCharacteristics; }
-#endif
+  Void  setSEIGreenMetadataInfoSEIEnable( Bool b)                    { m_greenMetadataInfoSEIEnabled = b;    }
+  Bool  getSEIGreenMetadataInfoSEIEnable( ) const                    { return m_greenMetadataInfoSEIEnabled; }
+  Void  setSEIGreenMetadataType(UChar v)                             { m_greenMetadataType = v;    }
+  UChar getSEIGreenMetadataType() const                              { return m_greenMetadataType; }
+  Void  setSEIXSDMetricType(UChar v)                                 { m_xsdMetricType = v;    }
+  UChar getSEIXSDMetricType() const                                  { return m_xsdMetricType; }
+
   const TComSEIMasteringDisplay &getMasteringDisplaySEI() const      { return m_masteringDisplay; }
 #if NH_MV
@@ -1046,6 +1097,10 @@
   WeightedPredictionMethod getWeightedPredictionMethod() const       { return m_weightedPredictionMethod; }
   Void         setWeightedPredictionMethod( WeightedPredictionMethod m ) { m_weightedPredictionMethod = m; }
-  Void         setSignHideFlag( Bool signHideFlag )                  { m_signHideFlag = signHideFlag; }
-  Bool         getSignHideFlag()                                     { return m_signHideFlag; }
+  Void         setSignDataHidingEnabledFlag( Bool b )                { m_SignDataHidingEnabledFlag = b;    }
+#if NH_MV
+  Bool         getSignDataHidingEnabledFlag()       const            { return m_SignDataHidingEnabledFlag; }
+#else
+  Bool         getSignDataHidingEnabledFlag()                        { return m_SignDataHidingEnabledFlag; }
+#endif
   Bool         getUseRateCtrl         ()                             { return m_RCEnableRateControl;   }
   Void         setUseRateCtrl         ( Bool b )                     { m_RCEnableRateControl = b;      }
@@ -1062,6 +1117,4 @@
   Bool         getForceIntraQP        ()                             { return m_RCForceIntraQP;        }
   Void         setForceIntraQP        ( Bool b )                     { m_RCForceIntraQP = b;           }
-
-#if U0132_TARGET_BITS_SATURATION
   Bool         getCpbSaturationEnabled()                             { return m_RCCpbSaturationEnabled;}
   Void         setCpbSaturationEnabled( Bool b )                     { m_RCCpbSaturationEnabled = b;   }
@@ -1070,5 +1123,4 @@
   Double       getInitialCpbFullness  ()                             { return m_RCInitialCpbFullness;  }
   Void         setInitialCpbFullness  (Double f)                     { m_RCInitialCpbFullness = f;     }
-#endif
 
 #if KWU_RC_MADPRED_E0227
@@ -1080,13 +1132,19 @@
   Void         setUseViewWiseRateCtrl (Bool b)                       { m_bViewWiseRateCtrl    = b;        }
 #endif
-  Bool         getTransquantBypassEnableFlag()                       { return m_TransquantBypassEnableFlag; }
-  Void         setTransquantBypassEnableFlag(Bool flag)              { m_TransquantBypassEnableFlag = flag; }
+#if NH_MV
+  Bool         getTransquantBypassEnabledFlag()               const   { return m_TransquantBypassEnabledFlag; }
+#else
+  Bool         getTransquantBypassEnabledFlag()                       { return m_TransquantBypassEnabledFlag; }
+#endif
+  Void         setTransquantBypassEnabledFlag(Bool flag)             { m_TransquantBypassEnabledFlag = flag; }
   Bool         getCUTransquantBypassFlagForceValue()                 { return m_CUTransquantBypassFlagForce; }
   Void         setCUTransquantBypassFlagForceValue(Bool flag)        { m_CUTransquantBypassFlagForce = flag; }
-  CostMode     getCostMode( )                                        { return m_costMode; }
+  CostMode     getCostMode( ) const                                  { return m_costMode; }
   Void         setCostMode(CostMode m )                              { m_costMode = m; }
 #if NH_MV
   Void         setVPS( TComVPS *p )                                  { m_cVPS = p;    }
   TComVPS*     getVPS()                                              { return m_cVPS; }
+  TComVPS*     getVPS() const                                        { return m_cVPS; } 
+  
 #else
   Void         setVPS(TComVPS *p)                                    { m_cVPS = *p; }
@@ -1094,5 +1152,5 @@
 #endif
 
-#if NH_3D_DLT
+#if NH_3D
   Void         setDLT( TComDLT p )                                   { m_cDLT = p; }
   TComDLT*     getDLT()                                              { return &m_cDLT; }
@@ -1261,12 +1319,16 @@
 #endif
 
-#if NH_3D_QTL
+#if NH_3D
   Void      setUseQTL                       ( Bool b ) { m_bUseQTL = b;    }
   Bool      getUseQTL                       ()         { return m_bUseQTL; }
-#endif
-#if NH_3D
-
-  Void      setProfileIdc( Int a )    { assert( a == 1 || a == 6 || a == 8 ); m_profileIdc = a;  }
+#if NH_MV_ALLOW_NON_CONFORMING
+  Void      setProfileIdc( Int a )    { assert( a == Profile::MAIN || a == Profile::MULTIVIEWMAIN|| a == Profile::MAIN3D  ||  a == Profile::NONE || a == Profile::MAIN3D_NONCONFORMING || a == Profile::MULTIVIEWMAIN_NONCONFORMING|| a == Profile::MAIN3D_NONCONFORMING  ); m_profileIdc = a;  }
+  Bool      decProcAnnexI()           { assert( m_profileIdc != -1 ); return ( m_profileIdc == Profile::MAIN3D  || m_profileIdc == Profile::MAIN3D_NONCONFORMING ); }    
+#else
+  Void      setProfileIdc( Int a )    { assert( a == Profile::MAIN || a == Profile::MULTIVIEWMAIN|| a == Profile::MAIN3D ); m_profileIdc = a;  }
   Bool      decProcAnnexI()           { assert( m_profileIdc != -1 ); return ( m_profileIdc == Profile::MAIN3D ); }    
+#endif
+
+  
 #endif // NH_3D
 };
Index: /trunk/source/Lib/TLibEncoder/TEncCu.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncCu.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncCu.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -46,5 +46,4 @@
 using namespace std;
 
-
 //! \ingroup TLibEncoder
 //! \{
@@ -68,5 +67,5 @@
   m_ppcTempCU      = new TComDataCU*[m_uhTotalDepth-1];
 
-#if NH_3D_ARP
+#if NH_3D
   m_ppcWeightedTempCU = new TComDataCU*[m_uhTotalDepth-1];
 #endif 
@@ -79,5 +78,5 @@
   m_ppcRecoYuvTemp = new TComYuv*[m_uhTotalDepth-1];
   m_ppcOrigYuv     = new TComYuv*[m_uhTotalDepth-1];
-#if NH_3D_DBBP
+#if NH_3D
   m_ppcOrigYuvDBBP = new TComYuv*[m_uhTotalDepth-1];
 #endif
@@ -92,5 +91,5 @@
     m_ppcBestCU[i] = new TComDataCU; m_ppcBestCU[i]->create( chromaFormat, uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
     m_ppcTempCU[i] = new TComDataCU; m_ppcTempCU[i]->create( chromaFormat, uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
-#if NH_3D_ARP
+#if NH_3D
     m_ppcWeightedTempCU[i] = new TComDataCU; m_ppcWeightedTempCU[i]->create( chromaFormat, uiNumPartitions, uiWidth, uiHeight, false, uiMaxWidth >> (m_uhTotalDepth - 1) );
 #endif  
@@ -105,5 +104,5 @@
 
     m_ppcOrigYuv    [i] = new TComYuv; m_ppcOrigYuv    [i]->create(uiWidth, uiHeight, chromaFormat);
-#if NH_3D_DBBP
+#if NH_3D
     m_ppcOrigYuvDBBP[i] = new TComYuv; m_ppcOrigYuvDBBP[i]->create(uiWidth, uiHeight, chromaFormat);
 #endif
@@ -147,5 +146,5 @@
       m_ppcTempCU[i]->destroy();      delete m_ppcTempCU[i];      m_ppcTempCU[i] = NULL;
     }
-#if NH_3D_ARP
+#if NH_3D
     if(m_ppcWeightedTempCU[i])
     {
@@ -181,5 +180,5 @@
       m_ppcOrigYuv[i]->destroy();     delete m_ppcOrigYuv[i];     m_ppcOrigYuv[i] = NULL;
     }
-#if NH_3D_DBBP
+#if NH_3D
     if(m_ppcOrigYuvDBBP[i])
     {
@@ -199,5 +198,5 @@
   }
 
-#if NH_3D_ARP
+#if NH_3D
   if(m_ppcWeightedTempCU)
   {
@@ -241,5 +240,5 @@
     m_ppcOrigYuv = NULL;
   }
-#if NH_3D_DBBP
+#if NH_3D
   if(m_ppcOrigYuvDBBP)
   {
@@ -266,4 +265,6 @@
 
   m_pcRateCtrl         = pcEncTop->getRateCtrl();
+  m_lumaQPOffset       = 0;
+  initLumaDeltaQpLUT();
 }
 
@@ -281,5 +282,5 @@
   m_ppcTempCU[0]->initCtu( pCtu->getPic(), pCtu->getCtuRsAddr() );
 
-#if NH_3D_ARP
+#if NH_3D
   m_ppcWeightedTempCU[0]->initCtu( pCtu->getPic(), pCtu->getCtuRsAddr() );
 #endif
@@ -329,4 +330,87 @@
 // Protected member functions
 // ====================================================================================================================
+
+Void TEncCu::initLumaDeltaQpLUT()
+{
+  const LumaLevelToDeltaQPMapping &mapping=m_pcEncCfg->getLumaLevelToDeltaQPMapping();
+
+  if ( !mapping.isEnabled() )
+  {
+    return;
+  }
+
+  // map the sparse LumaLevelToDeltaQPMapping.mapping to a fully populated linear table.
+
+  Int         lastDeltaQPValue=0;
+  std::size_t nextSparseIndex=0;
+  for(Int index=0; index<LUMA_LEVEL_TO_DQP_LUT_MAXSIZE; index++)
+  {
+    while (nextSparseIndex < mapping.mapping.size() && index>=mapping.mapping[nextSparseIndex].first)
+    {
+      lastDeltaQPValue=mapping.mapping[nextSparseIndex].second;
+      nextSparseIndex++;
+    }
+    m_lumaLevelToDeltaQPLUT[index]=lastDeltaQPValue;
+  }
+}
+
+Int TEncCu::calculateLumaDQP(TComDataCU *pCU, const UInt absPartIdx, const TComYuv * pOrgYuv)
+{
+  const Pel *pY = pOrgYuv->getAddr(COMPONENT_Y, absPartIdx);
+  const Int stride  = pOrgYuv->getStride(COMPONENT_Y);
+  Int width = pCU->getWidth(absPartIdx);
+  Int height = pCU->getHeight(absPartIdx);
+  Double avg = 0;
+
+  // limit the block by picture size
+  const TComSPS* pSPS = pCU->getSlice()->getSPS();
+  if ( pCU->getCUPelX() + width > pSPS->getPicWidthInLumaSamples() )
+  {
+    width = pSPS->getPicWidthInLumaSamples() - pCU->getCUPelX();
+  }
+  if ( pCU->getCUPelY() + height > pSPS->getPicHeightInLumaSamples() )
+  {
+    height = pSPS->getPicHeightInLumaSamples() - pCU->getCUPelY();
+  }
+
+  // Get QP offset derived from Luma level
+  if ( m_pcEncCfg->getLumaLevelToDeltaQPMapping().mode == LUMALVL_TO_DQP_AVG_METHOD )
+  {
+    // Use avg method
+    Int sum = 0;
+    for (Int y = 0; y < height; y++)
+    {
+      for (Int x = 0; x < width; x++)
+      {
+        sum += pY[x];
+      }
+      pY += stride;
+    }
+    avg = (Double)sum/(width*height);
+  }
+  else
+  {
+    // Use maximum luma value
+    Int maxVal = 0;
+    for (Int y = 0; y < height; y++)
+    {
+      for (Int x = 0; x < width; x++)
+      {
+        if (pY[x] > maxVal)
+        {
+          maxVal = pY[x];
+        }
+      }
+      pY += stride;
+    }
+    // use a percentage of the maxVal
+    avg = (Double)maxVal * m_pcEncCfg->getLumaLevelToDeltaQPMapping().maxMethodWeight;
+  }
+
+  Int lumaIdx = Clip3<Int>(0, Int(LUMA_LEVEL_TO_DQP_LUT_MAXSIZE)-1, Int(avg+0.5) );
+  Int QP = m_lumaLevelToDeltaQPLUT[lumaIdx];
+  return QP;
+}
+
 //! Derive small set of test modes for AMP encoder speed-up
 #if AMP_ENC_SPEEDUP
@@ -420,10 +504,6 @@
   const UInt fastDeltaQPCuMaxSize    = Clip3(sps.getMaxCUHeight()>>sps.getLog2DiffMaxMinCodingBlockSize(), sps.getMaxCUHeight(), 32u);
 
-#if NH_3D_QTL
-#if NH_3D_QTLPC
+#if NH_3D
   Bool  bLimQtPredFalg    = pcPic->getSlice(0)->getQtPredFlag(); 
-#else
-  Bool  bLimQtPredFalg    = false;
-#endif
   TComPic *pcTexture      = rpcBestCU->getSlice()->getTexturePic();
 
@@ -440,5 +520,5 @@
   m_ppcOrigYuv[uiDepth]->copyFromPicYuv( pcPic->getPicYuvOrg(), rpcBestCU->getCtuRsAddr(), rpcBestCU->getZorderIdxInCtu() );
 
-#if NH_3D_QTL  
+#if NH_3D
   Bool    bTrySplit     = true;
   Bool    bTrySplitDQP  = true;
@@ -448,11 +528,9 @@
   Bool    earlyDetectionSkipMode = false;
 
-#if NH_3D_NBDV
+#if NH_3D
   DisInfo DvInfo; 
   DvInfo.m_acNBDV.setZero();
   DvInfo.m_aVIdxCan = 0;
-#if NH_3D_NBDV_REF
   DvInfo.m_acDoNBDV.setZero();
-#endif
 #endif
   const UInt uiLPelX   = rpcBestCU->getCUPelX();
@@ -492,4 +570,15 @@
   }
 
+  if ( m_pcEncCfg->getLumaLevelToDeltaQPMapping().isEnabled() )
+  {
+    if ( uiDepth <= pps.getMaxCuDQPDepth() )
+    {
+      // keep using the same m_QP_LUMA_OFFSET in the same CTU
+      m_lumaQPOffset = calculateLumaDQP(rpcTempCU, 0, m_ppcOrigYuv[uiDepth]);
+    }
+    iMinQP = Clip3(-sps.getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP - m_lumaQPOffset);
+    iMaxQP = iMinQP; // force encode choose the modified QO
+  }
+
   if ( m_pcEncCfg->getUseRateCtrl() )
   {
@@ -502,5 +591,5 @@
   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 ( (pps.getTransquantBypassEnableFlag()) )
+  if ( (pps.getTransquantBypassEnabledFlag()) )
   {
     isAddLowestQP = true; // mark that the first iteration is to cost TQB mode.
@@ -512,5 +601,5 @@
   }
 
-#if NH_3D_IC
+#if NH_3D
   Bool bICEnabled = rpcTempCU->getSlice()->getViewIndex() && ( rpcTempCU->getSlice()->getSliceType() == P_SLICE || rpcTempCU->getSlice()->getSliceType() == B_SLICE ) && !rpcTempCU->getSlice()->getIsDepth();
   bICEnabled = bICEnabled && rpcTempCU->getSlice()->getApplyIC();
@@ -536,6 +625,12 @@
         iQP = lowestQP;
       }
-
-#if NH_3D_QTL
+      if ( m_pcEncCfg->getLumaLevelToDeltaQPMapping().isEnabled() && uiDepth <= pps.getMaxCuDQPDepth() )
+      {
+        getSliceEncoder()->updateLambda(pcSlice, iQP);
+      }
+
+
+
+#if NH_3D
       bTrySplit    = true;
 #endif
@@ -555,11 +650,7 @@
 
       rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_QTL
+#if NH_3D
       //logic for setting bTrySplit using the partition information that is stored of the texture colocated CU
-#if H_3D_FCO
-      if(depthMapDetect && !bIntraSliceDetect && !rapPic && ( m_pcEncCfg->getUseQTL() || bLimQtPredFalg ) && pcTexture->getReconMark())
-#else
       if(depthMapDetect && !bIntraSliceDetect && !rapPic && ( m_pcEncCfg->getUseQTL() || bLimQtPredFalg ))
-#endif
       {
         TComDataCU* pcTextureCU = pcTexture->getCtu( rpcBestCU->getCtuRsAddr() ); //Corresponding texture LCU
@@ -592,40 +683,11 @@
 #endif
 
-#if NH_3D_NBDV
+#if NH_3D
       if( rpcTempCU->getSlice()->getSliceType() != I_SLICE )
       {
-#if NH_3D_ARP && NH_3D_IV_MERGE && NH_3D_VSP
         if( rpcTempCU->getSlice()->getIvResPredFlag() || rpcTempCU->getSlice()->getIvMvPredFlag() || rpcTempCU->getSlice()->getViewSynthesisPredFlag() )
-#else 
-#if NH_3D_IV_MERGE && NH_3D_VSP
-        if( rpcTempCU->getSlice()->getIvMvPredFlag() || rpcTempCU->getSlice()->getViewSynthesisPredFlag() )
-#else
-#if NH_3D_ARP && NH_3D_VSP
-        if( rpcTempCU->getSlice()->getIvResPredFlag() || rpcTempCU->getSlice()->getViewSynthesisPredFlag() )
-#else
-#if NH_3D_VSP
-        if( rpcTempCU->getSlice()->getViewSynthesisPredFlag() )
-#else
-#if NH_3D_ARP
-        if( rpcTempCU->getSlice()->getIvResPredFlag() )
-#else
-#if H_3D_IV_MERGE
-        if( rpcTempCU->getSlice()->getVPS()->getIvMvPredFlag(rpcTempCU->getSlice()->getLayerId()) )
-#else
-#if NH_3D_DBBP
-        if( rpcTempCU->getSlice()->getDepthBasedBlkPartFlag() )
-#else
-        if (0)
-#endif
-#endif
-#endif
-#endif
-#endif
-#endif
-#endif
         {
           PartSize ePartTemp = rpcTempCU->getPartitionSize(0);
           rpcTempCU->setPartSizeSubParts(SIZE_2Nx2N, 0, uiDepth);
-#if NH_3D_IV_MERGE
           if (rpcTempCU->getSlice()->getIsDepth() )
           {
@@ -634,6 +696,4 @@
           else
           {
-#endif 
-#if NH_3D_NBDV_REF
             if( rpcTempCU->getSlice()->getDepthRefinementFlag() )
             {
@@ -641,11 +701,8 @@
             }
             else
-#endif 
             {
               rpcTempCU->getDisMvpCandNBDV(&DvInfo);
             }
-#if NH_3D_IV_MERGE
-          }
-#endif
+          }
           rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
           rpcBestCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
@@ -666,5 +723,5 @@
       if( rpcBestCU->getSlice()->getSliceType() != I_SLICE )
       {
-#if NH_3D_IC
+#if NH_3D
         for( UInt uiICId = 0; uiICId < ( bICEnabled ? 2 : 1 ); uiICId++ )
         {
@@ -674,5 +731,5 @@
         if(m_pcEncCfg->getUseEarlySkipDetection())
         {
-#if NH_3D_IC
+#if NH_3D
             rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
 #endif
@@ -683,10 +740,10 @@
           rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );//by Competition for inter_2Nx2N
 #endif
-#if NH_3D_VSP  || NH_3D_DBBP
+#if NH_3D
           rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
         }
         // SKIP
-#if NH_3D_IC
+#if NH_3D
           rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
 #endif
@@ -697,5 +754,5 @@
 
         rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_VSP  || NH_3D_DBBP
+#if NH_3D
         rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
@@ -704,5 +761,5 @@
         {
           // 2Nx2N, NxN
-#if NH_3D_IC
+#if NH_3D
             rpcTempCU->setICFlagSubParts(bICFlag, 0, 0, uiDepth);
 #endif
@@ -714,15 +771,11 @@
           rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
 #endif
-#if NH_3D_VSP  || NH_3D_DBBP
+#if NH_3D
           rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
-#endif
-#if NH_3D_DBBP
             if( rpcTempCU->getSlice()->getDepthBasedBlkPartFlag() && rpcTempCU->getSlice()->getDefaultRefViewIdxAvailableFlag() )
             {
               xCheckRDCostInterDBBP( rpcBestCU, rpcTempCU DEBUG_STRING_PASS_INTO(sDebug), false );
               rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode  );
-#if NH_3D_VSP  || NH_3D_DBBP
               rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
-#endif
             }
 #endif
@@ -733,9 +786,9 @@
           }
         }
-#if NH_3D_IC
+#if NH_3D
         }
 #endif
       }
-#if NH_3D_QTL
+#if NH_3D
       if(depthMapDetect && !bIntraSliceDetect && !rapPic && ( m_pcEncCfg->getUseQTL() || bLimQtPredFalg ))
       {
@@ -757,11 +810,10 @@
     }
 #endif
-#if NH_3D_ENC_DEPTH
+#if NH_3D
     if( rpcBestCU->getSlice()->getIsDepth() && rpcBestCU->getSlice()->isIRAP() )
     {
       earlyDetectionSkipMode = false;
     }
-#endif
-#if NH_3D_DIS
+
     rpcTempCU->initEstData( uiDepth, iMinQP, isAddLowestQP  );
     if( rpcBestCU->getSlice()->getDepthIntraSkipFlag() )
@@ -792,5 +844,5 @@
           {
             if( uiDepth == sps.getLog2DiffMaxMinCodingBlockSize() && doNotBlockPu
-#if NH_3D_QTL
+#if NH_3D
                 && bTrySplit
 #endif
@@ -804,5 +856,5 @@
 #endif
               rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_VSP || NH_3D_DBBP
+#if NH_3D
               rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
@@ -812,5 +864,5 @@
 
           if(doNotBlockPu
-#if NH_3D_QTL
+#if NH_3D
             && bTryNx2N
 #endif
@@ -823,5 +875,5 @@
 #endif
             rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_VSP || NH_3D_DBBP
+#if NH_3D
             rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
@@ -833,5 +885,5 @@
           }
           if(doNotBlockPu
-#if NH_3D_QTL
+#if NH_3D
             && bTry2NxN
 #endif
@@ -846,5 +898,5 @@
 
             rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_VSP || NH_3D_DBBP
+#if NH_3D
             rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
@@ -874,5 +926,5 @@
             {
               if(doNotBlockPu
-#if NH_3D_QTL
+#if NH_3D
                 && bTry2NxN
 #endif
@@ -885,5 +937,5 @@
 #endif
                 rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_VSP || NH_3D_DBBP
+#if NH_3D
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
@@ -894,5 +946,5 @@
               }
               if(doNotBlockPu
-#if NH_3D_QTL
+#if NH_3D
                 && bTry2NxN
 #endif
@@ -906,5 +958,5 @@
 
                 rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_VSP || NH_3D_DBBP
+#if NH_3D
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
@@ -920,5 +972,5 @@
             {
               if(doNotBlockPu
-#if NH_3D_QTL
+#if NH_3D
                 && bTry2NxN
 #endif
@@ -933,5 +985,5 @@
 
                 rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_VSP || NH_3D_DBBP
+#if NH_3D
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
@@ -942,5 +994,5 @@
               }
               if(doNotBlockPu
-#if NH_3D_QTL
+#if NH_3D
                 && bTry2NxN
 #endif
@@ -953,5 +1005,5 @@
 #endif
                 rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_VSP || NH_3D_DBBP
+#if NH_3D
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
@@ -969,5 +1021,5 @@
             {
               if(doNotBlockPu
-#if NH_3D_QTL
+#if NH_3D
                 && bTryNx2N
 #endif
@@ -981,5 +1033,5 @@
 
                 rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_VSP || NH_3D_DBBP
+#if NH_3D
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
@@ -990,5 +1042,5 @@
               }
               if(doNotBlockPu
-#if NH_3D_QTL
+#if NH_3D
                 && bTryNx2N
 #endif
@@ -1001,5 +1053,5 @@
 #endif
                 rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_VSP || NH_3D_DBBP
+#if NH_3D
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
@@ -1010,5 +1062,5 @@
             {
               if(doNotBlockPu
-#if NH_3D_QTL
+#if NH_3D
                 && bTryNx2N
 #endif
@@ -1021,5 +1073,5 @@
 #endif
                 rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_VSP || NH_3D_DBBP
+#if NH_3D
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
@@ -1030,5 +1082,5 @@
               }
               if(doNotBlockPu
-#if NH_3D_QTL
+#if NH_3D
                 && bTryNx2N
 #endif
@@ -1042,5 +1094,5 @@
 #endif
                 rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_VSP || NH_3D_DBBP
+#if NH_3D
                 rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
 #endif
@@ -1051,35 +1103,30 @@
 
 #else
-#if NH_3D_QTL
+#if NH_3D
             if (bTry2NxN)
             {
 #endif
-
-            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
-            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_VSP || NH_3D_DBBP
-            rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
-#endif
-            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
-            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_VSP || NH_3D_DBBP
-            rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
-#endif
-#if NH_3D_QTL
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnU );
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if NH_3D
+              rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_2NxnD );
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if NH_3D
+              rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
             }
             if (bTryNx2N)
             {
 #endif
-            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
-            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_VSP || NH_3D_DBBP
-            rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
-#endif
-            xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
-            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_VSP || NH_3D_DBBP
-            rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
-#endif
-#if NH_3D_QTL
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nLx2N );
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if NH_3D
+              rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
+#endif
+              xCheckRDCostInter( rpcBestCU, rpcTempCU, SIZE_nRx2N );
+              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+#if NH_3D
+              rpcTempCU->setDvInfoSubParts(DvInfo, 0, uiDepth);
             }
 #endif
@@ -1093,35 +1140,43 @@
         {
 #endif
-
         // do normal intra modes
         // speedup for inter frames
 
-        if((rpcBestCU->getSlice()->getSliceType() == I_SLICE)                                     ||
-           ((!m_pcEncCfg->getDisableIntraPUsInInterSlices()) && (
-           (rpcBestCU->getCbf( 0, COMPONENT_Y  ) != 0)                                            ||
-          ((rpcBestCU->getCbf( 0, COMPONENT_Cb ) != 0) && (numberValidComponents > COMPONENT_Cb)) ||
-          ((rpcBestCU->getCbf( 0, COMPONENT_Cr ) != 0) && (numberValidComponents > COMPONENT_Cr))   // avoid very complex intra if it is unlikely
- #if NH_3D_ENC_DEPTH
+
+#if MCTS_ENC_CHECK
+        if ( m_pcEncCfg->getTMCTSSEITileConstraint() || (rpcBestCU->getSlice()->getSliceType() == I_SLICE) ||
+             ((!m_pcEncCfg->getDisableIntraPUsInInterSlices()) && (
+             (rpcBestCU->getCbf(0, COMPONENT_Y) != 0) ||
+             ((rpcBestCU->getCbf(0, COMPONENT_Cb) != 0) && (numberValidComponents > COMPONENT_Cb)) ||
+             ((rpcBestCU->getCbf(0, COMPONENT_Cr) != 0) && (numberValidComponents > COMPONENT_Cr))  // avoid very complex intra if it is unlikely
+#else
+        if((rpcBestCU->getSlice()->getSliceType() == I_SLICE)                                        ||
+            ((!m_pcEncCfg->getDisableIntraPUsInInterSlices()) && (
+              (rpcBestCU->getCbf( 0, COMPONENT_Y  ) != 0)                                            ||
+             ((rpcBestCU->getCbf( 0, COMPONENT_Cb ) != 0) && (numberValidComponents > COMPONENT_Cb)) ||
+             ((rpcBestCU->getCbf( 0, COMPONENT_Cr ) != 0) && (numberValidComponents > COMPONENT_Cr))  // avoid very complex intra if it is unlikely
+#endif
+ #if NH_3D
             || rpcBestCU->getSlice()->getIsDepth()
 #endif
             )))
-        {
-#if NH_3D_ENC_DEPTH
-            Bool bOnlyIVP = false;
-            Bool bUseIVP = true;
-            if( (rpcBestCU->getSlice()->getSliceType() != I_SLICE) && 
-                !( (rpcBestCU->getCbf( 0, COMPONENT_Y  ) != 0)                                            ||
-                  ((rpcBestCU->getCbf( 0, COMPONENT_Cb ) != 0) && (numberValidComponents > COMPONENT_Cb)) ||
-                  ((rpcBestCU->getCbf( 0, COMPONENT_Cr ) != 0) && (numberValidComponents > COMPONENT_Cr))   ) &&
-                  (rpcBestCU->getSlice()->getIsDepth() && !(rpcBestCU->getSlice()->isIRAP())) )
-            { 
-              bOnlyIVP = true;
-              bUseIVP = rpcBestCU->getSlice()->getIntraContourFlag();
-            }
-            if( bUseIVP )
-            {
-              xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_2Nx2N DEBUG_STRING_PASS_INTO(sDebug), bOnlyIVP );
-#else
-          xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_2Nx2N DEBUG_STRING_PASS_INTO(sDebug) );
+          {
+#if NH_3D
+          Bool bOnlyIVP = false;
+          Bool bUseIVP = true;
+          if( (rpcBestCU->getSlice()->getSliceType() != I_SLICE) && 
+            !( (rpcBestCU->getCbf( 0, COMPONENT_Y  ) != 0)                                            ||
+            ((rpcBestCU->getCbf( 0, COMPONENT_Cb ) != 0) && (numberValidComponents > COMPONENT_Cb)) ||
+            ((rpcBestCU->getCbf( 0, COMPONENT_Cr ) != 0) && (numberValidComponents > COMPONENT_Cr))   ) &&
+            (rpcBestCU->getSlice()->getIsDepth() && !(rpcBestCU->getSlice()->isIRAP())) )
+          { 
+            bOnlyIVP = true;
+            bUseIVP = rpcBestCU->getSlice()->getIntraContourFlag();
+          }
+          if( bUseIVP )
+          {
+            xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_2Nx2N DEBUG_STRING_PASS_INTO(sDebug), bOnlyIVP );
+#else
+            xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_2Nx2N DEBUG_STRING_PASS_INTO(sDebug) );
 #endif
 #if KWU_RC_MADPRED_E0227
@@ -1133,25 +1188,25 @@
 #endif
 
-          rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-          if( uiDepth == sps.getLog2DiffMaxMinCodingBlockSize() )
-          {
-#if NH_3D_QTL //Try IntraNxN
+            rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+            if( uiDepth == sps.getLog2DiffMaxMinCodingBlockSize() )
+            {
+#if NH_3D   //Try IntraNxN
               if(bTrySplit)
               {
 #endif
-            if( rpcTempCU->getWidth(0) > ( 1 << sps.getQuadtreeTULog2MinSize() ) )
-            {
-#if NH_3D_ENC_DEPTH
-              xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_NxN DEBUG_STRING_PASS_INTO(sDebug), bOnlyIVP );
-#else
-              xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_NxN DEBUG_STRING_PASS_INTO(sDebug)   );
+                if( rpcTempCU->getWidth(0) > ( 1 << sps.getQuadtreeTULog2MinSize() ) )
+                {
+#if NH_3D
+                  xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_NxN DEBUG_STRING_PASS_INTO(sDebug), bOnlyIVP );
+#else
+                  xCheckRDCostIntra( rpcBestCU, rpcTempCU, SIZE_NxN DEBUG_STRING_PASS_INTO(sDebug)   );
 #endif        
-              rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+                  rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
+                }
+#if NH_3D
+              }
+#endif
             }
-#if NH_3D_QTL
-              }
-#endif
-          }
-#if NH_3D_ENC_DEPTH
+#if NH_3D
           }
 #endif
@@ -1171,5 +1226,4 @@
           if((uiBestBits > uiRawBits) || (rpcBestCU->getTotalCost() > m_pcRdCost->calcRdCost(uiRawBits, 0)))
 #endif
-
           {
             xCheckIntraPCM (rpcBestCU, rpcTempCU);
@@ -1236,4 +1290,10 @@
   }
 
+  if ( m_pcEncCfg->getLumaLevelToDeltaQPMapping().isEnabled() )
+  {
+    iMinQP = Clip3(-sps.getQpBDOffset(CHANNEL_TYPE_LUMA), MAX_QP, iBaseQP - m_lumaQPOffset);
+    iMaxQP = iMinQP;
+  }
+
   if ( m_pcEncCfg->getUseRateCtrl() )
   {
@@ -1251,5 +1311,5 @@
   const Bool bSubBranch = bBoundary || !( m_pcEncCfg->getUseEarlyCU() && rpcBestCU->getTotalCost()!=MAX_DOUBLE && rpcBestCU->isSkipped(0) );
 #endif
-#if NH_3D_QTL
+#if NH_3D
   if( bSubBranch && uiDepth < sps.getLog2DiffMaxMinCodingBlockSize() && (!getFastDeltaQp() || uiWidth > fastDeltaQPCuMaxSize || bBoundary) && bTrySplitDQP )
 #else
@@ -1258,4 +1318,6 @@
   {
     // further split
+    Double splitTotalCost = 0;
+
     for (Int iQP=iMinQP; iQP<=iMaxQP; iQP++)
     {
@@ -1280,5 +1342,5 @@
       DEBUG_STRING_NEW(sTempDebug)
 
-#if NH_3D_ARP
+#if NH_3D
       m_ppcWeightedTempCU[uhNextDepth]->setSlice( m_ppcWeightedTempCU[ uiDepth]->getSlice()); 
       m_ppcWeightedTempCU[uhNextDepth]->setPic  ( m_ppcWeightedTempCU[ uiDepth] ); 
@@ -1318,4 +1380,8 @@
           rpcTempCU->copyPartFrom( pcSubBestPartCU, uiPartUnitIdx, uhNextDepth );         // Keep best part data to current temporary data.
           xCopyYuv2Tmp( pcSubBestPartCU->getTotalNumPart()*uiPartUnitIdx, uhNextDepth );
+          if ( m_pcEncCfg->getLumaLevelToDeltaQPMapping().isEnabled() && pps.getMaxCuDQPDepth() >= 1 )
+          {
+            splitTotalCost += pcSubBestPartCU->getTotalCost();
+          }
         }
         else
@@ -1331,8 +1397,20 @@
         m_pcEntropyCoder->resetBits();
         m_pcEntropyCoder->encodeSplitFlag( rpcTempCU, 0, uiDepth, true );
+        if ( m_pcEncCfg->getLumaLevelToDeltaQPMapping().isEnabled() && pps.getMaxCuDQPDepth() >= 1 )
+        {
+          Int splitBits = m_pcEntropyCoder->getNumberOfWrittenBits();
+          Double splitBitCost = m_pcRdCost->calcRdCost( splitBits, 0 );
+          splitTotalCost += splitBitCost;
+        }
 
         rpcTempCU->getTotalBits() += m_pcEntropyCoder->getNumberOfWrittenBits(); // split bits
         rpcTempCU->getTotalBins() += ((TEncBinCABAC *)((TEncSbac*)m_pcEntropyCoder->m_pcEntropyCoderIf)->getEncBinIf())->getBinsCoded();
       }
+      if ( m_pcEncCfg->getLumaLevelToDeltaQPMapping().isEnabled() && pps.getMaxCuDQPDepth() >= 1 )
+      {
+        rpcTempCU->getTotalCost() = splitTotalCost;
+      }
+      else
+      {
 #if NH_3D_VSO // M10
       if ( m_pcRdCost->getUseLambdaScaleVSO() )
@@ -1343,4 +1421,5 @@
 #endif
         rpcTempCU->getTotalCost()  = m_pcRdCost->calcRdCost( rpcTempCU->getTotalBits(), rpcTempCU->getTotalDistortion() );
+      }
 
       if( uiDepth == pps.getMaxCuDQPDepth() && pps.getUseDQP())
@@ -1572,5 +1651,5 @@
   }
 
-  if (pps.getTransquantBypassEnableFlag())
+  if (pps.getTransquantBypassEnabledFlag())
   {
     m_pcEntropyCoder->encodeCUTransquantBypassFlag( pcCU, uiAbsPartIdx );
@@ -1591,8 +1670,6 @@
 
     m_pcEntropyCoder->encodeMergeIndex( pcCU, uiAbsPartIdx );
-#if NH_3D_ARP
+#if NH_3D
     m_pcEntropyCoder->encodeARPW( pcCU , uiAbsPartIdx );
-#endif
-#if NH_3D_IC
     m_pcEntropyCoder->encodeICFlag  ( pcCU, uiAbsPartIdx );
 #endif
@@ -1602,50 +1679,44 @@
   }
 
-#if NH_3D_DIS
+#if NH_3D
   m_pcEntropyCoder->encodeDIS( pcCU, uiAbsPartIdx );
   if(!pcCU->getDISFlag(uiAbsPartIdx))
   {
 #endif
-  m_pcEntropyCoder->encodePredMode( pcCU, uiAbsPartIdx );
-  m_pcEntropyCoder->encodePartSize( pcCU, uiAbsPartIdx, uiDepth );
-
-  if (pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
-  {
-    m_pcEntropyCoder->encodeIPCMInfo( pcCU, uiAbsPartIdx );
-
-    if(pcCU->getIPCMFlag(uiAbsPartIdx))
-    {
-#if NH_3D_SDC_INTRA
-      m_pcEntropyCoder->encodeSDCFlag( pcCU, uiAbsPartIdx );
+    m_pcEntropyCoder->encodePredMode( pcCU, uiAbsPartIdx );
+    m_pcEntropyCoder->encodePartSize( pcCU, uiAbsPartIdx, uiDepth );
+
+    if (pcCU->isIntra( uiAbsPartIdx ) && pcCU->getPartitionSize( uiAbsPartIdx ) == SIZE_2Nx2N )
+    {
+      m_pcEntropyCoder->encodeIPCMInfo( pcCU, uiAbsPartIdx );
+
+      if(pcCU->getIPCMFlag(uiAbsPartIdx))
+      {
+#if NH_3D
+        m_pcEntropyCoder->encodeSDCFlag( pcCU, uiAbsPartIdx );
 #endif  
 
-      // Encode slice finish
-      finishCU(pcCU,uiAbsPartIdx);
-      return;
-    }
-  }
-
-  // prediction Info ( Intra : direction mode, Inter : Mv, reference idx )
-  m_pcEntropyCoder->encodePredInfo( pcCU, uiAbsPartIdx );
-#if NH_3D_DBBP
-  m_pcEntropyCoder->encodeDBBPFlag( pcCU, uiAbsPartIdx );
-#endif
-#if NH_3D_SDC_INTRA
-  m_pcEntropyCoder->encodeSDCFlag( pcCU, uiAbsPartIdx );
-#endif  
-#if NH_3D_ARP
-  m_pcEntropyCoder->encodeARPW( pcCU , uiAbsPartIdx );
-#endif
-#if NH_3D_IC
-  m_pcEntropyCoder->encodeICFlag  ( pcCU, uiAbsPartIdx );
-#endif
-
-  // Encode Coefficients
-  Bool bCodeDQP = getdQPFlag();
-  Bool codeChromaQpAdj = getCodeChromaQpAdjFlag();
-  m_pcEntropyCoder->encodeCoeff( pcCU, uiAbsPartIdx, uiDepth, bCodeDQP, codeChromaQpAdj );
-  setCodeChromaQpAdjFlag( codeChromaQpAdj );
-  setdQPFlag( bCodeDQP );
-#if NH_3D_DIS
+        // Encode slice finish
+        finishCU(pcCU,uiAbsPartIdx);
+        return;
+      }
+    }
+
+    // prediction Info ( Intra : direction mode, Inter : Mv, reference idx )
+    m_pcEntropyCoder->encodePredInfo( pcCU, uiAbsPartIdx );
+#if NH_3D
+    m_pcEntropyCoder->encodeDBBPFlag( pcCU, uiAbsPartIdx );
+    m_pcEntropyCoder->encodeSDCFlag( pcCU, uiAbsPartIdx );
+    m_pcEntropyCoder->encodeARPW( pcCU , uiAbsPartIdx );
+    m_pcEntropyCoder->encodeICFlag  ( pcCU, uiAbsPartIdx );
+#endif
+
+    // Encode Coefficients
+    Bool bCodeDQP = getdQPFlag();
+    Bool codeChromaQpAdj = getCodeChromaQpAdjFlag();
+    m_pcEntropyCoder->encodeCoeff( pcCU, uiAbsPartIdx, uiDepth, bCodeDQP, codeChromaQpAdj );
+    setCodeChromaQpAdjFlag( codeChromaQpAdj );
+    setdQPFlag( bCodeDQP );
+#if NH_3D
   }
 #endif
@@ -1788,5 +1859,5 @@
 #endif
 
-#if NH_3D_MLC
+#if NH_3D
   TComMvField  cMvFieldNeighbours[MRG_MAX_NUM_CANDS_MEM << 1]; // double length for mv of both lists
   UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS_MEM];
@@ -1803,5 +1874,5 @@
   }
   UChar uhDepth = rpcTempCU->getDepth( 0 );
-#if NH_3D_IC
+#if NH_3D
   Bool bICFlag = rpcTempCU->getICFlag( 0 );
 #endif
@@ -1817,12 +1888,11 @@
 #endif
 
-#if NH_3D_ARP
+#if NH_3D  
   DisInfo cOrigDisInfo = rpcTempCU->getDvInfo(0);
-#else
 #endif
 
   rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to CTU level
 
-#if NH_3D_SPIVMP
+#if NH_3D
   Bool bSPIVMPFlag[MRG_MAX_NUM_CANDS_MEM];
   memset(bSPIVMPFlag, false, sizeof(Bool)*MRG_MAX_NUM_CANDS_MEM);
@@ -1831,61 +1901,16 @@
   pcMvFieldSP = new TComMvField[rpcTempCU->getPic()->getPicSym()->getNumPartitionsInCtu()*2]; 
   puhInterDirSP = new UChar[rpcTempCU->getPic()->getPicSym()->getNumPartitionsInCtu()]; 
-#endif
-
-#if NH_3D_VSP
-#if !NH_3D_ARP
-  Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
-  memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
-#if NH_3D_MLC
-  rpcTempCU->initAvailableFlags();
-#endif
-  rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
-#if NH_3D_MLC
-  rpcTempCU->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours
-#if NH_3D_SPIVMP
-    , pcMvFieldSP, puhInterDirSP
-#endif
-    , numValidMergeCand 
-    );
-
-  rpcTempCU->buildMCL( cMvFieldNeighbours,uhInterDirNeighbours, vspFlag
-#if NH_3D_SPIVMP
-    , bSPIVMPFlag
-#endif
-    , numValidMergeCand 
-    );
-#endif
-#endif
-#else
-#if NH_3D_MLC
-  rpcTempCU->initAvailableFlags();
-#endif
+  Int mergeCandBuffer[MRG_MAX_NUM_CANDS_MEM];
+
+  for( UInt ui = 0; ui < rpcTempCU->getSlice()->getMaxNumMergeCand(); ++ui )
+#else
+
+#if MCTS_ENC_CHECK
+  UInt numSpatialMergeCandidates = 0;
+  rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, numSpatialMergeCandidates );
+#else
   rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
-#if NH_3D_MLC
-  rpcTempCU->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours
-#if H_3D_SPIVMP
-    , pcMvFieldSP, puhInterDirSP
-#endif
-    , numValidMergeCand 
-    );
-#if NH_3D_MLC
-  rpcTempCU->buildMCL( cMvFieldNeighbours,uhInterDirNeighbours
-#if H_3D_SPIVMP
-    , bSPIVMPFlag
-#endif
-    , numValidMergeCand 
-    );
-#endif
-#endif
-#endif
-
-#if NH_3D_MLC
-  Int mergeCandBuffer[MRG_MAX_NUM_CANDS_MEM];
-#else
+#endif
   Int mergeCandBuffer[MRG_MAX_NUM_CANDS];
-#endif
-#if NH_3D_MLC
-  for( UInt ui = 0; ui < rpcTempCU->getSlice()->getMaxNumMergeCand(); ++ui )
-#else
   for( UInt ui = 0; ui < numValidMergeCand; ++ui )
 #endif
@@ -1893,4 +1918,11 @@
     mergeCandBuffer[ui] = 0;
   }
+
+#if MCTS_ENC_CHECK && !NH_3D
+  if (m_pcEncCfg->getTMCTSSEITileConstraint() && rpcTempCU->isLastColumnCTUInTile())
+  {
+    numValidMergeCand = numSpatialMergeCandidates;
+  }
+#endif
 
   Bool bestIsSkip = false;
@@ -1907,11 +1939,7 @@
   DEBUG_STRING_NEW(bestStr)
 
-#if NH_3D_ARP
+#if NH_3D
   Int nARPWMax = rpcTempCU->getSlice()->getARPStepNum() - 1;
-#if NH_3D_IC
   if( nARPWMax < 0 || bICFlag )
-#else
-  if( nARPWMax < 0 )
-#endif
   {
     nARPWMax = 0;
@@ -1919,52 +1947,25 @@
   for( Int nARPW=nARPWMax; nARPW >= 0 ; nARPW-- )
   {
-#if NH_3D
 #if DEBUG_STRING
     bestStr.clear(); 
 #endif
-#endif
-#if NH_3D_IV_MERGE
     memset( mergeCandBuffer, 0, MRG_MAX_NUM_CANDS_MEM*sizeof(Int) );
-#else
-    memset( mergeCandBuffer, 0, MRG_MAX_NUM_CANDS * sizeof(Int) );
-#endif
     rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uhDepth ); // interprets depth relative to LCU level
     rpcTempCU->setARPWSubParts( (UChar)nARPW , 0 , uhDepth );
-#if NH_3D_IC
     rpcTempCU->setICFlagSubParts( bICFlag, 0, 0, uhDepth );
-#endif
     rpcTempCU->getDvInfo(0) = cOrigDisInfo;
     rpcTempCU->setDvInfoSubParts(cOrigDisInfo, 0, uhDepth );
-#if NH_3D_VSP
     Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
     memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
-#endif
-#if NH_3D
-#if NH_3D_MLC
     rpcTempCU->initAvailableFlags();
-#endif
+#if MCTS_ENC_CHECK
+    UInt numSpatialMergeCandidates = 0;
+    rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, numSpatialMergeCandidates  );
+#else
     rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
-    rpcTempCU->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours
-#if NH_3D_SPIVMP
-      , pcMvFieldSP, puhInterDirSP
-#endif
-      , numValidMergeCand 
-      );
-
-    rpcTempCU->buildMCL( cMvFieldNeighbours,uhInterDirNeighbours
-#if NH_3D_VSP
-      , vspFlag
-#endif
-#if NH_3D_SPIVMP
-      , bSPIVMPFlag
-#endif
-      , numValidMergeCand 
-      );
-
-#else
-    rpcTempCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
-#endif
-
-
+#endif
+    rpcTempCU->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, pcMvFieldSP, puhInterDirSP, numValidMergeCand );
+
+    rpcTempCU->buildMCL( cMvFieldNeighbours,uhInterDirNeighbours , vspFlag , bSPIVMPFlag, numValidMergeCand );
 #endif
 
@@ -1977,5 +1978,5 @@
     for( UInt uiMergeCand = 0; uiMergeCand < numValidMergeCand; ++uiMergeCand )
     {
-#if NH_3D_IC
+#if NH_3D
       if( rpcTempCU->getSlice()->getApplyIC() && rpcTempCU->getSlice()->getIcSkipParseFlag() )
       {
@@ -1997,5 +1998,5 @@
           // set MC parameters
           rpcTempCU->setPredModeSubParts( MODE_INTER, 0, uhDepth ); // interprets depth relative to CTU level
-#if NH_3D_IC
+#if NH_3D
           rpcTempCU->setICFlagSubParts( bICFlag, 0, 0, uhDepth );
 #endif
@@ -2005,12 +2006,7 @@
           rpcTempCU->setMergeFlagSubParts( true, 0, 0, uhDepth ); // interprets depth relative to CTU level
           rpcTempCU->setMergeIndexSubParts( uiMergeCand, 0, 0, uhDepth ); // interprets depth relative to CTU level
-#if NH_3D_ARP
+#if NH_3D
           rpcTempCU->setARPWSubParts( (UChar)nARPW , 0 , uhDepth );
-#endif
-
-#if NH_3D_VSP
           rpcTempCU->setVSPFlagSubParts( vspFlag[uiMergeCand], 0, 0, uhDepth );
-#endif
-#if NH_3D_SPIVMP
           rpcTempCU->setSPIVMPFlagSubParts(bSPIVMPFlag[uiMergeCand], 0, 0, uhDepth);
           if (bSPIVMPFlag[uiMergeCand])
@@ -2030,7 +2026,5 @@
           }
           else
-#endif
           {
-#if NH_3D_VSP
             if ( vspFlag[uiMergeCand] )
             {
@@ -2062,11 +2056,19 @@
             {
 #endif
-            rpcTempCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeCand], 0, 0, uhDepth ); // interprets depth relative to CTU level
-            rpcTempCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
-            rpcTempCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
-#if NH_3D_VSP
+              rpcTempCU->setInterDirSubParts( uhInterDirNeighbours[uiMergeCand], 0, 0, uhDepth ); // interprets depth relative to CTU level
+              rpcTempCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
+              rpcTempCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand], SIZE_2Nx2N, 0, 0 ); // interprets depth relative to rpcTempCU level
+#if NH_3D
             }
 #endif
-          }
+#if MCTS_ENC_CHECK
+            if ( m_pcEncCfg->getTMCTSSEITileConstraint () && (!(m_pcPredSearch->checkTMctsMvp(rpcTempCU))))
+            {
+              continue;
+            }
+#endif
+#if NH_3D
+          }
+#endif
           // do MC
           m_pcPredSearch->motionCompensation ( rpcTempCU, m_ppcPredYuvTemp[uhDepth] );
@@ -2099,14 +2101,10 @@
             mergeCandBuffer[uiMergeCand] = 1;
           }
-#if NH_3D_DIS
+#if NH_3D
           rpcTempCU->setDISFlagSubParts( false, 0, uhDepth );
-#endif
-#if NH_3D_VSP
           if( rpcTempCU->getSkipFlag(0) )
           {
             rpcTempCU->setTrIdxSubParts(0, 0, uhDepth);
           }
-#endif
-#if NH_3D_SDC_INTER
           TComDataCU *rpcTempCUPre = rpcTempCU;
 #endif
@@ -2114,5 +2112,5 @@
           xCheckDQP( rpcTempCU );
           xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth DEBUG_STRING_PASS_INTO(bestStr) DEBUG_STRING_PASS_INTO(tmpStr));
-#if NH_3D_SDC_INTER
+#if NH_3D
           if( rpcTempCU->getSlice()->getInterSdcFlag() && !uiNoResidual )
           {
@@ -2141,7 +2139,5 @@
               }
               rpcTempCU->setSkipFlagSubParts( false, 0, uhDepth );
-#if NH_3D_DIS
               rpcTempCU->setDISFlagSubParts( false, 0, uhDepth );
-#endif
               rpcTempCU->setTrIdxSubParts( 0, 0, uhDepth );
               rpcTempCU->setCbfSubParts( 1, COMPONENT_Y, 0, uhDepth );
@@ -2187,5 +2183,5 @@
           if( m_pcEncCfg->getUseFastDecisionForMerge() && !bestIsSkip )
           {
-#if NH_3D_SDC_INTER
+#if NH_3D
             if( rpcTempCU->getSlice()->getInterSdcFlag() )
             {
@@ -2196,5 +2192,5 @@
 #endif
             bestIsSkip = rpcBestCU->getQtRootCbf(0) == 0;
-#if NH_3D_SDC_INTER
+#if NH_3D
             }
 #endif
@@ -2241,11 +2237,11 @@
   }
   DEBUG_STRING_APPEND(sDebug, bestStr)
-#if NH_3D_ARP
+
+#if NH_3D
  }
-#endif
-#if NH_3D_SPIVMP
  delete[] pcMvFieldSP;
  delete[] puhInterDirSP;
 #endif
+
 #if NH_MV
  D_DEC_INDENT( g_traceModeCheck );
@@ -2282,5 +2278,5 @@
 
   // prior to this, rpcTempCU will have just been reset using rpcTempCU->initEstData( uiDepth, iQP, bIsLosslessMode );
-#if NH_3D_ARP
+#if NH_3D
   const Bool bTransquantBypassFlag = rpcTempCU->getCUTransquantBypass(0);
 #endif
@@ -2290,12 +2286,9 @@
 #endif
   UChar uhDepth = rpcTempCU->getDepth( 0 );
-#if NH_3D_ARP
+#if NH_3D
     Bool bFirstTime = true;
     Int nARPWMax    = rpcTempCU->getSlice()->getARPStepNum() - 1;
-#if NH_3D_IC
+
     if( nARPWMax < 0 || ePartSize != SIZE_2Nx2N || rpcTempCU->getICFlag(0) )
-#else
-    if( nARPWMax < 0 || ePartSize != SIZE_2Nx2N )
-#endif
     {
       nARPWMax = 0;
@@ -2323,5 +2316,5 @@
       }
 #endif
-#if NH_3D_DIS
+#if NH_3D
       rpcTempCU->setDISFlagSubParts( false, 0, uhDepth );
 #endif
@@ -2329,8 +2322,11 @@
   rpcTempCU->setPredModeSubParts  ( MODE_INTER, 0, uhDepth );
   rpcTempCU->setChromaQpAdjSubParts( rpcTempCU->getCUTransquantBypass(0) ? 0 : m_cuChromaQpOffsetIdxPlus1, 0, uhDepth );
-#if NH_3D_ARP
+
+#if MCTS_ENC_CHECK
+  rpcTempCU->setTMctsMvpIsValid(true);
+#endif
+
+#if NH_3D
       rpcTempCU->setARPWSubParts( (UChar)nARPW , 0 , uhDepth );
-#endif
-#if NH_3D_ARP
       if( bFirstTime == false && nARPWMax )
       {
@@ -2355,5 +2351,5 @@
   m_pcPredSearch->predInterSearch ( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcRecoYuvTemp[uhDepth] );
 #endif
-#if NH_3D_ARP
+#if NH_3D
         if( nARPWMax )
         {
@@ -2366,5 +2362,5 @@
   if ( !rpcTempCU->getMergeAMP() )
   {
-#if NH_3D_ARP
+#if NH_3D
         if( nARPWMax )
         {
@@ -2391,6 +2387,14 @@
 #endif
 
+#if MCTS_ENC_CHECK
+  if (m_pcEncCfg->getTMCTSSEITileConstraint() && (!rpcTempCU->getTMctsMvpIsValid()))
+  {
+    return;
+  }
+#endif
+
+
   m_pcPredSearch->encodeResAndCalcRdInterCU( rpcTempCU, m_ppcOrigYuv[uhDepth], m_ppcPredYuvTemp[uhDepth], m_ppcResiYuvTemp[uhDepth], m_ppcResiYuvBest[uhDepth], m_ppcRecoYuvTemp[uhDepth], false DEBUG_STRING_PASS_INTO(sTest) );
-#if NH_3D_VSP
+#if NH_3D
   if( rpcTempCU->getQtRootCbf(0)==0 )
   {
@@ -2410,5 +2414,5 @@
   DebugInterPredResiReco(sTest, *(m_ppcPredYuvTemp[uhDepth]), *(m_ppcResiYuvBest[uhDepth]), *(m_ppcRecoYuvTemp[uhDepth]), DebugStringGetPredModeMask(rpcTempCU->getPredictionMode(0)));
 #endif
-#if NH_3D_SDC_INTER
+#if NH_3D
       TComDataCU *rpcTempCUPre = rpcTempCU;
 #endif
@@ -2416,5 +2420,5 @@
   xCheckDQP( rpcTempCU );
   xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth DEBUG_STRING_PASS_INTO(sDebug) DEBUG_STRING_PASS_INTO(sTest));
-#if NH_3D_SDC_INTER
+#if NH_3D
       if( rpcTempCU->getSlice()->getInterSdcFlag() && ePartSize == SIZE_2Nx2N)
       {
@@ -2445,7 +2449,5 @@
           }
           rpcTempCU->setSkipFlagSubParts( false, 0, uhDepth );
-#if NH_3D_DIS
           rpcTempCU->setDISFlagSubParts( false, 0, uhDepth );
-#endif
           rpcTempCU->setTrIdxSubParts( 0, 0, uhDepth );
           rpcTempCU->setCbfSubParts( 1, COMPONENT_Y, 0, uhDepth );
@@ -2487,6 +2489,4 @@
 
       }
-#endif
-#if NH_3D_ARP
     }
 #endif
@@ -2499,5 +2499,5 @@
 }
 
-#if NH_3D_DBBP
+#if NH_3D
 Void TEncCu::xInvalidateOriginalSegments( TComYuv* pOrigYuv, TComYuv* pOrigYuvTemp, Bool* pMask, UInt uiValidSegment )
 {
@@ -2558,7 +2558,5 @@
   }
 }
-#endif
-
-#if NH_3D_DBBP
+
 Void TEncCu::xCheckRDCostInterDBBP( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU  DEBUG_STRING_FN_DECLARE(sDebug), Bool bUseMRG )
 {
@@ -2583,10 +2581,8 @@
   AOF( uiWidth == uiHeight );
   
-#if NH_3D_DBBP
   if(uiWidth <= 8)
   {
     return;
   }
-#endif
   
   rpcTempCU->setPartSizeSubParts( SIZE_2Nx2N,  0, uhDepth );
@@ -2594,9 +2590,5 @@
   // fetch virtual depth block
   UInt uiDepthStride = 0;
-#if H_3D_FCO
-  Pel* pDepthPels = rpcTempCU->getVirtualDepthBlock(rpcTempCU->getZorderIdxInCU(), uiWidth, uiHeight, uiDepthStride);
-#else
   Pel* pDepthPels = rpcTempCU->getVirtualDepthBlock(0, uiWidth, uiHeight, uiDepthStride);
-#endif
   AOF( pDepthPels != NULL );
   AOF( uiDepthStride != 0 );
@@ -2643,8 +2635,6 @@
     pDBBPTmpData->auhMergeIndex[uiSegment] = rpcTempCU->getMergeIndex(0);
     
-#if NH_3D_VSP
     AOF( rpcTempCU->getSPIVMPFlag(0) == false );
     AOF( rpcTempCU->getVSPFlag(0) == 0 );
-#endif
     
     for ( UInt uiRefListIdx = 0; uiRefListIdx < 2; uiRefListIdx++ )
@@ -2698,6 +2688,5 @@
   xCheckBestMode(rpcBestCU, rpcTempCU, uhDepth  DEBUG_STRING_PASS_INTO(sDebug) DEBUG_STRING_PASS_INTO(sTest) );
 }
-#endif
-#if NH_3D_DIS
+
 Void TEncCu::xCheckRDCostDIS( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize eSize DEBUG_STRING_FN_DECLARE(sDebug) )
 {
@@ -2733,7 +2722,5 @@
   rpcTempCU->setDISFlagSubParts(true, 0, uiDepth);
   rpcTempCU->setIntraDirSubParts(CHANNEL_TYPE_LUMA, DC_IDX, 0, uiDepth);
-#if NH_3D_SDC_INTRA
   rpcTempCU->setSDCFlagSubParts( false, 0, uiDepth);
-#endif
 
   UInt uiPreCalcDistC;
@@ -2750,5 +2737,5 @@
 
   m_pcEntropyCoder->resetBits();
-  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnabledFlag())
   {
     m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
@@ -2782,5 +2769,5 @@
                                 PartSize     eSize
                                 DEBUG_STRING_FN_DECLARE(sDebug)
-#if NH_3D_ENC_DEPTH
+#if NH_3D
                               , Bool bOnlyIVP
 #endif
@@ -2798,4 +2785,5 @@
     }
   }
+
 #if NH_MV
   D_PRINT_INC_INDENT (g_traceModeCheck, "xCheckRDCostIntra; eSize: " + n2s(eSize) );
@@ -2815,5 +2803,5 @@
 
   rpcTempCU->setSkipFlagSubParts( false, 0, uiDepth );
-#if NH_3D_DIS
+#if NH_3D
   rpcTempCU->setDISFlagSubParts( false, 0, uiDepth );
 #endif
@@ -2827,5 +2815,5 @@
 
   m_pcPredSearch->estIntraPredLumaQT( rpcTempCU, m_ppcOrigYuv[uiDepth], m_ppcPredYuvTemp[uiDepth], m_ppcResiYuvTemp[uiDepth], m_ppcRecoYuvTemp[uiDepth], resiLuma DEBUG_STRING_PASS_INTO(sTest) 
-#if NH_3D_ENC_DEPTH
+#if NH_3D
                                     , bOnlyIVP
 #endif
@@ -2839,5 +2827,5 @@
   }
   
-#if NH_3D_SDC_INTRA
+#if NH_3D
   if( rpcTempCU->getSDCFlag( 0 ) )
   {
@@ -2849,10 +2837,10 @@
   m_pcEntropyCoder->resetBits();
 
-  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnabledFlag())
   {
     m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
   }
   m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
-#if NH_3D_DIS
+#if NH_3D
   m_pcEntropyCoder->encodeDIS( rpcTempCU, 0,          true );
   if(!rpcTempCU->getDISFlag(0))
@@ -2863,5 +2851,5 @@
     m_pcEntropyCoder->encodePredInfo( rpcTempCU, 0 );
     m_pcEntropyCoder->encodeIPCMInfo(rpcTempCU, 0, true );
-#if NH_3D_SDC_INTRA
+#if NH_3D
     m_pcEntropyCoder->encodeSDCFlag( rpcTempCU, 0, true );
 #endif
@@ -2873,5 +2861,5 @@
     setCodeChromaQpAdjFlag( codeChromaQpAdjFlag );
     setdQPFlag( bCodeDQP );
-#if NH_3D_DIS
+#if NH_3D
   }
 #endif
@@ -2931,5 +2919,5 @@
 #endif
   rpcTempCU->setSkipFlagSubParts( false, 0, uiDepth );
-#if NH_3D_DIS
+#if NH_3D
   rpcTempCU->setDISFlagSubParts( false, 0, uiDepth );
 #endif
@@ -2947,5 +2935,5 @@
   m_pcEntropyCoder->resetBits();
 
-  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+  if ( rpcTempCU->getSlice()->getPPS()->getTransquantBypassEnabledFlag())
   {
     m_pcEntropyCoder->encodeCUTransquantBypassFlag( rpcTempCU, 0,          true );
@@ -2953,5 +2941,5 @@
 
   m_pcEntropyCoder->encodeSkipFlag ( rpcTempCU, 0,          true );
-#if NH_3D_DIS
+#if NH_3D
   m_pcEntropyCoder->encodeDIS( rpcTempCU, 0,          true );
 #endif
@@ -2959,5 +2947,5 @@
   m_pcEntropyCoder->encodePartSize ( rpcTempCU, 0, uiDepth, true );
   m_pcEntropyCoder->encodeIPCMInfo ( rpcTempCU, 0, true );
-#if NH_3D_SDC_INTRA
+#if NH_3D
   m_pcEntropyCoder->encodeSDCFlag( rpcTempCU, 0, true );
 #endif
Index: /trunk/source/Lib/TLibEncoder/TEncCu.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncCu.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncCu.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -69,5 +69,5 @@
   TComDataCU**            m_ppcBestCU;      ///< Best CUs in each depth
   TComDataCU**            m_ppcTempCU;      ///< Temporary CUs in each depth
-#if NH_3D_ARP
+#if NH_3D
   TComDataCU**            m_ppcWeightedTempCU;
 #endif
@@ -82,5 +82,5 @@
   TComYuv**               m_ppcOrigYuv;     ///< Original Yuv for each depth
 
-#if NH_3D_DBBP
+#if NH_3D
   TComYuv**               m_ppcOrigYuvDBBP;
 #endif
@@ -91,4 +91,7 @@
   Bool                    m_stillToCodeChromaQpOffsetFlag; //indicates whether chroma QP offset flag needs to coded at this particular CU granularity.
   Int                     m_cuChromaQpOffsetIdxPlus1; // if 0, then cu_chroma_qp_offset_flag will be 0, otherwise cu_chroma_qp_offset_flag will be 1.
+  Int                     m_lumaLevelToDeltaQPLUT[LUMA_LEVEL_TO_DQP_LUT_MAXSIZE];
+  Int                     m_lumaQPOffset;
+  TEncSlice*              m_pcSliceEncoder;
 
   //  Access channel
@@ -116,4 +119,9 @@
   Void  init                ( TEncTop* pcEncTop );
 
+  Void       setSliceEncoder( TEncSlice* pSliceEncoder ) { m_pcSliceEncoder = pSliceEncoder; }
+  TEncSlice* getSliceEncoder() { return m_pcSliceEncoder; }
+  Void       initLumaDeltaQpLUT();
+  Int        calculateLumaDQP( TComDataCU *pCU, const UInt absPartIdx, const TComYuv * pOrgYuv );
+
   /// create internal buffers
   Void  create              ( UChar uhTotalDepth, UInt iMaxWidth, UInt iMaxHeight, ChromaFormat chromaFormat );
@@ -158,9 +166,7 @@
   Void  xCheckRDCostInter   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize  );
 #endif
-#if NH_3D_DBBP
+#if NH_3D
   Void  xInvalidateOriginalSegments( TComYuv* pOrigYuv, TComYuv* pOrigYuvTemp, Bool* pMask, UInt uiValidSegment );
   Void  xCheckRDCostInterDBBP( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU  DEBUG_STRING_FN_DECLARE(sDebug),  Bool bUseMRG = false );
-#endif
-#if NH_3D_DIS
   Void  xCheckRDCostDIS   ( TComDataCU*& rpcBestCU, TComDataCU*& rpcTempCU, PartSize ePartSize DEBUG_STRING_FN_DECLARE(sDebug) );
 #endif
@@ -169,5 +175,5 @@
                               PartSize     ePartSize
                               DEBUG_STRING_FN_DECLARE(sDebug)
-#if NH_3D_ENC_DEPTH
+#if NH_3D
                             , Bool bOnlyIVP
 #endif
Index: /trunk/source/Lib/TLibEncoder/TEncEntropy.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncEntropy.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -116,5 +116,5 @@
   m_pcEntropyCoderIf->codeSkipFlag( pcCU, uiAbsPartIdx );
 }
-#if NH_3D_DIS
+#if NH_3D
 Void TEncEntropy::encodeDIS( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
 {
@@ -148,12 +148,8 @@
 }
 
-#if NH_3D_IC
+#if NH_3D
 Void TEncEntropy::encodeICFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
 {
-#if NH_3D_ARP
   if ( pcCU->isIntra( uiAbsPartIdx ) || ( pcCU->getSlice()->getViewIndex() == 0 ) || pcCU->getSlice()->getIsDepth() || pcCU->getARPW( uiAbsPartIdx ) > 0 )
-#else
-  if ( pcCU->isIntra( uiAbsPartIdx ) || ( pcCU->getSlice()->getViewIndex() == 0 ) || pcCU->getSlice()->getIsDepth() )
-#endif
   {
     return;
@@ -186,7 +182,5 @@
   }
 }
-#endif
-
-#if NH_3D_ARP
+
 Void TEncEntropy::encodeARPW( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
@@ -715,5 +709,5 @@
 #endif
 
-#if NH_3D_SDC_INTRA
+#if NH_3D
   if( pcCU->getSDCFlag( uiAbsPartIdx ) && pcCU->isIntra( uiAbsPartIdx ) )
   {
@@ -722,6 +716,5 @@
     assert( pcCU->getCbf(uiAbsPartIdx, COMPONENT_Y) == 1 );
   }
-#endif
-#if NH_3D_SDC_INTER
+
   if( pcCU->getSDCFlag( uiAbsPartIdx ) && !pcCU->isIntra( uiAbsPartIdx ) )
   {
@@ -730,9 +723,6 @@
     assert( pcCU->getSlice()->getIsDepth() );
   }
-#endif
-#if NH_3D
   if( pcCU->getSlice()->getIsDepth() )
   {
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
     if( pcCU->getSDCFlag( uiAbsPartIdx ) )
     {
@@ -740,6 +730,4 @@
       return;
     }
-#endif
-#if NH_3D_DMM
     if( pcCU->isIntra(uiAbsPartIdx) )
   {
@@ -754,5 +742,4 @@
       }
     }
-#endif
   }
 #endif
@@ -832,9 +819,9 @@
 }
 
-Void TEncEntropy::estimateBit (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, const ChannelType chType)
+Void TEncEntropy::estimateBit (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, const ChannelType chType, COEFF_SCAN_TYPE scanType )
 {
   const UInt heightAtEntropyCoding = (width != height) ? (height >> 1) : height;
 
-  m_pcEntropyCoderIf->estBit ( pcEstBitsSbac, width, heightAtEntropyCoding, chType );
+  m_pcEntropyCoderIf->estBit ( pcEstBitsSbac, width, heightAtEntropyCoding, chType, scanType );
 }
 
@@ -851,11 +838,10 @@
 }
 
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
+#if NH_3D
 Void TEncEntropy::encodeDeltaDC  ( TComDataCU* pcCU, UInt absPartIdx )
 {
   m_pcEntropyCoderIf->codeDeltaDC( pcCU, absPartIdx );
 }
-#endif
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
+
 Void TEncEntropy::encodeSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
 {
@@ -881,6 +867,5 @@
 }
 
-#endif
-#if NH_3D_DBBP
+
 Void TEncEntropy::encodeDBBPFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD )
 {
Index: /trunk/source/Lib/TLibEncoder/TEncEntropy.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncEntropy.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncEntropy.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -79,22 +79,14 @@
   virtual Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
   virtual Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
-#if NH_3D_DIS
+#if NH_3D
   virtual Void codeDIS          ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
 #endif
   virtual Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
   virtual Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
+#if NH_3D
   virtual Void codeDeltaDC       ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
-#endif
-#if NH_3D_ARP  
   virtual Void codeARPW          ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
-#endif
-#if NH_3D_IC
   virtual Void codeICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
-#endif
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   virtual Void codeSDCFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
-#endif
-#if NH_3D_DBBP
   virtual Void codeDBBPFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx ) = 0;
 #endif
@@ -125,5 +117,5 @@
   virtual Void codeTransformSkipFlags ( TComTU &rTu, ComponentID component ) = 0;
   virtual Void codeSAOBlkParam   (SAOBlkParam& saoBlkParam, const BitDepths &bitDepths, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail, Bool onlyEstMergeInfo = false)    =0;
-  virtual Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType) = 0;
+  virtual Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType, COEFF_SCAN_TYPE scanType) = 0;
 
   virtual Void codeExplicitRdpcmMode ( TComTU &rTu, const ComponentID compID ) = 0;
@@ -163,5 +155,5 @@
   Void encodeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
   Void encodeSkipFlag          ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
-#if NH_3D_DIS
+#if NH_3D
   Void encodeDIS               ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD=false );
 #endif
@@ -173,17 +165,9 @@
   Void encodeMergeFlag    ( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void encodeMergeIndex   ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
-#if NH_3D_ARP
+#if NH_3D
   Void encodeARPW         ( TComDataCU* pcCU, UInt uiAbspartIdx );
-#endif
-#if NH_3D_IC
   Void encodeICFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
-#endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   Void encodeDeltaDC      ( TComDataCU* pcCU, UInt absPartIdx );
-#endif
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   Void encodeSDCFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
-#endif
-#if NH_3D_DBBP
   Void encodeDBBPFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx, Bool bRD = false );
 #endif
@@ -215,5 +199,5 @@
   Void encodeCoeffNxN         ( TComTU &rTu, TCoeff* pcCoef, const ComponentID compID );
 
-  Void estimateBit             ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType );
+  Void estimateBit             ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType, COEFF_SCAN_TYPE scanType);
 
   Void encodeSAOBlkParam(SAOBlkParam& saoBlkParam, const BitDepths &bitDepths, Bool* sliceEnabled, Bool leftMergeAvail, Bool aboveMergeAvail){m_pcEntropyCoderIf->codeSAOBlkParam(saoBlkParam, bitDepths, sliceEnabled, leftMergeAvail, aboveMergeAvail, false);}
Index: /trunk/source/Lib/TLibEncoder/TEncGOP.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncGOP.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -108,8 +108,5 @@
   m_associatedIRAPType = NAL_UNIT_CODED_SLICE_IDR_N_LP;
   m_associatedIRAPPOC  = 0;
-#if W0038_DB_OPT
   m_pcDeblockingTempPicYuv = NULL;
-#endif
-  return;
 }
 
@@ -128,5 +125,4 @@
 Void  TEncGOP::destroy()
 {
-#if W0038_DB_OPT
   if (m_pcDeblockingTempPicYuv)
   {
@@ -135,5 +131,4 @@
     m_pcDeblockingTempPicYuv = NULL;
   }
-#endif
 }
 
@@ -161,10 +156,10 @@
   m_layerId              = pcTEncTop->getLayerId();
   m_viewId               = pcTEncTop->getViewId();
+#endif
+
 #if NH_3D
   m_viewIndex            = pcTEncTop->getViewIndex();
   m_isDepth              = pcTEncTop->getIsDepth();
-#endif
-#endif
-#if NH_3D_IC
+
   m_aICEnableCandidate   = pcTEncTop->getICEnableCandidate();
   m_aICEnableNum         = pcTEncTop->getICEnableNum();
@@ -212,18 +207,32 @@
 
 
-Int TEncGOP::xWriteParameterSets (AccessUnit &accessUnit, TComSlice *slice)
+#if NH_MV
+Int TEncGOP::xWriteParameterSets (AccessUnit &accessUnit, TComSlice *slice, const Bool bSeqFirst, const Bool bWriteVps )
+#else
+Int TEncGOP::xWriteParameterSets (AccessUnit &accessUnit, TComSlice *slice, const Bool bSeqFirst)
+#endif
 {
   Int actualTotalBits = 0;
 
 #if NH_MV
-  if ( getLayerId() == 0 )
+  if ( bWriteVps )
   {
     actualTotalBits += xWriteVPS(accessUnit, m_pcEncTop->getVPS());
   }
 #else
-  actualTotalBits += xWriteVPS(accessUnit, m_pcEncTop->getVPS());
-#endif
-  actualTotalBits += xWriteSPS(accessUnit, slice->getSPS());
-  actualTotalBits += xWritePPS(accessUnit, slice->getPPS());
+  if (bSeqFirst)
+  {
+    actualTotalBits += xWriteVPS(accessUnit, m_pcEncTop->getVPS());
+  }
+#endif
+  if (m_pcEncTop->SPSNeedsWriting(slice->getSPS()->getSPSId())) // Note this assumes that all changes to the SPS are made at the TEncTop level prior to picture creation (TEncTop::xGetNewPicBuffer).
+  {
+    assert(bSeqFirst); // Implementations that use more than 1 SPS need to be aware of activation issues.
+    actualTotalBits += xWriteSPS(accessUnit, slice->getSPS());
+  }
+  if (m_pcEncTop->PPSNeedsWriting(slice->getPPS()->getPPSId())) // Note this assumes that all changes to the PPS are made at the TEncTop level prior to picture creation (TEncTop::xGetNewPicBuffer).
+  {
+    actualTotalBits += xWritePPS(accessUnit, slice->getPPS());
+  }
 
   return actualTotalBits;
@@ -513,5 +522,4 @@
     seiMessages.push_back(seiChromaResamplingFilterHint);
   }
-#if U0033_ALTERNATIVE_TRANSFER_CHARACTERISTICS_SEI
   if(m_pcCfg->getSEIAlternativeTransferCharacteristicsSEIEnable())
   {
@@ -520,5 +528,4 @@
     seiMessages.push_back(seiAlternativeTransferCharacteristics);
   }
-#endif
 }
 
@@ -555,5 +562,5 @@
     {
       // Gradual decoding refresh SEI
-      SEIGradualDecodingRefreshInfo *gradualDecodingRefreshInfoSEI = new SEIGradualDecodingRefreshInfo();
+      SEIRegionRefreshInfo *gradualDecodingRefreshInfoSEI = new SEIRegionRefreshInfo();
       gradualDecodingRefreshInfoSEI->m_gdrForegroundFlag = true; // Indicating all "foreground"
       seiMessages.push_back(gradualDecodingRefreshInfoSEI);
@@ -1046,4 +1053,13 @@
 
 
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+static UInt calculateCollocatedFromL0Flag(const TComSlice *pSlice)
+{
+  const Int refIdx = 0; // Zero always assumed
+  const TComPic *refPicL0 = pSlice->getRefPic(REF_PIC_LIST_0, refIdx);
+  const TComPic *refPicL1 = pSlice->getRefPic(REF_PIC_LIST_1, refIdx);
+  return refPicL0->getSlice(0)->getSliceQp() > refPicL1->getSlice(0)->getSliceQp();
+}
+#else
 static UInt calculateCollocatedFromL1Flag(TEncCfg *pCfg, const Int GOPid, const Int gopSize)
 {
@@ -1094,4 +1110,5 @@
   }
 }
+#endif
 
 
@@ -1141,9 +1158,14 @@
 Void TEncGOP::compressPicInGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic,
                                 TComList<TComPicYuv*>& rcListPicYuvRecOut,  std::list<AccessUnit>& accessUnitsInGOP,
-                                Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, Int iGOPid )
+                                Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, const Bool printMSSSIM, Int iGOPid )
 #else
 Void TEncGOP::compressGOP( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic,
                            TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP,
+#if JVET_F0064_MSSSIM            
+                           Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, const Bool printMSSSIM )
+#else
+
                            Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE )
+#endif
 #endif
 {
@@ -1193,5 +1215,7 @@
     clock_t iBeforeTime = clock();
 
+#if !X0038_LAMBDA_FROM_QP_CAPABILITY
     UInt uiColDir = calculateCollocatedFromL1Flag(m_pcCfg, iGOPid, m_iGopSize);
+#endif
 
     /////////////////////////////////////////////////////////////////////////////////////////////////// Initial to start encoding
@@ -1237,4 +1261,8 @@
     xGetBuffer( rcListPic, rcListPicYuvRecOut, iNumPicRcvd, iTimeOffset, pcPic, pcPicYuvRecOut, pocCurr, isField );
 
+#if REDUCED_ENCODER_MEMORY
+    pcPic->prepareForReconstruction();
+
+#endif
     //  Slice data initialization
     pcPic->clearSliceBuffer();
@@ -1247,7 +1275,4 @@
     m_pcSliceEncoder->initEncSlice ( pcPic, iPOCLast, pocCurr, iGOPid, pcSlice, isField );
 #endif
-
-    //Set Frame/Field coding
-    pcSlice->getPic()->setField(isField);
 
     pcSlice->setLastIDR(m_iLastIDR);
@@ -1441,10 +1466,7 @@
     Int numDirectRefLayers = vps    ->getNumDirectRefLayers( getLayerId() );
 #endif
-#if NH_3D_QTL
+
+#if NH_3D
     pcSlice->setIvPicLists( m_ivPicLists );
-#endif
-#if NH_3D
-
-
     Int gopNum = (pcSlice->getRapPicFlag() && getLayerId() > 0) ? MAX_GOP : iGOPid;
     GOPEntry gopEntry      = m_pcCfg->getGOPEntry( gopNum );
@@ -1517,8 +1539,6 @@
       pcSlice->checkInCompPredRefLayers();
     }
-#if NH_3D_IV_MERGE
     // This needs to be done after initialization of 3D tool parameters.
     pcSlice->setMaxNumMergeCand      ( m_pcCfg->getMaxNumMergeCand()   + ( ( pcSlice->getMpiFlag( ) || pcSlice->getIvMvPredFlag( ) || pcSlice->getViewSynthesisPredFlag( )   ) ? 1 : 0 ));
-#endif
 #endif
 
@@ -1545,12 +1565,8 @@
     pcSlice->setRefPicList ( rcListPic );
 #endif
-#if NH_3D_NBDV
+#if NH_3D
     pcSlice->setDefaultRefView();
-#endif
-#if NH_3D_ARP
     //GT: This seems to be broken when layerId in vps is not equal to layerId in nuh
     pcSlice->setARPStepNum(m_ivPicLists);
-#endif
-#if NH_3D_IC
     pcSlice->setICEnableCandidate( m_aICEnableCandidate );
     pcSlice->setICEnableNum( m_aICEnableNum );
@@ -1576,5 +1592,10 @@
     if (pcSlice->getSliceType() == B_SLICE)
     {
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+      const UInt uiColFromL0 = calculateCollocatedFromL0Flag(pcSlice);
+      pcSlice->setColFromL0Flag(uiColFromL0);
+#else
       pcSlice->setColFromL0Flag(1-uiColDir);
+#endif
       Bool bLowDelay = true;
       Int  iCurrPOC  = pcSlice->getPOC();
@@ -1603,5 +1624,7 @@
     }
 
+#if !X0038_LAMBDA_FROM_QP_CAPABILITY
     uiColDir = 1-uiColDir;
+#endif
 
     //-------------------------------------------------------------
@@ -1609,5 +1632,5 @@
 
     pcSlice->setList1IdxToList0Idx();
-#if NH_3D_TMVP
+#if NH_3D
     if(pcSlice->getLayerId())
       pcSlice->generateAlterRefforTMVP();
@@ -1659,10 +1682,4 @@
 
     // SAIT_VSO_EST_A0033
-#if H_3D_FCO
-    Bool flagRec;
-    flagRec =  ((m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), false, pcSlice->getPOC(), true) == NULL) ? false: true);
-    pcRdCost->setVideoRecPicYuv( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), false, pcSlice->getPOC(), flagRec ) );
-    pcRdCost->setDepthPicYuv   ( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), true, pcSlice->getPOC(), false ) );
-#else    
     Int curAuxId     = pcSlice->getVPS()->getAuxId( getLayerId() ); 
     Int curDepthFlag = pcSlice->getIsDepth(); 
@@ -1670,5 +1687,5 @@
     pcRdCost->setVideoRecPicYuv( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), false       , 0       , pcSlice->getPOC(), true ) );
     pcRdCost->setDepthPicYuv   ( m_pcEncTop->getIvPicLists()->getPicYuv( pcSlice->getViewIndex(), curDepthFlag, curAuxId, pcSlice->getPOC(), false ) );
-#endif
+
     // LGE_WVSO_A0119
     Bool bUseWVSO  = m_pcEncTop->getUseWVSO();
@@ -1708,5 +1725,4 @@
       pcSlice->setMvdL1ZeroFlag(false);
     }
-    pcPic->getSlice(pcSlice->getSliceIdx())->setMvdL1ZeroFlag(pcSlice->getMvdL1ZeroFlag());
 
 
@@ -1733,5 +1749,4 @@
 #endif
 
-#if U0132_TARGET_BITS_SATURATION
       if (m_pcRateCtrl->getCpbSaturationEnabled() && frameLevel != 0)
       {
@@ -1746,19 +1761,10 @@
         estimatedCpbFullness -= m_pcRateCtrl->getBufferingRate();
         // prevent underflow
-#if V0078_ADAPTIVE_LOWER_BOUND
         if (estimatedCpbFullness - estimatedBits < m_pcRateCtrl->getRCPic()->getLowerBound())
         {
           estimatedBits = max(200, estimatedCpbFullness - m_pcRateCtrl->getRCPic()->getLowerBound());
         }
-#else
-        if (estimatedCpbFullness - estimatedBits < (Int)(m_pcRateCtrl->getCpbSize()*0.1f))
-        {
-          estimatedBits = max(200, estimatedCpbFullness - (Int)(m_pcRateCtrl->getCpbSize()*0.1f));
-        }
-#endif
-
         m_pcRateCtrl->getRCPic()->setTargetBits(estimatedBits);
       }
-#endif
 
       Int sliceQP = m_pcCfg->getInitialQP();
@@ -1782,5 +1788,4 @@
           bits = m_pcRateCtrl->getRCPic()->getRefineBitsForIntra( bits );
 
-#if U0132_TARGET_BITS_SATURATION
           if (m_pcRateCtrl->getCpbSaturationEnabled() )
           {
@@ -1795,17 +1800,9 @@
             estimatedCpbFullness -= m_pcRateCtrl->getBufferingRate();
             // prevent underflow
-#if V0078_ADAPTIVE_LOWER_BOUND
             if (estimatedCpbFullness - bits < m_pcRateCtrl->getRCPic()->getLowerBound())
             {
               bits = estimatedCpbFullness - m_pcRateCtrl->getRCPic()->getLowerBound();
             }
-#else
-            if (estimatedCpbFullness - bits < (Int)(m_pcRateCtrl->getCpbSize()*0.1f))
-            {
-              bits = estimatedCpbFullness - (Int)(m_pcRateCtrl->getCpbSize()*0.1f);
-            }
-#endif
           }
-#endif
 
           if ( bits < 200 )
@@ -1849,5 +1846,5 @@
     UInt uiNumSliceSegments = 1;
 
-#if NH_3D_NBDV
+#if NH_3D
       if(pcSlice->getViewIndex() && !pcSlice->getIsDepth()) //Notes from QC: this condition shall be changed once the configuration is completed, e.g. in pcSlice->getSPS()->getMultiviewMvPredMode() || ARP in prev. HTM. Remove this comment once it is done.
       {
@@ -1855,11 +1852,6 @@
         pcPic->setNumDdvCandPics(pcPic->getDisCandRefPictures(iColPoc));
       }
-#endif
-#if NH_3D
       pcSlice->setDepthToDisparityLUTs();
 
-#endif
-
-#if NH_3D_NBDV
       if(pcSlice->getViewIndex() && !pcSlice->getIsDepth() && !pcSlice->isIntra()) //Notes from QC: this condition shall be changed once the configuration is completed, e.g. in pcSlice->getSPS()->getMultiviewMvPredMode() || ARP in prev. HTM. Remove this comment once it is done.
       {
@@ -1935,5 +1927,4 @@
     if ( m_pcCfg->getDeblockingFilterMetric() )
     {
-#if W0038_DB_OPT
       if ( m_pcCfg->getDeblockingFilterMetric()==2 )
       {
@@ -1942,9 +1933,6 @@
       else
       {
-#endif
       applyDeblockingFilterMetric(pcPic, uiNumSliceSegments);
-#if W0038_DB_OPT
-      }
-#endif
+      }
     }
     m_pcLoopFilter->loopFilterPic( pcPic );
@@ -1953,17 +1941,43 @@
     // Set entropy coder
     m_pcEntropyCoder->setEntropyCoder   ( m_pcCavlcCoder );
+
+    // write various parameter sets
+#if JCTVC_Y0038_PARAMS
+    //bool writePS = m_bSeqFirst || (m_pcCfg->getReWriteParamSetsFlag() && (pcPic->getSlice(0)->getSliceType() == I_SLICE));
+#if NH_MV
+    bool writePS = m_bSeqFirst || (m_pcCfg->getReWriteParamSetsFlag() && (pcSlice->isIRAP())  );
+#else
+    bool writePS = m_bSeqFirst || (m_pcCfg->getReWriteParamSetsFlag() && (pcSlice->isIRAP()));
+#endif 
+    if (writePS)
+    {
+#if NH_MV
+      if ( m_layerId == pcSlice->getSPS()->getLayerId() )
+      {
+        m_pcEncTop->setParamSetChanged(pcSlice->getSPS()->getSPSId(), false );
+      }
+      
+      if ( m_layerId == pcSlice->getPPS()->getLayerId() )
+      {
+        m_pcEncTop->setParamSetChanged(pcSlice->getPPS()->getSPSId(), true  );        
+      }
+
+#else
+      m_pcEncTop->setParamSetChanged(pcSlice->getSPS()->getSPSId(), pcSlice->getPPS()->getPPSId());
+#endif
+    }
+#if NH_MV
+    actualTotalBits += xWriteParameterSets(accessUnit, pcSlice, writePS, (getLayerId() == 0) && m_bSeqFirst );
+#else
+    actualTotalBits += xWriteParameterSets(accessUnit, pcSlice, writePS);
+#endif
+
+    if (writePS)
+#else
+    actualTotalBits += xWriteParameterSets(accessUnit, pcSlice, m_bSeqFirst);
+
     if ( m_bSeqFirst )
-    {
-      // write various parameter sets
-      actualTotalBits += xWriteParameterSets(accessUnit, pcSlice);
-#if H_3D_PPS_FIX_DEPTH
-      if(!pcSlice->getIsDepth() || !pcSlice->getViewIndex() )
-      {
-#endif
-#if H_3D_PPS_FIX_DEPTH
-      }
-#endif
-
-
+#endif
+    {
       // create prefix SEI messages at the beginning of the sequence
       assert(leadingSeiMessages.empty());
@@ -1998,5 +2012,4 @@
       m_pcEncTop->getRDGoOnSbacCoder()->setBitstream(&tempBitCounter);
       m_pcSAO->initRDOCabacCoder(m_pcEncTop->getRDGoOnSbacCoder(), pcSlice);
-#if OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP
       m_pcSAO->SAOProcess(pcPic, sliceEnabled, pcPic->getSlice(0)->getLambdas(),
                           m_pcCfg->getTestSAODisableAtPictureLevel(),
@@ -2005,7 +2018,4 @@
                           m_pcCfg->getSaoCtuBoundary(),
                           m_pcCfg->getSaoResetEncoderStateAfterIRAP());
-#else
-      m_pcSAO->SAOProcess(pcPic, sliceEnabled, pcPic->getSlice(0)->getLambdas(), m_pcCfg->getTestSAODisableAtPictureLevel(), m_pcCfg->getSaoEncodingRate(), m_pcCfg->getSaoEncodingRateChroma(), m_pcCfg->getSaoCtuBoundary());
-#endif
       m_pcSAO->PCMLFDisableProcess(pcPic);
       m_pcEncTop->getRDGoOnSbacCoder()->setBitstream(NULL);
@@ -2158,9 +2168,23 @@
       trailingSeiMessages.push_back(decodedPictureHashSei);
     }
+
+    m_pcCfg->setEncodedFlag(iGOPid, true);
+
+    Double PSNR_Y;
+#if JVET_F0064_MSSSIM
+    xCalculateAddPSNRs( isField, isTff, iGOPid, pcPic, accessUnit, rcListPic, dEncTime, snr_conversion, printFrameMSE, printMSSSIM, &PSNR_Y );
+#else
+    xCalculateAddPSNRs( isField, isTff, iGOPid, pcPic, accessUnit, rcListPic, dEncTime, snr_conversion, printFrameMSE, &PSNR_Y );
+#endif
+    
+    // Only produce the Green Metadata SEI message with the last picture.
+    if( m_pcCfg->getSEIGreenMetadataInfoSEIEnable() && pcSlice->getPOC() == ( m_pcCfg->getFramesToBeEncoded() - 1 )  )
+    {
+      SEIGreenMetadataInfo *seiGreenMetadataInfo = new SEIGreenMetadataInfo;
+      m_seiEncoder.initSEIGreenMetadataInfo(seiGreenMetadataInfo, (UInt)(PSNR_Y * 100 + 0.5));
+      trailingSeiMessages.push_back(seiGreenMetadataInfo);
+    }
+    
     xWriteTrailingSEIMessages(trailingSeiMessages, accessUnit, pcSlice->getTLayer(), pcSlice->getSPS());
-
-    m_pcCfg->setEncodedFlag(iGOPid, true);
-
-    xCalculateAddPSNRs( isField, isTff, iGOPid, pcPic, accessUnit, rcListPic, dEncTime, snr_conversion, printFrameMSE );
 
     printHash(m_pcCfg->getDecodedPictureHashSEIType(), digestStr);
@@ -2187,5 +2211,4 @@
         m_pcRateCtrl->getRCGOP()->updateAfterPicture( estimatedBits );
       }
-#if U0132_TARGET_BITS_SATURATION
       if (m_pcRateCtrl->getCpbSaturationEnabled())
       {
@@ -2193,5 +2216,4 @@
         printf(" [CPB %6d bits]", m_pcRateCtrl->getCpbState());
       }
-#endif
     }
 
@@ -2223,4 +2245,13 @@
     iGOPid=effFieldIRAPMap.restoreGOPid(iGOPid);
     }
+#if REDUCED_ENCODER_MEMORY
+
+    pcPic->releaseReconstructionIntermediateData();
+    if (!isField) // don't release the source data for field-coding because the fields are dealt with in pairs. // TODO: release source data for interlace simulations.
+    {
+      pcPic->releaseEncoderSourceImageData();
+    }
+
+#endif
   } // iGOPid-loop
 
@@ -2232,5 +2263,9 @@
 }
 
+#if JVET_F0064_MSSSIM
+Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded, Bool isField, const Bool printMSEBasedSNR, const Bool printSequenceMSE, const Bool printMSSSIM, const BitDepths &bitDepths)
+#else
 Void TEncGOP::printOutSummary(UInt uiNumAllPicCoded, Bool isField, const Bool printMSEBasedSNR, const Bool printSequenceMSE, const BitDepths &bitDepths)
+#endif
 {
   assert (uiNumAllPicCoded == m_gcAnalyzeAll.getNumPic());
@@ -2245,4 +2280,6 @@
   const ChromaFormat chFmt = m_pcCfg->getChromaFormatIdc();
 
+
+#if JVET_F0064_MSSSIM
   //-- all
 #if NH_MV
@@ -2251,4 +2288,22 @@
   printf( "\n\nSUMMARY --------------------------------------------------------\n" );
 #endif
+  m_gcAnalyzeAll.printOut('a', chFmt, printMSEBasedSNR, printSequenceMSE, printMSSSIM, bitDepths);
+
+  printf( "\n\nI Slices--------------------------------------------------------\n" );
+  m_gcAnalyzeI.printOut('i', chFmt, printMSEBasedSNR, printSequenceMSE, printMSSSIM, bitDepths);
+
+  printf( "\n\nP Slices--------------------------------------------------------\n" );
+  m_gcAnalyzeP.printOut('p', chFmt, printMSEBasedSNR, printSequenceMSE, printMSSSIM, bitDepths);
+
+  printf( "\n\nB Slices--------------------------------------------------------\n" );
+  m_gcAnalyzeB.printOut('b', chFmt, printMSEBasedSNR, printSequenceMSE, printMSSSIM, bitDepths);
+#else
+  //-- all
+#if NH_MV
+  printf( "\n\nSUMMARY -------------------------------------------- LayerId %2d\n", getLayerId() );
+#else
+  printf( "\n\nSUMMARY --------------------------------------------------------\n" );
+#endif
+
   m_gcAnalyzeAll.printOut('a', chFmt, printMSEBasedSNR, printSequenceMSE, bitDepths);
 
@@ -2261,5 +2316,5 @@
   printf( "\n\nB Slices--------------------------------------------------------\n" );
   m_gcAnalyzeB.printOut('b', chFmt, printMSEBasedSNR, printSequenceMSE, bitDepths);
-
+#endif
   if (!m_pcCfg->getSummaryOutFilename().empty())
   {
@@ -2277,14 +2332,14 @@
   {
     //-- interlaced summary
-#if TEMPORAL_SUBSAMPLE
     m_gcAnalyzeAll_in.setFrmRate( m_pcCfg->getFrameRate() / (Double)m_pcCfg->getTemporalSubsampleRatio());
-#else
-    m_gcAnalyzeAll_in.setFrmRate( m_pcCfg->getFrameRate());
-#endif
     m_gcAnalyzeAll_in.setBits(m_gcAnalyzeAll.getBits());
     // prior to the above statement, the interlace analyser does not contain the correct total number of bits.
 
     printf( "\n\nSUMMARY INTERLACED ---------------------------------------------\n" );
+#if JVET_F0064_MSSSIM
+    m_gcAnalyzeAll_in.printOut('a', chFmt, printMSEBasedSNR, printSequenceMSE, printMSSSIM, bitDepths);
+#else
     m_gcAnalyzeAll_in.printOut('a', chFmt, printMSEBasedSNR, printSequenceMSE, bitDepths);
+#endif
 
     if (!m_pcCfg->getSummaryOutFilename().empty())
@@ -2374,7 +2429,5 @@
   }
 
-#if !NH_MV
   assert (rpcPic != NULL);
-#endif
   assert (rpcPic->getPOC() == pocCurr);
 
@@ -2420,7 +2473,13 @@
 }
 
-Void TEncGOP::xCalculateAddPSNRs( const Bool isField, const Bool isFieldTopFieldFirst, const Int iGOPid, TComPic* pcPic, const AccessUnit&accessUnit, TComList<TComPic*> &rcListPic, const Double dEncTime, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE )
-{
-  xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime, snr_conversion, printFrameMSE );
+#if JVET_F0064_MSSSIM
+Void TEncGOP::xCalculateAddPSNRs( const Bool isField, const Bool isFieldTopFieldFirst, const Int iGOPid, TComPic* pcPic, const AccessUnit&accessUnit, TComList<TComPic*> &rcListPic, const Double dEncTime, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, const Bool printMSSSIM, Double* PSNR_Y )
+{
+  xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime, snr_conversion, printFrameMSE, printMSSSIM, PSNR_Y );
+#else
+Void TEncGOP::xCalculateAddPSNRs( const Bool isField, const Bool isFieldTopFieldFirst, const Int iGOPid, TComPic* pcPic, const AccessUnit&accessUnit, TComList<TComPic*> &rcListPic, const Double dEncTime, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, Double* PSNR_Y )
+{
+  xCalculateAddPSNR( pcPic, pcPic->getPicYuvRec(), accessUnit, dEncTime, snr_conversion, printFrameMSE, PSNR_Y );
+#endif
 
   //In case of field coding, compute the interlaced PSNR for both fields
@@ -2477,15 +2536,27 @@
       if( (pcPic->isTopField() && isFieldTopFieldFirst) || (!pcPic->isTopField() && !isFieldTopFieldFirst))
       {
-        xCalculateInterlacedAddPSNR(pcPic, correspondingFieldPic, pcPic->getPicYuvRec(), correspondingFieldPic->getPicYuvRec(), snr_conversion, printFrameMSE );
+#if JVET_F0064_MSSSIM
+        xCalculateInterlacedAddPSNR(pcPic, correspondingFieldPic, pcPic->getPicYuvRec(), correspondingFieldPic->getPicYuvRec(), snr_conversion, printFrameMSE, printMSSSIM, PSNR_Y );
+#else
+        xCalculateInterlacedAddPSNR(pcPic, correspondingFieldPic, pcPic->getPicYuvRec(), correspondingFieldPic->getPicYuvRec(), snr_conversion, printFrameMSE, PSNR_Y );
+#endif
       }
       else
       {
-        xCalculateInterlacedAddPSNR(correspondingFieldPic, pcPic, correspondingFieldPic->getPicYuvRec(), pcPic->getPicYuvRec(), snr_conversion, printFrameMSE );
-      }
-    }
-  }
-}
-
-Void TEncGOP::xCalculateAddPSNR( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit& accessUnit, Double dEncTime, const InputColourSpaceConversion conversion, const Bool printFrameMSE )
+#if JVET_F0064_MSSSIM
+        xCalculateInterlacedAddPSNR(correspondingFieldPic, pcPic, correspondingFieldPic->getPicYuvRec(), pcPic->getPicYuvRec(), snr_conversion, printFrameMSE, printMSSSIM, PSNR_Y );
+#else
+        xCalculateInterlacedAddPSNR(correspondingFieldPic, pcPic, correspondingFieldPic->getPicYuvRec(), pcPic->getPicYuvRec(), snr_conversion, printFrameMSE, PSNR_Y );
+#endif
+      }
+    }
+  }
+}
+
+#if JVET_F0064_MSSSIM
+Void TEncGOP::xCalculateAddPSNR( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit& accessUnit, Double dEncTime, const InputColourSpaceConversion conversion, const Bool printFrameMSE, const Bool printMSSSIM, Double* PSNR_Y )
+#else
+Void TEncGOP::xCalculateAddPSNR( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit& accessUnit, Double dEncTime, const InputColourSpaceConversion conversion, const Bool printFrameMSE, Double* PSNR_Y )
+#endif
 {
   Double  dPSNR[MAX_NUM_COMPONENT];
@@ -2556,4 +2627,31 @@
   }
 
+#if EXTENSION_360_VIDEO
+  m_ext360.calculatePSNRs(pcPic);
+#endif
+
+#if JVET_F0064_MSSSIM
+  //===== calculate MS-SSIM =====
+  Double  MSSSIM[MAX_NUM_COMPONENT] = {0,0,0};
+  if (printMSSSIM) 
+  {
+    for(Int chan=0; chan<pcPicD->getNumberValidComponents(); chan++)
+    {
+      const ComponentID ch  = ComponentID(chan);
+      const TComPicYuv *pOrgPicYuv =(conversion!=IPCOLOURSPACE_UNCHANGED) ? pcPic ->getPicYuvTrueOrg() : pcPic ->getPicYuvOrg();
+      const Pel*  pOrg      = pOrgPicYuv->getAddr(ch);
+      const Int   orgStride = pOrgPicYuv->getStride(ch);
+      const Pel*  pRec      = picd.getAddr(ch);
+      const Int   recStride = picd.getStride(ch);
+      const Int   width     = pcPicD->getWidth (ch) - (m_pcEncTop->getPad(0) >> pcPic->getComponentScaleX(ch));
+      const Int   height    = pcPicD->getHeight(ch) - ((m_pcEncTop->getPad(1) >> (pcPic->isField()?1:0)) >> pcPic->getComponentScaleY(ch));
+      const UInt  bitDepth  = pcPic->getPicSym()->getSPS().getBitDepth(toChannelType(ch));
+ 
+      MSSSIM[ch] = xCalculateMSSSIM (pOrg, orgStride, pRec, recStride, width, height, bitDepth);
+    }
+  }
+#endif
+
+
 #if NH_3D_VSO
 #if H_3D_VSO_SYNTH_DIST_OUT
@@ -2562,5 +2660,4 @@
 #endif
   /* calculate the size of the access unit, excluding:
-   *  - any AnnexB contributions (start_code_prefix, zero_byte, etc.,)
    *  - SEI NAL units
    */
@@ -2576,4 +2673,13 @@
     {
       numRBSPBytes += numRBSPBytes_nal;
+      // add start code bytes (Annex B)
+      if (it == accessUnit.begin() || (*it)->m_nalUnitType == NAL_UNIT_VPS || (*it)->m_nalUnitType == NAL_UNIT_SPS || (*it)->m_nalUnitType == NAL_UNIT_PPS)
+      {
+        numRBSPBytes += 4;
+      }
+      else
+      {
+        numRBSPBytes += 3;
+      }
     }
   }
@@ -2583,18 +2689,49 @@
 
   //===== add PSNR =====
+#if JVET_F0064_MSSSIM
+  m_gcAnalyzeAll.addResult (dPSNR, (Double)uibits, MSEyuvframe, MSSSIM);
+#else
   m_gcAnalyzeAll.addResult (dPSNR, (Double)uibits, MSEyuvframe);
+#endif
+#if EXTENSION_360_VIDEO
+  m_ext360.addResult(m_gcAnalyzeAll);
+#endif
 
   TComSlice*  pcSlice = pcPic->getSlice(0);
   if (pcSlice->isIntra())
   {
+#if JVET_F0064_MSSSIM
+    m_gcAnalyzeI.addResult (dPSNR, (Double)uibits, MSEyuvframe, MSSSIM);
+#else
     m_gcAnalyzeI.addResult (dPSNR, (Double)uibits, MSEyuvframe);
+#endif
+#if EXTENSION_360_VIDEO
+    m_ext360.addResult(m_gcAnalyzeI);
+#endif
+    *PSNR_Y = dPSNR[COMPONENT_Y];
   }
   if (pcSlice->isInterP())
   {
+#if JVET_F0064_MSSSIM
+    m_gcAnalyzeP.addResult (dPSNR, (Double)uibits, MSEyuvframe, MSSSIM);
+#else
     m_gcAnalyzeP.addResult (dPSNR, (Double)uibits, MSEyuvframe);
+#endif
+#if EXTENSION_360_VIDEO
+    m_ext360.addResult(m_gcAnalyzeP);
+#endif
+    *PSNR_Y = dPSNR[COMPONENT_Y];
   }
   if (pcSlice->isInterB())
   {
+#if JVET_F0064_MSSSIM
+    m_gcAnalyzeB.addResult (dPSNR, (Double)uibits, MSEyuvframe, MSSSIM);
+#else
     m_gcAnalyzeB.addResult (dPSNR, (Double)uibits, MSEyuvframe);
+#endif
+#if EXTENSION_360_VIDEO
+    m_ext360.addResult(m_gcAnalyzeB);
+#endif
+    *PSNR_Y = dPSNR[COMPONENT_Y];
   }
 
@@ -2647,8 +2784,17 @@
   printf(" [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", dPSNR[COMPONENT_Y], dPSNR[COMPONENT_Cb], dPSNR[COMPONENT_Cr] );
 #endif
+#if JVET_F0064_MSSSIM
+  if (printMSSSIM)
+  {
+    printf(" [MS-SSIM Y %1.6lf    U %1.6lf    V %1.6lf]", MSSSIM[COMPONENT_Y], MSSSIM[COMPONENT_Cb], MSSSIM[COMPONENT_Cr] );
+  }  
+#endif
   if (printFrameMSE)
   {
     printf(" [Y MSE %6.4lf  U MSE %6.4lf  V MSE %6.4lf]", MSEyuvframe[COMPONENT_Y], MSEyuvframe[COMPONENT_Cb], MSEyuvframe[COMPONENT_Cr] );
   }
+#if EXTENSION_360_VIDEO
+  m_ext360.printPerPOCInfo();
+#endif
   printf(" [ET %5.0f ]", dEncTime );
 
@@ -2679,7 +2825,184 @@
 }
 
+#if JVET_F0064_MSSSIM
+Double TEncGOP::xCalculateMSSSIM (const Pel *pOrg, const Int orgStride, const Pel* pRec, const Int recStride, const Int width, const Int height, const UInt bitDepth)
+{
+  const Int MAX_MSSSIM_SCALE  = 5;
+  const Int WEIGHTING_MID_TAP = 5;
+  const Int WEIGHTING_SIZE    = WEIGHTING_MID_TAP*2+1;
+
+  UInt maxScale;
+
+  // For low resolution videos determine number of scales 
+  if (width < 22 || height < 22)
+  {
+    maxScale = 1; 
+  }
+  else if (width < 44 || height < 44)
+  {
+    maxScale = 2; 
+  }
+  else if (width < 88 || height < 88)
+  {
+    maxScale = 3; 
+  }
+  else if (width < 176 || height < 176)
+  {
+    maxScale = 4; 
+  }
+  else
+  {
+    maxScale = 5;
+  }
+
+  assert(maxScale>0 && maxScale<=MAX_MSSSIM_SCALE);
+
+  //Normalized Gaussian mask design, 11*11, s.d. 1.5
+  Double weights[WEIGHTING_SIZE][WEIGHTING_SIZE];
+  {
+    Double coeffSum=0.0;
+    for(Int y=0; y<WEIGHTING_SIZE; y++)
+    {
+      for(Int x=0; x<WEIGHTING_SIZE; x++)
+      {
+        weights[y][x]=exp(-((y-WEIGHTING_MID_TAP)*(y-WEIGHTING_MID_TAP)+(x-WEIGHTING_MID_TAP)*(x-WEIGHTING_MID_TAP))/(WEIGHTING_MID_TAP-0.5));
+        coeffSum +=weights[y][x];
+      }
+    }
+
+    for(Int y=0; y<WEIGHTING_SIZE; y++)
+    {
+      for(Int x=0; x<WEIGHTING_SIZE; x++)
+      {
+        weights[y][x] /=coeffSum;
+      }
+    }
+  }
+
+  //Resolution based weights
+  const Double exponentWeights[MAX_MSSSIM_SCALE][MAX_MSSSIM_SCALE] = {{1.0,    0,      0,      0,      0     },
+                                                                      {0.1356, 0.8644, 0,      0,      0     },
+                                                                      {0.0711, 0.4530, 0.4760, 0,      0     },
+                                                                      {0.0517, 0.3295, 0.3462, 0.2726, 0     },
+                                                                      {0.0448, 0.2856, 0.3001, 0.2363, 0.1333}};
+
+  //Downsampling of data:
+  std::vector<Double> original[MAX_MSSSIM_SCALE];
+  std::vector<Double> recon[MAX_MSSSIM_SCALE];
+
+  for(UInt scale=0; scale<maxScale; scale++)
+  {
+    const Int scaledHeight = height >> scale;
+    const Int scaledWidth  = width  >> scale;
+    original[scale].resize(scaledHeight*scaledWidth, Double(0));
+    recon[scale].resize(scaledHeight*scaledWidth, Double(0));
+  }
+
+  // Initial [0] arrays to be a copy of the source data (but stored in array "Double", not Pel array).
+  for(Int y=0; y<height; y++)
+  {
+    for(Int x=0; x<width; x++)
+    {
+      original[0][y*width+x] = pOrg[y*orgStride+x];
+      recon[0][   y*width+x] = pRec[y*recStride+x];
+    }
+  }
+
+  // Set up other arrays to be average value of each 2x2 sample.
+  for(UInt scale=1; scale<maxScale; scale++)
+  {
+    const Int scaledHeight = height >> scale;
+    const Int scaledWidth  = width  >> scale;
+    for(Int y=0; y<scaledHeight; y++)
+    {
+      for(Int x=0; x<scaledWidth; x++)
+      {
+        original[scale][y*scaledWidth+x]= (original[scale-1][ 2*y   *(2*scaledWidth)+2*x  ] +
+                                           original[scale-1][ 2*y   *(2*scaledWidth)+2*x+1] +
+                                           original[scale-1][(2*y+1)*(2*scaledWidth)+2*x  ] +
+                                           original[scale-1][(2*y+1)*(2*scaledWidth)+2*x+1]) / 4.0;
+        recon[scale][y*scaledWidth+x]=    (   recon[scale-1][ 2*y   *(2*scaledWidth)+2*x  ] +
+                                              recon[scale-1][ 2*y   *(2*scaledWidth)+2*x+1] +
+                                              recon[scale-1][(2*y+1)*(2*scaledWidth)+2*x  ] +
+                                              recon[scale-1][(2*y+1)*(2*scaledWidth)+2*x+1]) / 4.0;
+      }
+    }
+  }
+  
+  // Calculate MS-SSIM:
+  const UInt   maxValue  = (1<<bitDepth)-1;
+  const Double c1        = (0.01*maxValue)*(0.01*maxValue);
+  const Double c2        = (0.03*maxValue)*(0.03*maxValue);
+  
+  Double finalMSSSIM = 1.0;
+
+  for(UInt scale=0; scale<maxScale; scale++)
+  {
+    const Int scaledHeight    = height >> scale;
+    const Int scaledWidth     = width  >> scale;
+    const Int blocksPerRow    = scaledWidth-WEIGHTING_SIZE+1;
+    const Int blocksPerColumn = scaledHeight-WEIGHTING_SIZE+1;
+    const Int totalBlocks     = blocksPerRow*blocksPerColumn;
+
+    Double meanSSIM= 0.0;
+
+    for(Int blockIndexY=0; blockIndexY<blocksPerColumn; blockIndexY++)
+    {
+      for(Int blockIndexX=0; blockIndexX<blocksPerRow; blockIndexX++)
+      {
+        Double muOrg          =0.0;
+        Double muRec          =0.0;
+        Double muOrigSqr      =0.0;
+        Double muRecSqr       =0.0;
+        Double muOrigMultRec  =0.0;
+
+        for(Int y=0; y<WEIGHTING_SIZE; y++)
+        {
+          for(Int x=0;x<WEIGHTING_SIZE; x++)
+          {
+            const Double gaussianWeight=weights[y][x];
+            const Int    sampleOffset=(blockIndexY+y)*scaledWidth+(blockIndexX+x);
+            const Double orgPel=original[scale][sampleOffset];
+            const Double recPel=   recon[scale][sampleOffset];
+
+            muOrg        +=orgPel*       gaussianWeight;
+            muRec        +=recPel*       gaussianWeight;
+            muOrigSqr    +=orgPel*orgPel*gaussianWeight;
+            muRecSqr     +=recPel*recPel*gaussianWeight;
+            muOrigMultRec+=orgPel*recPel*gaussianWeight;
+          }
+        }
+
+        const Double sigmaSqrOrig = muOrigSqr    -(muOrg*muOrg);
+        const Double sigmaSqrRec  = muRecSqr     -(muRec*muRec);
+        const Double sigmaOrigRec = muOrigMultRec-(muOrg*muRec);
+
+        Double blockSSIMVal = ((2.0*sigmaOrigRec + c2)/(sigmaSqrOrig+sigmaSqrRec + c2));
+        if(scale == maxScale-1)
+        {
+          blockSSIMVal*=(2.0*muOrg*muRec + c1)/(muOrg*muOrg+muRec*muRec + c1);
+        }
+
+        meanSSIM += blockSSIMVal;
+      }
+    }
+
+    meanSSIM /=totalBlocks;
+
+    finalMSSSIM *= pow(meanSSIM, exponentWeights[maxScale-1][scale]);
+  }
+
+  return finalMSSSIM;
+}
+#endif
+
+
 Void TEncGOP::xCalculateInterlacedAddPSNR( TComPic* pcPicOrgFirstField, TComPic* pcPicOrgSecondField,
                                            TComPicYuv* pcPicRecFirstField, TComPicYuv* pcPicRecSecondField,
-                                           const InputColourSpaceConversion conversion, const Bool printFrameMSE )
+#if JVET_F0064_MSSSIM
+                                           const InputColourSpaceConversion conversion, const Bool printFrameMSE, const Bool printMSSSIM, Double* PSNR_Y )
+#else
+                                           const InputColourSpaceConversion conversion, const Bool printFrameMSE, Double* PSNR_Y )
+#endif
 {
 
@@ -2755,10 +3078,56 @@
   }
 
+#if JVET_F0064_MSSSIM
+  //===== calculate MS-SSIM =====
+  Double MSSSIM[MAX_NUM_COMPONENT] = {0,0,0};
+  if (printMSSSIM)
+  {
+    for(Int chan=0; chan<numValidComponents; chan++)
+    {
+      const ComponentID ch=ComponentID(chan);
+      assert(apcPicRecFields[0]->getWidth(ch) ==apcPicRecFields[1]->getWidth(ch) );
+      assert(apcPicRecFields[0]->getHeight(ch)==apcPicRecFields[1]->getHeight(ch));
+
+      Double sumOverFieldsMSSSIM = 0.0;
+      const Int   width  = apcPicRecFields[0]->getWidth (ch) - ( m_pcEncTop->getPad(0)       >> apcPicRecFields[0]->getComponentScaleX(ch));
+      const Int   height = apcPicRecFields[0]->getHeight(ch) - ((m_pcEncTop->getPad(1) >> 1) >> apcPicRecFields[0]->getComponentScaleY(ch));
+
+      for(UInt fieldNum=0; fieldNum<2; fieldNum++)
+      {
+        TComPic    *pcPic      = apcPicOrgFields[fieldNum];
+        TComPicYuv *pcPicD     = apcPicRecFields[fieldNum];
+
+        const Pel*  pOrg       = (conversion!=IPCOLOURSPACE_UNCHANGED) ? pcPic ->getPicYuvTrueOrg()->getAddr(ch)   : pcPic ->getPicYuvOrg()->getAddr(ch);
+        const Int   orgStride  = (conversion!=IPCOLOURSPACE_UNCHANGED) ? pcPic ->getPicYuvTrueOrg()->getStride(ch) : pcPic ->getPicYuvOrg()->getStride(ch);
+        Pel*        pRec       = pcPicD->getAddr(ch);
+        const Int   recStride  = pcPicD->getStride(ch);
+        const UInt  bitDepth   = sps.getBitDepth(toChannelType(ch));
+
+        sumOverFieldsMSSSIM += xCalculateMSSSIM (pOrg, orgStride, pRec, recStride, width, height, bitDepth);
+      }
+
+      MSSSIM[ch] = sumOverFieldsMSSSIM/2;
+    }
+  }
+#endif
+
   UInt uibits = 0; // the number of bits for the pair is not calculated here - instead the overall total is used elsewhere.
 
   //===== add PSNR =====
+#if JVET_F0064_MSSSIM
+  m_gcAnalyzeAll_in.addResult (dPSNR, (Double)uibits, MSEyuvframe, MSSSIM);
+#else
   m_gcAnalyzeAll_in.addResult (dPSNR, (Double)uibits, MSEyuvframe);
+#endif
+
+  *PSNR_Y = dPSNR[COMPONENT_Y];
 
   printf("\n                                      Interlaced frame %d: [Y %6.4lf dB    U %6.4lf dB    V %6.4lf dB]", pcPicOrgSecondField->getPOC()/2 , dPSNR[COMPONENT_Y], dPSNR[COMPONENT_Cb], dPSNR[COMPONENT_Cr] );
+#if JVET_F0064_MSSSIM  
+  if (printMSSSIM)
+  {
+    printf(" [MS-SSIM Y %1.6lf    U %1.6lf    V %1.6lf]", MSSSIM[COMPONENT_Y], MSSSIM[COMPONENT_Cb], MSSSIM[COMPONENT_Cr] );
+  }
+#endif
   if (printFrameMSE)
   {
@@ -3113,5 +3482,5 @@
     {
       pcPic->getSlice(i)->setDeblockingFilterOverrideFlag(false);
-      pcPic->getSlice(i)->setDeblockingFilterDisable(        pcPic->getSlice(i)->getPPS()->getPicDisableDeblockingFilterFlag() );
+      pcPic->getSlice(i)->setDeblockingFilterDisable(        pcPic->getSlice(i)->getPPS()->getPPSDeblockingFilterDisabledFlag() );
       pcPic->getSlice(i)->setDeblockingFilterBetaOffsetDiv2( pcPic->getSlice(i)->getPPS()->getDeblockingFilterBetaOffsetDiv2() );
       pcPic->getSlice(i)->setDeblockingFilterTcOffsetDiv2(   pcPic->getSlice(i)->getPPS()->getDeblockingFilterTcOffsetDiv2()   );
@@ -3120,5 +3489,4 @@
 }
 
-#if W0038_DB_OPT
 Void TEncGOP::applyDeblockingFilterParameterSelection( TComPic* pcPic, const UInt numSlices, const Int gopID )
 {
@@ -3223,5 +3591,5 @@
     {
       pcPic->getSlice(i)->setDeblockingFilterOverrideFlag(false);
-      pcPic->getSlice(i)->setDeblockingFilterDisable(        pcPic->getSlice(i)->getPPS()->getPicDisableDeblockingFilterFlag() );
+      pcPic->getSlice(i)->setDeblockingFilterDisable(        pcPic->getSlice(i)->getPPS()->getPPSDeblockingFilterDisabledFlag() );
       pcPic->getSlice(i)->setDeblockingFilterBetaOffsetDiv2( pcPic->getSlice(i)->getPPS()->getDeblockingFilterBetaOffsetDiv2() );
       pcPic->getSlice(i)->setDeblockingFilterTcOffsetDiv2(   pcPic->getSlice(i)->getPPS()->getDeblockingFilterTcOffsetDiv2()   );
@@ -3239,5 +3607,4 @@
   }
 }
-#endif
 
 #if NH_MV
Index: /trunk/source/Lib/TLibEncoder/TEncGOP.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncGOP.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncGOP.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -55,4 +55,7 @@
 #include "SEIwrite.h"
 #include "SEIEncoder.h"
+#if EXTENSION_360_VIDEO
+#include "TAppEncHelper360/TExt360EncGop.h"
+#endif
 
 #include "TEncAnalyze.h"
@@ -93,4 +96,12 @@
 
   TEncAnalyze             m_gcAnalyzeAll_in;
+
+#if EXTENSION_360_VIDEO
+  TExt360EncGop           m_ext360;
+public:
+  TExt360EncGop &getExt360Data() { return m_ext360; }
+private:
+#endif
+
   //  Data
   Bool                    m_bLongtermTestPictureHasBeenCoded;
@@ -127,10 +138,9 @@
   Int                     m_layerId;  
   Int                     m_viewId;
+#endif
 #if NH_3D
   Int                     m_viewIndex; 
   Bool                    m_isDepth;
-#endif
-#endif
-#if NH_3D_IC
+
   Int*                    m_aICEnableCandidate; 
   Int*                    m_aICEnableNum; 
@@ -153,8 +163,6 @@
   Bool                    m_bufferingPeriodSEIPresentInAU;
   SEIEncoder              m_seiEncoder;
-#if W0038_DB_OPT
   TComPicYuv*             m_pcDeblockingTempPicYuv;
   Int                     m_DBParam[MAX_ENCODER_DEBLOCKING_QUALITY_LAYERS][4];   //[layer_id][0: available; 1: bDBDisabled; 2: Beta Offset Div2; 3: Tc Offset Div2;]
-#endif
 
 public:
@@ -168,9 +176,13 @@
 #if NH_MV
   Void  initGOP     ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, std::list<AccessUnit>& accessUnitsInGOP);  
-  Void  compressPicInGOP ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec,
-    std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, Int iGOPid );
+  Void compressPicInGOP ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec,
+    std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, const Bool printMSSSIM, Int iGOPid );
 #else
   Void  compressGOP ( Int iPOCLast, Int iNumPicRcvd, TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRec,
+#if JVET_F0064_MSSSIM
+                      std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, const Bool printMSSSIM );
+#else
                       std::list<AccessUnit>& accessUnitsInGOP, Bool isField, Bool isTff, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE );
+#endif
 #endif
   Void  xAttachSliceDataToNalUnit (OutputNALUnit& rNalu, TComOutputBitstream* pcBitstreamRedirect);
@@ -189,5 +201,10 @@
 
   TComList<TComPic*>*   getListPic()      { return m_pcListPic; }
+#if JVET_F0064_MSSSIM  
+  Void  printOutSummary      ( UInt uiNumAllPicCoded, Bool isField, const Bool printMSEBasedSNR, const Bool printSequenceMSE, const Bool printMSSSIM, const BitDepths &bitDepths );
+#else
+
   Void  printOutSummary      ( UInt uiNumAllPicCoded, Bool isField, const Bool printMSEBasedSNR, const Bool printSequenceMSE, const BitDepths &bitDepths );
+#endif
 #if NH_3D_VSO
   Void  preLoopFilterPicAll  ( TComPic* pcPic, Dist64& ruiDist);
@@ -204,4 +221,9 @@
   Void arrangeLongtermPicturesInRPS(TComSlice *, TComList<TComPic*>& );
 
+  TEncAnalyze& getAnalyzeAllData() { return m_gcAnalyzeAll; }
+  TEncAnalyze& getAnalyzeIData()   { return m_gcAnalyzeI; }
+  TEncAnalyze& getAnalyzePData()   { return m_gcAnalyzeP; }
+  TEncAnalyze& getAnalyzeBData()   { return m_gcAnalyzeB; }
+
 protected:
   TEncRateCtrl* getRateCtrl()       { return m_pcRateCtrl;  }
@@ -212,9 +234,19 @@
   Void  xGetBuffer        ( TComList<TComPic*>& rcListPic, TComList<TComPicYuv*>& rcListPicYuvRecOut, Int iNumPicRcvd, Int iTimeOffset, TComPic*& rpcPic, TComPicYuv*& rpcPicYuvRecOut, Int pocCurr, Bool isField );
 
-  Void  xCalculateAddPSNRs         ( const Bool isField, const Bool isFieldTopFieldFirst, const Int iGOPid, TComPic* pcPic, const AccessUnit&accessUnit, TComList<TComPic*> &rcListPic, Double dEncTime, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE );
-  Void  xCalculateAddPSNR          ( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit&, Double dEncTime, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE );
+#if JVET_F0064_MSSSIM
+  Void  xCalculateAddPSNRs         ( const Bool isField, const Bool isFieldTopFieldFirst, const Int iGOPid, TComPic* pcPic, const AccessUnit&accessUnit, TComList<TComPic*> &rcListPic, Double dEncTime, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, const Bool printMSSSIM, Double* PSNR_Y );
+  Void  xCalculateAddPSNR          ( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit&, Double dEncTime, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, const Bool printMSSSIM, Double* PSNR_Y );
   Void  xCalculateInterlacedAddPSNR( TComPic* pcPicOrgFirstField, TComPic* pcPicOrgSecondField,
                                      TComPicYuv* pcPicRecFirstField, TComPicYuv* pcPicRecSecondField,
-                                     const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE );
+                                     const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, const Bool printMSSSIM, Double* PSNR_Y );
+  Double xCalculateMSSSIM (const Pel *pOrg, const Int orgStride, const Pel* pRec, const Int recStride, const Int width, const Int height, const UInt bitDepth);
+#else
+  Void  xCalculateAddPSNRs         ( const Bool isField, const Bool isFieldTopFieldFirst, const Int iGOPid, TComPic* pcPic, const AccessUnit&accessUnit, TComList<TComPic*> &rcListPic, Double dEncTime, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, Double* PSNR_Y );
+  Void  xCalculateAddPSNR          ( TComPic* pcPic, TComPicYuv* pcPicD, const AccessUnit&, Double dEncTime, const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, Double* PSNR_Y );
+  Void  xCalculateInterlacedAddPSNR( TComPic* pcPicOrgFirstField, TComPic* pcPicOrgSecondField,
+                                     TComPicYuv* pcPicRecFirstField, TComPicYuv* pcPicRecSecondField,
+                                     const InputColourSpaceConversion snr_conversion, const Bool printFrameMSE, Double* PSNR_Y );
+#endif
+
 #if NH_3D_VSO
   Dist64 xFindDistortionFrame (TComPicYuv* pcPic0, TComPicYuv* pcPic1, const BitDepths &bitDepths);
@@ -245,5 +277,9 @@
   Int xWriteSPS (AccessUnit &accessUnit, const TComSPS *sps);
   Int xWritePPS (AccessUnit &accessUnit, const TComPPS *pps);
-  Int xWriteParameterSets (AccessUnit &accessUnit, TComSlice *slice);
+#if NH_MV
+  Int xWriteParameterSets (AccessUnit &accessUnit, TComSlice *slice, const Bool bSeqFirst, const Bool bWriteVps ); 
+#else
+  Int xWriteParameterSets (AccessUnit &accessUnit, TComSlice *slice, const Bool bSeqFirst ); 
+#endif
 
 #if NH_MV
@@ -253,7 +289,5 @@
 
   Void applyDeblockingFilterMetric( TComPic* pcPic, UInt uiNumSlices );
-#if W0038_DB_OPT
   Void applyDeblockingFilterParameterSelection( TComPic* pcPic, const UInt numSlices, const Int gopID );
-#endif
 };// END CLASS DEFINITION TEncGOP
 
Index: /trunk/source/Lib/TLibEncoder/TEncPic.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncPic.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncPic.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -122,7 +122,13 @@
  * \param bIsVirtual
  */
+#if REDUCED_ENCODER_MEMORY
+Void TEncPic::create( const TComSPS &sps, const TComPPS &pps, UInt uiMaxAdaptiveQPDepth )
+{
+  TComPic::create( sps, pps, true, false );
+#else
 Void TEncPic::create( const TComSPS &sps, const TComPPS &pps, UInt uiMaxAdaptiveQPDepth, Bool bIsVirtual )
 {
   TComPic::create( sps, pps, bIsVirtual );
+#endif
   const Int  iWidth      = sps.getPicWidthInLumaSamples();
   const Int  iHeight     = sps.getPicHeightInLumaSamples();
Index: /trunk/source/Lib/TLibEncoder/TEncPic.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncPic.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncPic.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -103,5 +103,9 @@
   virtual ~TEncPic();
 
+#if REDUCED_ENCODER_MEMORY
+  Void          create( const TComSPS &sps, const TComPPS &pps, UInt uiMaxAdaptiveQPDepth );
+#else
   Void          create( const TComSPS &sps, const TComPPS &pps, UInt uiMaxAdaptiveQPDepth, Bool bIsVirtual /* = false*/ );
+#endif
   virtual Void  destroy();
 
Index: /trunk/source/Lib/TLibEncoder/TEncPreanalyzer.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncPreanalyzer.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibEncoder/TEncPreanalyzer.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncPreanalyzer.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncPreanalyzer.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
-* Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncRateCtrl.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -554,5 +554,4 @@
 }
 
-#if V0078_ADAPTIVE_LOWER_BOUND
 Int TEncRCPic::xEstPicLowerBound(TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP)
 {
@@ -592,6 +591,4 @@
   return lowerBound;
 }
-#endif
-
 
 Void TEncRCPic::addToPictureLsit( list<TEncRCPic*>& listPreviousPictures )
@@ -652,7 +649,5 @@
   Int picWidthInLCU  = ( picWidth  % LCUWidth  ) == 0 ? picWidth  / LCUWidth  : picWidth  / LCUWidth  + 1;
   Int picHeightInLCU = ( picHeight % LCUHeight ) == 0 ? picHeight / LCUHeight : picHeight / LCUHeight + 1;
-#if V0078_ADAPTIVE_LOWER_BOUND
   m_lowerBound       = xEstPicLowerBound( encRCSeq, encRCGOP );
-#endif
 
   m_LCULeft         = m_numberOfLCU;
@@ -1683,10 +1678,8 @@
     m_encRCSeq->initLCUPara();
   }
-#if U0132_TARGET_BITS_SATURATION
   m_CpbSaturationEnabled = false;
   m_cpbSize              = targetBitrate;
   m_cpbState             = (UInt)(m_cpbSize*0.5f);
   m_bufferingRate        = (Int)(targetBitrate / frameRate);
-#endif
 
 #if KWU_RC_MADPRED_E0227
@@ -1714,5 +1707,4 @@
 }
 
-#if U0132_TARGET_BITS_SATURATION
 Int  TEncRateCtrl::updateCpbState(Int actualBits)
 {
@@ -1742,5 +1734,4 @@
   printf("\nHRD - [Initial CPB state %6d] [CPB Size %6d] [Buffering Rate %6d]\n", m_cpbState, m_cpbSize, m_bufferingRate);
 }
-#endif
 
 Void TEncRateCtrl::destroyRCGOP()
Index: /trunk/source/Lib/TLibEncoder/TEncRateCtrl.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncRateCtrl.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -267,7 +267,5 @@
   Int xEstPicTargetBits( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP );
   Int xEstPicHeaderBits( list<TEncRCPic*>& listPreviousPictures, Int frameLevel );
-#if V0078_ADAPTIVE_LOWER_BOUND
   Int xEstPicLowerBound( TEncRCSeq* encRCSeq, TEncRCGOP* encRCGOP );
-#endif
 
 public:
@@ -285,13 +283,9 @@
   Int  getBitsCoded()                                     { return m_targetBits - m_estHeaderBits - m_bitsLeft; }
   Int  getLCUCoded()                                      { return m_numberOfLCU - m_LCULeft; }
-#if V0078_ADAPTIVE_LOWER_BOUND
   Int  getLowerBound()                                    { return m_lowerBound; }
-#endif
   TRCLCU* getLCU()                                        { return m_LCUs; }
   TRCLCU& getLCU( Int LCUIdx )                            { return m_LCUs[LCUIdx]; }
   Int  getPicActualHeaderBits()                           { return m_picActualHeaderBits; }
-#if U0132_TARGET_BITS_SATURATION
   Void setBitLeft(Int bits)                               { m_bitsLeft = bits; }
-#endif
   Void setTargetBits( Int bits )                          { m_targetBits = bits; m_bitsLeft = bits;}
   Void setTotalIntraCost(Double cost)                     { m_totalCostIntra = cost; }
@@ -327,7 +321,5 @@
   Int m_estHeaderBits;
   Int m_estPicQP;
-#if V0078_ADAPTIVE_LOWER_BOUND
   Int m_lowerBound;
-#endif
   Double m_estPicLambda;
 
@@ -381,5 +373,4 @@
   Void setLayerID(Int layerid)     { m_LayerID = layerid; }
 #endif
-#if U0132_TARGET_BITS_SATURATION
   Bool       getCpbSaturationEnabled()  { return m_CpbSaturationEnabled;  }
   UInt       getCpbState()              { return m_cpbState;       }
@@ -388,5 +379,4 @@
   Int        updateCpbState(Int actualBits);
   Void       initHrdParam(const TComHRD* pcHrd, Int iFrameRate, Double fInitialCpbFullness);
-#endif
 
 private:
@@ -396,10 +386,8 @@
   list<TEncRCPic*> m_listRCPictures;
   Int        m_RCQP;
-#if U0132_TARGET_BITS_SATURATION
   Bool       m_CpbSaturationEnabled;    // Enable target bits saturation to avoid CPB overflow and underflow
   Int        m_cpbState;                // CPB State 
   UInt       m_cpbSize;                 // CPB size
   UInt       m_bufferingRate;           // Buffering rate
-#endif
 
 #if KWU_RC_MADPRED_E0227
Index: /trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -120,7 +120,5 @@
 
   ::memset(m_saoDisabledRate, 0, sizeof(m_saoDisabledRate));
-#if OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP
   m_lastIRAPPoc = MAX_INT;
-#endif
 
   for(Int typeIdc=0; typeIdc < NUM_SAO_NEW_TYPES; typeIdc++)
@@ -242,9 +240,5 @@
 
 
-#if OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP
 Void TEncSampleAdaptiveOffset::SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas, const Bool bTestSAODisableAtPictureLevel, const Double saoEncodingRate, const Double saoEncodingRateChroma, const Bool isPreDBFSamplesUsed, const Bool bResetStateAfterIRAP )
-#else
-Void TEncSampleAdaptiveOffset::SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas, const Bool bTestSAODisableAtPictureLevel, const Double saoEncodingRate, const Double saoEncodingRateChroma, Bool isPreDBFSamplesUsed )
-#endif
 {
   TComPicYuv* orgYuv= pPic->getPicYuvOrg();
@@ -263,9 +257,5 @@
   }
   //slice on/off
-#if OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP
   decidePicParams(sliceEnabled, pPic, saoEncodingRate, saoEncodingRateChroma, bResetStateAfterIRAP);
-#else
-  decidePicParams(sliceEnabled, pPic->getSlice(0)->getDepth(), saoEncodingRate, saoEncodingRateChroma);
-#endif
 
   //block on/off
@@ -341,11 +331,6 @@
 }
 
-#if OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP
 Void TEncSampleAdaptiveOffset::decidePicParams(Bool* sliceEnabled, const TComPic* pic, const Double saoEncodingRate, const Double saoEncodingRateChroma, const Bool bResetStateAfterIRAP)
-#else
-Void TEncSampleAdaptiveOffset::decidePicParams(Bool* sliceEnabled, Int picTempLayer, const Double saoEncodingRate, const Double saoEncodingRateChroma)
-#endif
-{
-#if OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP
+{
   if (pic->getSlice(0)->isIRAP())
   {
@@ -364,5 +349,4 @@
   }
   const Int picTempLayer = pic->getSlice(0)->getDepth();
-#endif
 
   //decide sliceEnabled[compIdx]
Index: /trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncSampleAdaptiveOffset.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -103,18 +103,10 @@
   Void destroyEncData();
   Void initRDOCabacCoder(TEncSbac* pcRDGoOnSbacCoder, TComSlice* pcSlice) ;
-#if OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP
   Void SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas, const Bool bTestSAODisableAtPictureLevel, const Double saoEncodingRate, const Double saoEncodingRateChroma, const Bool isPreDBFSamplesUsed, const Bool bResetStateAfterIRAP);
-#else
-  Void SAOProcess(TComPic* pPic, Bool* sliceEnabled, const Double *lambdas, const Bool bTestSAODisableAtPictureLevel, const Double saoEncodingRate, const Double saoEncodingRateChroma, Bool isPreDBFSamplesUsed);
-#endif
 public: //methods
   Void getPreDBFStatistics(TComPic* pPic);
 private: //methods
   Void getStatistics(SAOStatData*** blkStats, TComPicYuv* orgYuv, TComPicYuv* srcYuv,TComPic* pPic, Bool isCalculatePreDeblockSamples = false);
-#if OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP
   Void decidePicParams(Bool* sliceEnabled, const TComPic* pic, const Double saoEncodingRate, const Double saoEncodingRateChroma, const Bool bResetStateAfterIRAP);
-#else
-  Void decidePicParams(Bool* sliceEnabled, Int picTempLayer, const Double saoEncodingRate, const Double saoEncodingRateChroma);
-#endif
   Void decideBlkParams(TComPic* pic, Bool* sliceEnabled, SAOStatData*** blkStats, TComPicYuv* srcYuv, TComPicYuv* resYuv, SAOBlkParam* reconParams, SAOBlkParam* codedParams, const Bool bTestSAODisableAtPictureLevel, const Double saoEncodingRate, const Double saoEncodingRateChroma);
   Void getBlkStats(const ComponentID compIdx, const Int channelBitDepth, SAOStatData* statsDataTypes, Pel* srcBlk, Pel* orgBlk, Int srcStride, Int orgStride, Int width, Int height, Bool isLeftAvail,  Bool isRightAvail, Bool isAboveAvail, Bool isBelowAvail, Bool isAboveLeftAvail, Bool isAboveRightAvail, Bool isCalculatePreDeblockSamples);
@@ -141,7 +133,5 @@
   SAOStatData***         m_preDBFstatData;
   Double                 m_saoDisabledRate[MAX_NUM_COMPONENT][MAX_TLAYER];
-#if OPTIONAL_RESET_SAO_ENCODING_AFTER_IRAP
   Int                    m_lastIRAPPoc;
-#endif
   Int                    m_skipLinesR[MAX_NUM_COMPONENT][NUM_SAO_NEW_TYPES];
   Int                    m_skipLinesB[MAX_NUM_COMPONENT][NUM_SAO_NEW_TYPES];
Index: /trunk/source/Lib/TLibEncoder/TEncSbac.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncSbac.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -62,5 +62,5 @@
 , m_cCUSplitFlagSCModel                ( 1,             1,                      NUM_SPLIT_FLAG_CTX                   , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cCUSkipFlagSCModel                 ( 1,             1,                      NUM_SKIP_FLAG_CTX                    , m_contextModels + m_numContextModels, m_numContextModels)
-#if NH_3D_DIS
+#if NH_3D
 , m_cCUDISFlagSCModel                  ( 1,             1,                      NUM_DIS_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cCUDISTypeSCModel                  ( 1,             1,                      NUM_DIS_TYPE_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
@@ -68,8 +68,6 @@
 , m_cCUMergeFlagExtSCModel             ( 1,             1,                      NUM_MERGE_FLAG_EXT_CTX               , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cCUMergeIdxExtSCModel              ( 1,             1,                      NUM_MERGE_IDX_EXT_CTX                , m_contextModels + m_numContextModels, m_numContextModels)
-#if NH_3D_ARP
+#if NH_3D
 , m_cCUPUARPWSCModel                   ( 1,             1,                      NUM_ARPW_CTX                         , m_contextModels + m_numContextModels, m_numContextModels)
-#endif                                                                                                               
-#if NH_3D_IC                                                                                                          
 , m_cCUICFlagSCModel                   ( 1,             1,                      NUM_IC_FLAG_CTX                      , m_contextModels + m_numContextModels, m_numContextModels)
 #endif
@@ -102,18 +100,12 @@
 , m_ChromaQpAdjIdcSCModel              ( 1,             1,                      NUM_CHROMA_QP_ADJ_IDC_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
 
-#if NH_3D_DMM
+#if NH_3D
 , m_cNotDmmFlagSCModel                 ( 1,             1,                      NUM_NOTDMM_FLAG_CTX                  , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cDmmModeSCModel                    ( 1,             1,                      NUM_DMM_MODE_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
-#endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
 , m_cDdcDataSCModel                    ( 1,             1,                      NUM_DDC_DATA_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cSDCFlagSCModel                    ( 1,             1,                       NUM_SDC_FLAG_CTX                    , m_contextModels + m_numContextModels, m_numContextModels)
-#endif
-#if NH_3D_SDC_INTRA
 , m_cSDCResidualFlagSCModel            ( 1,             1,                      SDC_NUM_RESIDUAL_FLAG_CTX            , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cSDCResidualSCModel                ( 1,             1,                      SDC_NUM_RESIDUAL_CTX                 , m_contextModels + m_numContextModels, m_numContextModels)
 , m_cDdcFlagSCModel                    ( 1,             1,                      NUM_DDC_FLAG_CTX                     , m_contextModels + m_numContextModels, m_numContextModels)
-#endif                                                                                                          
-#if NH_3D_DBBP
 , m_cDBBPFlagSCModel                   ( 1,             1,                       DBBP_NUM_FLAG_CTX                   , m_contextModels + m_numContextModels, m_numContextModels)
 #endif
@@ -143,5 +135,5 @@
   m_cCUSplitFlagSCModel.initBuffer                ( eSliceType, iQp, (UChar*)INIT_SPLIT_FLAG );
   m_cCUSkipFlagSCModel.initBuffer                 ( eSliceType, iQp, (UChar*)INIT_SKIP_FLAG );
-#if NH_3D_DIS
+#if NH_3D
   m_cCUDISFlagSCModel.initBuffer                  ( eSliceType, iQp, (UChar*)INIT_DIS_FLAG );
   m_cCUDISTypeSCModel.initBuffer                  ( eSliceType, iQp, (UChar*)INIT_DIS_TYPE );
@@ -149,8 +141,6 @@
   m_cCUMergeFlagExtSCModel.initBuffer             ( eSliceType, iQp, (UChar*)INIT_MERGE_FLAG_EXT);
   m_cCUMergeIdxExtSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_MERGE_IDX_EXT);
-#if NH_3D_ARP
+#if NH_3D
   m_cCUPUARPWSCModel.initBuffer                   ( eSliceType, iQp, (UChar*)INIT_ARPW );
-#endif
-#if NH_3D_IC
   m_cCUICFlagSCModel.initBuffer                   ( eSliceType, iQp, (UChar*)INIT_IC_FLAG );
 #endif
@@ -183,18 +173,12 @@
   m_ChromaQpAdjIdcSCModel.initBuffer              ( eSliceType, iQp, (UChar*)INIT_CHROMA_QP_ADJ_IDC );
 
-#if NH_3D_DMM
+#if NH_3D
   m_cNotDmmFlagSCModel.initBuffer                 ( eSliceType, iQp, (UChar*)INIT_NOTDMM_FLAG );
   m_cDmmModeSCModel.initBuffer                    ( eSliceType, iQp, (UChar*)INIT_DMM_MODE );
-#endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   m_cDdcDataSCModel.initBuffer                    ( eSliceType, iQp, (UChar*)INIT_DDC_DATA );
   m_cSDCFlagSCModel.initBuffer                    ( eSliceType, iQp, (UChar*)INIT_SDC_FLAG );
-#endif
-#if NH_3D_SDC_INTRA
   m_cSDCResidualFlagSCModel.initBuffer            ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL_FLAG );
   m_cSDCResidualSCModel.initBuffer                ( eSliceType, iQp, (UChar*)INIT_SDC_RESIDUAL );
   m_cDdcFlagSCModel.initBuffer                    ( eSliceType, iQp, (UChar*)INIT_DDC_FLAG );
-#endif                                           
-#if NH_3D_DBBP
   m_cDBBPFlagSCModel.initBuffer                   ( eSliceType, iQp, (UChar*)INIT_DBBP_FLAG );
 #endif
@@ -231,5 +215,5 @@
       curCost  = m_cCUSplitFlagSCModel.calcCost                ( curSliceType, qp, (UChar*)INIT_SPLIT_FLAG );
       curCost += m_cCUSkipFlagSCModel.calcCost                 ( curSliceType, qp, (UChar*)INIT_SKIP_FLAG );
-#if NH_3D_DIS
+#if NH_3D
       curCost += m_cCUDISFlagSCModel.calcCost                  ( curSliceType, qp, (UChar*)INIT_DIS_FLAG );
       curCost += m_cCUDISTypeSCModel.calcCost                  ( curSliceType, qp, (UChar*)INIT_DIS_TYPE );
@@ -237,14 +221,8 @@
       curCost += m_cCUMergeFlagExtSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_MERGE_FLAG_EXT);
       curCost += m_cCUMergeIdxExtSCModel.calcCost              ( curSliceType, qp, (UChar*)INIT_MERGE_IDX_EXT);
-#if NH_3D_ARP
+#if NH_3D
       curCost += m_cCUPUARPWSCModel.calcCost                   ( curSliceType, qp, (UChar*)INIT_ARPW );
-#endif                                                     
-#if NH_3D_IC                                                
       curCost += m_cCUICFlagSCModel.calcCost                   ( curSliceType, qp, (UChar*)INIT_IC_FLAG );
-#endif                                                     
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
       curCost += m_cSDCFlagSCModel.calcCost                    ( curSliceType, qp, (UChar*)INIT_SDC_FLAG );
-#endif                                                     
-#if NH_3D_DBBP
       curCost += m_cDBBPFlagSCModel.calcCost                   ( curSliceType, qp, (UChar*)INIT_DBBP_FLAG );
 #endif
@@ -276,9 +254,7 @@
       curCost += m_ChromaQpAdjFlagSCModel.calcCost             ( curSliceType, qp, (UChar*)INIT_CHROMA_QP_ADJ_FLAG );
       curCost += m_ChromaQpAdjIdcSCModel.calcCost              ( curSliceType, qp, (UChar*)INIT_CHROMA_QP_ADJ_IDC );
-#if NH_3D_DMM
+#if NH_3D
       curCost += m_cNotDmmFlagSCModel.calcCost                 ( curSliceType, qp, (UChar*)INIT_NOTDMM_FLAG );  
       curCost += m_cDmmModeSCModel.calcCost                    ( curSliceType, qp, (UChar*)INIT_DMM_MODE );
-#endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
       curCost += m_cDdcDataSCModel.calcCost                    ( curSliceType, qp, (UChar*)INIT_DDC_DATA );
 #endif
@@ -406,5 +382,5 @@
 }
 
-#if NH_3D_DIS
+#if NH_3D
 Void TEncSbac::codeDIS( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
@@ -522,5 +498,5 @@
 }
 
-#if NH_3D_DMM
+#if NH_3D
 Void TEncSbac::loadIntraDepthDmm( const TEncSbac* pSrc )
 {
@@ -567,5 +543,5 @@
 {
   PartSize eSize         = pcCU->getPartitionSize( uiAbsPartIdx );
-#if NH_3D_QTLPC
+#if NH_3D
   Bool    bLimQtPredFlag = pcCU->getPic()->getSlice(0)->getQtPredFlag();
   TComPic *pcTexture     = pcCU->getSlice()->getTexturePic();
@@ -578,9 +554,5 @@
   UInt uiTexturePart = eSize;
 
-#if H_3D_FCO
-  if(bDepthMapDetect && !bIntraSliceDetect && !rapPic && pcCU->getPic()->getReduceBitsFlag() && bLimQtPredFlag && pcTexture->getReconMark())
-#else
   if(bDepthMapDetect && !bIntraSliceDetect && !rapPic && pcCU->getPic()->getReduceBitsFlag() && bLimQtPredFlag )
-#endif
   {
     TComDataCU *pcTextureCU = pcTexture->getCtu(pcCU->getCtuRsAddr());
@@ -616,85 +588,81 @@
   DTRACE_CU("part_mode", eSize )
 #endif        
-#if NH_3D_QTLPC
+#if NH_3D
     if (depthDependent==false || uiTexturePart == SIZE_NxN|| uiTexturePart == SIZE_2Nx2N)
     {
 #endif
-
-  switch(eSize)
-  {
-    case SIZE_2Nx2N:
-    {
-      m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 0) );
-      break;
-    }
-    case SIZE_2NxN:
-    case SIZE_2NxnU:
-    case SIZE_2NxnD:
-    {
-      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
-      m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 1) );
-      if ( pcCU->getSlice()->getSPS()->getUseAMP() && uiDepth < log2DiffMaxMinCodingBlockSize )
-      {
-        if (eSize == SIZE_2NxN)
-        {
-          m_pcBinIf->encodeBin(1, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
-        }
-        else
-        {
-          m_pcBinIf->encodeBin(0, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
-          m_pcBinIf->encodeBinEP((eSize == SIZE_2NxnU? 0: 1));
-        }
-      }
-      break;
-    }
-    case SIZE_Nx2N:
-    case SIZE_nLx2N:
-    case SIZE_nRx2N:
-    {
-      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
-      m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
-
-      if( uiDepth == log2DiffMaxMinCodingBlockSize && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) )
-      {
-        m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 2) );
-      }
-
-      if ( pcCU->getSlice()->getSPS()->getUseAMP() && uiDepth < log2DiffMaxMinCodingBlockSize )
-      {
-        if (eSize == SIZE_Nx2N)
-        {
-          m_pcBinIf->encodeBin(1, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
-        }
-        else
-        {
-          m_pcBinIf->encodeBin(0, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
-          m_pcBinIf->encodeBinEP((eSize == SIZE_nLx2N? 0: 1));
-        }
-      }
-      break;
-    }
-    case SIZE_NxN:
-    {
-      if( uiDepth == log2DiffMaxMinCodingBlockSize && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) )
-      {
-        m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
-        m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
-        m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 2) );
-      }
-      break;
-    }
-    default:
-    {
-      assert(0);
-      break;
-    }
-  }
-#if NH_3D_QTLPC
+      switch(eSize)
+      {
+      case SIZE_2Nx2N:
+        {
+          m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+          break;
+        }
+      case SIZE_2NxN:
+      case SIZE_2NxnU:
+      case SIZE_2NxnD:
+        {
+          m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+          m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+          if ( pcCU->getSlice()->getSPS()->getUseAMP() && uiDepth < log2DiffMaxMinCodingBlockSize )
+          {
+            if (eSize == SIZE_2NxN)
+            {
+              m_pcBinIf->encodeBin(1, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
+            }
+            else
+            {
+              m_pcBinIf->encodeBin(0, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
+              m_pcBinIf->encodeBinEP((eSize == SIZE_2NxnU? 0: 1));
+            }
+          }
+          break;
+        }
+      case SIZE_Nx2N:
+      case SIZE_nLx2N:
+      case SIZE_nRx2N:
+        {
+          m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+          m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+
+          if( uiDepth == log2DiffMaxMinCodingBlockSize && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) )
+          {
+            m_pcBinIf->encodeBin( 1, m_cCUPartSizeSCModel.get( 0, 0, 2) );
+          }
+
+          if ( pcCU->getSlice()->getSPS()->getUseAMP() && uiDepth < log2DiffMaxMinCodingBlockSize )
+          {
+            if (eSize == SIZE_Nx2N)
+            {
+              m_pcBinIf->encodeBin(1, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
+            }
+            else
+            {
+              m_pcBinIf->encodeBin(0, m_cCUPartSizeSCModel.get( 0, 0, 3 ));
+              m_pcBinIf->encodeBinEP((eSize == SIZE_nLx2N? 0: 1));
+            }
+          }
+          break;
+        }
+      case SIZE_NxN:
+        {
+          if( uiDepth == log2DiffMaxMinCodingBlockSize && !( pcCU->getWidth(uiAbsPartIdx) == 8 && pcCU->getHeight(uiAbsPartIdx) == 8 ) )
+          {
+            m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 0) );
+            m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 1) );
+            m_pcBinIf->encodeBin( 0, m_cCUPartSizeSCModel.get( 0, 0, 2) );
+          }
+          break;
+        }
+      default:
+        {
+          assert(0);
+          break;
+        }
+      }
+#if NH_3D
     }
     else if(uiTexturePart == SIZE_2NxN || uiTexturePart == SIZE_2NxnU || uiTexturePart == SIZE_2NxnD)
     {
-      //assert(eSize!=SIZE_NxN);
-      //assert(eSize!=SIZE_Nx2N);
-      //assert(eSize==SIZE_2Nx2N || eSize==SIZE_2NxN || eSize==SIZE_2NxnU || eSize==SIZE_2NxnD);
       switch(eSize)
       {
@@ -729,7 +697,4 @@
     else if(uiTexturePart == SIZE_Nx2N|| uiTexturePart==SIZE_nLx2N || uiTexturePart==SIZE_nRx2N)
     {
-      //assert(eSize!=SIZE_NxN);
-      //assert(eSize!=SIZE_2NxN);
-      //assert(eSize==SIZE_2Nx2N ||eSize==SIZE_Nx2N || eSize==SIZE_nLx2N || eSize==SIZE_nRx2N);
       switch(eSize)
       {
@@ -768,5 +733,4 @@
     }
 #endif
-
 }
 
@@ -885,5 +849,5 @@
 }
 
-#if NH_3D_ARP
+#if NH_3D
 Void TEncSbac::codeARPW( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
@@ -903,7 +867,5 @@
 #endif
 }
-#endif
-
-#if NH_3D_IC
+
 /** code Illumination Compensation flag
  * \param pcCU
@@ -940,5 +902,5 @@
 
   assert( uiCtx < 3 );
-#if NH_3D_QTLPC
+#if NH_3D
   Bool bCodeSplitFlag    = true;
 
@@ -951,9 +913,5 @@
   Bool rapPic     = (pcCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_W_RADL || pcCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_IDR_N_LP || pcCU->getSlice()->getNalUnitType() == NAL_UNIT_CODED_SLICE_CRA);
 
-#if H_3D_FCO
-  if(bDepthMapDetect && !bIntraSliceDetect && !rapPic && pcCU->getPic()->getReduceBitsFlag() && bLimQtPredFlag && pcTexture->getReconMark() )
-#else
   if(bDepthMapDetect && !bIntraSliceDetect && !rapPic && pcCU->getPic()->getReduceBitsFlag() && bLimQtPredFlag  )
-#endif
   {
     TComDataCU *pcTextureCU = pcTexture->getCtu(pcCU->getCtuRsAddr());
@@ -1009,5 +967,5 @@
   {
     dir[j] = pcCU->getIntraDir( CHANNEL_TYPE_LUMA, absPartIdx+partOffset*j );
-#if NH_3D_DMM
+#if NH_3D
     if( pcCU->getSlice()->getIntraSdcWedgeFlag() ||  pcCU->getSlice()->getIntraContourFlag() )
     {
@@ -1018,17 +976,17 @@
     {
 #endif
-    pcCU->getIntraDirPredictor(absPartIdx+partOffset*j, preds[j], COMPONENT_Y);
-    for(UInt i = 0; i < NUM_MOST_PROBABLE_MODES; i++)
-    {
-      if(dir[j] == preds[j][i])
-      {
-        predIdx[j] = i;
-      }
-    }
-    m_pcBinIf->encodeBin((predIdx[j] != -1)? 1 : 0, m_cCUIntraPredSCModel.get( 0, 0, 0 ) );
+      pcCU->getIntraDirPredictor(absPartIdx+partOffset*j, preds[j], COMPONENT_Y);
+      for(UInt i = 0; i < NUM_MOST_PROBABLE_MODES; i++)
+      {
+        if(dir[j] == preds[j][i])
+        {
+          predIdx[j] = i;
+        }
+      }
+      m_pcBinIf->encodeBin((predIdx[j] != -1)? 1 : 0, m_cCUIntraPredSCModel.get( 0, 0, 0 ) );
 #if NH_MV_ENC_DEC_TRAC
       DTRACE_CU("prev_intra_luma_pred_flag", (predIdx[j] != -1)? 1 : 0); 
 #endif
-#if NH_3D_DMM
+#if NH_3D
     }
 #endif
@@ -1037,43 +995,43 @@
   for (j=0;j<partNum;j++)
   {
-#if NH_3D_DMM
+#if NH_3D
     if( pcCU->getIntraDir( CHANNEL_TYPE_LUMA, absPartIdx+partOffset*j ) < NUM_INTRA_MODE )
     {
 #endif
-    if(predIdx[j] != -1)
-    {
-      m_pcBinIf->encodeBinEP( predIdx[j] ? 1 : 0 );
-      if (predIdx[j])
-      {
-        m_pcBinIf->encodeBinEP( predIdx[j]-1 );
-      }
+      if(predIdx[j] != -1)
+      {
+        m_pcBinIf->encodeBinEP( predIdx[j] ? 1 : 0 );
+        if (predIdx[j])
+        {
+          m_pcBinIf->encodeBinEP( predIdx[j]-1 );
+        }
 #if NH_MV_ENC_DEC_TRAC
         DTRACE_CU("mpm_idx", predIdx[j] ); 
 #endif
-    }
-    else
-    {
-      if (preds[j][0] > preds[j][1])
-      {
-        std::swap(preds[j][0], preds[j][1]);
-      }
-      if (preds[j][0] > preds[j][2])
-      {
-        std::swap(preds[j][0], preds[j][2]);
-      }
-      if (preds[j][1] > preds[j][2])
-      {
-        std::swap(preds[j][1], preds[j][2]);
-      }
-      for(Int i = (Int(NUM_MOST_PROBABLE_MODES) - 1); i >= 0; i--)
-      {
-        dir[j] = dir[j] > preds[j][i] ? dir[j] - 1 : dir[j];
-      }
-      m_pcBinIf->encodeBinsEP( dir[j], 5 );
+      }
+      else
+      {
+        if (preds[j][0] > preds[j][1])
+        {
+          std::swap(preds[j][0], preds[j][1]);
+        }
+        if (preds[j][0] > preds[j][2])
+        {
+          std::swap(preds[j][0], preds[j][2]);
+        }
+        if (preds[j][1] > preds[j][2])
+        {
+          std::swap(preds[j][1], preds[j][2]);
+        }
+        for(Int i = (Int(NUM_MOST_PROBABLE_MODES) - 1); i >= 0; i--)
+        {
+          dir[j] = dir[j] > preds[j][i] ? dir[j] - 1 : dir[j];
+        }
+        m_pcBinIf->encodeBinsEP( dir[j], 5 );
 #if NH_MV_ENC_DEC_TRAC
         DTRACE_CU("rem_intra_luma_pred_mode", dir[j] ); 
 #endif
-    }
-#if NH_3D_DMM
+      }
+#if NH_3D
     }
 #endif
@@ -1721,5 +1679,5 @@
     else
     {
-      beValid = pcCU->getSlice()->getPPS()->getSignHideFlag();
+      beValid = pcCU->getSlice()->getPPS()->getSignDataHidingEnabledFlag();
     }
   }
@@ -2168,5 +2126,5 @@
  ****************************************************************************
  */
-Void TEncSbac::estBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType )
+Void TEncSbac::estBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType, COEFF_SCAN_TYPE scanType )
 {
   estCBFBit( pcEstBitsSbac );
@@ -2178,5 +2136,5 @@
 
   // encode last significant position
-  estLastSignificantPositionBit( pcEstBitsSbac, width, height, chType );
+  estLastSignificantPositionBit( pcEstBitsSbac, width, height, chType, scanType );
 
   // encode significant coefficients
@@ -2312,6 +2270,11 @@
  */
 
-Void TEncSbac::estLastSignificantPositionBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType )
-{
+Void TEncSbac::estLastSignificantPositionBit( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType, COEFF_SCAN_TYPE scanType )
+{
+  if (scanType == SCAN_VER)
+  {
+    swap(width, height);
+  }
+
   //--------------------------------------------------------------------------------------------------.
 
@@ -2459,22 +2422,15 @@
 }
 
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
+#if NH_3D
 Void TEncSbac::codeDeltaDC( TComDataCU* pcCU, UInt absPartIdx )
 {
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   if( !(pcCU->getSDCFlag( absPartIdx )) )
-#endif
-#if NH_3D_DMM
     if( !(pcCU->isIntra( absPartIdx ) && isDmmMode( pcCU->getIntraDir( CHANNEL_TYPE_LUMA, absPartIdx ) )) )
-#endif
     assert( 0 );
 
   UInt uiNumSegments = 1;
-#if NH_3D_DMM
   uiNumSegments = isDmmMode( pcCU->getIntraDir( CHANNEL_TYPE_LUMA, absPartIdx ) ) ? 2 : 1;
-#endif
 
   UInt hasDeltaDC = 1;
-#if NH_3D_SDC_INTRA
   if( pcCU->isIntra( absPartIdx ) && pcCU->getSDCFlag( absPartIdx ))
   {
@@ -2489,5 +2445,4 @@
     m_pcBinIf->encodeBin( hasDeltaDC, m_cDdcFlagSCModel.get( 0, 0, 0 ) );
   }
-#endif
 
   if( hasDeltaDC )
@@ -2498,5 +2453,4 @@
       if( pcCU->isIntra( absPartIdx ) )
       {
-#if NH_3D_SDC_INTRA
         if( pcCU->getSDCFlag( absPartIdx ) )
         {
@@ -2505,18 +2459,11 @@
         else
         {
-#endif
-#if NH_3D_DMM
         deltaDC = pcCU->getDmmDeltaDC( getDmmType( pcCU->getIntraDir( CHANNEL_TYPE_LUMA, absPartIdx ) ), segment, absPartIdx );
-#endif
-#if NH_3D_SDC_INTRA
-        }
-#endif
-      }
-#if NH_3D_SDC_INTER
+        }
+      }
       else
       {
         deltaDC = pcCU->getSDCSegmentDCOffset( segment, absPartIdx );
       }
-#endif
       xCodeDeltaDC( deltaDC, uiNumSegments );
     }
@@ -2565,7 +2512,5 @@
   return;
 }
-#endif
-
-#if NH_3D_DMM
+
 Void TEncSbac::xCodeIntraDepthMode( TComDataCU* pcCU, UInt absPartIdx )
 {
@@ -2612,7 +2557,5 @@
   }
 }
-#endif
-
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
+
 Void TEncSbac::codeSDCFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
@@ -2624,7 +2567,5 @@
 }
 
-#endif
-
-#if NH_3D_DBBP
+
 Void TEncSbac::codeDBBPFlag( TComDataCU* pcCU, UInt uiAbsPartIdx )
 {
Index: /trunk/source/Lib/TLibEncoder/TEncSbac.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncSbac.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncSbac.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -80,5 +80,5 @@
   Void  load                   ( const TEncSbac* pSrc  );
   Void  loadIntraDirMode       ( const TEncSbac* pScr, const ChannelType chType  );
-#if NH_3D_DMM
+#if NH_3D
   Void  loadIntraDepthDmm      ( const TEncSbac* pSrc );
 #endif
@@ -115,9 +115,7 @@
   Void  xWriteEpExGolomb     ( UInt uiSymbol, UInt uiCount );
   Void  xWriteCoefRemainExGolomb ( UInt symbol, UInt &rParam, const Bool useLimitedPrefixLength, const Int maxLog2TrDynamicRange );
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
+#if NH_3D
   Void  xWriteExGolombLevelDdc( UInt uiSymbol );
   Void  xCodeDeltaDC         ( Pel valDeltaDC, UInt uiNumSeg );
-#endif
-#if NH_3D_DMM
   Void  xCodeIntraDepthMode  ( TComDataCU* pcCU, UInt absPartIdx );
   Void  xCodeDmmData         ( TComDataCU* pcCU, UInt absPartIdx );
@@ -138,22 +136,14 @@
   Void codeCUTransquantBypassFlag( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void codeSkipFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
-#if NH_3D_DIS
+#if NH_3D
   Void codeDIS           ( TComDataCU* pcCU, UInt uiAbsPartIdx );
 #endif
   Void codeMergeFlag     ( TComDataCU* pcCU, UInt uiAbsPartIdx );
   Void codeMergeIndex    ( TComDataCU* pcCU, UInt uiAbsPartIdx );
-#if NH_3D_ARP
+#if NH_3D
   Void codeARPW          ( TComDataCU* pcCU, UInt uiAbsPartIdx );
-#endif
-#if NH_3D_IC
   Void codeICFlag        ( TComDataCU* pcCU, UInt uiAbsPartIdx );
-#endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   Void  codeDeltaDC      ( TComDataCU* pcCU, UInt absPartIdx );
-#endif
-#if NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   Void codeSDCFlag       ( TComDataCU* pcCU, UInt uiAbsPartIdx );
-#endif
-#if NH_3D_DBBP
   Void codeDBBPFlag      ( TComDataCU* pcCU, UInt uiAbsPartIdx );
 #endif
@@ -188,9 +178,9 @@
   // -------------------------------------------------------------------------------------------------------------------
 
-  Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType);
+  Void estBit               (estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType, COEFF_SCAN_TYPE scanType);
   Void estCBFBit                     ( estBitsSbacStruct* pcEstBitsSbac );
   Void estSignificantCoeffGroupMapBit( estBitsSbacStruct* pcEstBitsSbac, ChannelType chType );
   Void estSignificantMapBit          ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType );
-  Void estLastSignificantPositionBit ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType );
+  Void estLastSignificantPositionBit ( estBitsSbacStruct* pcEstBitsSbac, Int width, Int height, ChannelType chType, COEFF_SCAN_TYPE scanType );
   Void estSignificantCoefficientsBit ( estBitsSbacStruct* pcEstBitsSbac, ChannelType chType );
 
@@ -204,5 +194,5 @@
   ContextModel3DBuffer m_cCUSplitFlagSCModel;
   ContextModel3DBuffer m_cCUSkipFlagSCModel;
-#if NH_3D_DIS
+#if NH_3D
   ContextModel3DBuffer m_cCUDISFlagSCModel;
   ContextModel3DBuffer m_cCUDISTypeSCModel;
@@ -210,8 +200,6 @@
   ContextModel3DBuffer m_cCUMergeFlagExtSCModel;
   ContextModel3DBuffer m_cCUMergeIdxExtSCModel;
-#if NH_3D_ARP
+#if NH_3D
   ContextModel3DBuffer m_cCUPUARPWSCModel;
-#endif
-#if NH_3D_IC
   ContextModel3DBuffer m_cCUICFlagSCModel;
 #endif
@@ -248,18 +236,12 @@
   ContextModel3DBuffer m_ChromaQpAdjIdcSCModel;
 
-#if NH_3D_DMM
+#if NH_3D
   ContextModel3DBuffer m_cNotDmmFlagSCModel;
   ContextModel3DBuffer m_cDmmModeSCModel;
-#endif
-#if NH_3D_DMM || NH_3D_SDC_INTRA || NH_3D_SDC_INTER
   ContextModel3DBuffer m_cDdcDataSCModel;
   ContextModel3DBuffer m_cSDCFlagSCModel;
-#endif
-#if NH_3D_SDC_INTRA  
   ContextModel3DBuffer m_cSDCResidualFlagSCModel;
   ContextModel3DBuffer m_cSDCResidualSCModel;
   ContextModel3DBuffer m_cDdcFlagSCModel;
-#endif
-#if NH_3D_DBBP
   ContextModel3DBuffer m_cDBBPFlagSCModel;
 #endif
Index: /trunk/source/Lib/TLibEncoder/TEncSearch.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncSearch.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -316,8 +316,6 @@
   const Pel* const  piRefSrch = rcStruct.piRefY + iSearchY * rcStruct.iYStride + iSearchX;
 
-#if NH_3D_IC
+#if NH_3D
   m_cDistParam.bUseIC = pcPatternKey->getICFlag();
-#endif
-#if NH_3D_SDC_INTER
   m_cDistParam.bUseSDCMRSAD = pcPatternKey->getSDCMRSADFlag();
 #endif
@@ -848,5 +846,30 @@
   const TComMv* pcMvRefine = (iFrac == 2 ? s_acMvRefineH : s_acMvRefineQ);
 
+#if MCTS_ENC_CHECK
+  UInt maxRefinements = 9;
+  Int mvShift = 2;
+
+  // filter length of sub-sample generation filter to be considered
+  const UInt LumaLTSampleOffset = 3;
+  const UInt LumaRBSampleOffset = 4;
+
+  if (m_pcEncCfg->getTMCTSSEITileConstraint())
+  {
+    // if close to tile borders
+    if ( pcPatternKey->getROIYPosX() + (baseRefMv.getHor() >> mvShift ) < pcPatternKey->getTileLeftTopPelPosX() +  LumaLTSampleOffset ||
+         pcPatternKey->getROIYPosY() + (baseRefMv.getVer() >> mvShift ) < pcPatternKey->getTileLeftTopPelPosY() +  LumaLTSampleOffset ||
+         pcPatternKey->getROIYPosX() + (baseRefMv.getHor() >> mvShift)  > pcPatternKey->getTileRightBottomPelPosX() - pcPatternKey->getROIYWidth() - LumaRBSampleOffset ||
+         pcPatternKey->getROIYPosY() + (baseRefMv.getVer() >> mvShift)  > pcPatternKey->getTileRightBottomPelPosY() - pcPatternKey->getROIYHeight() - LumaRBSampleOffset  
+       )
+    {
+      // only allow full pel positions to avoid filter dependency
+      maxRefinements = 1;
+    }
+  }  
+
+  for (UInt i = 0; i < maxRefinements; i++)
+#else
   for (UInt i = 0; i < 9; i++)
+#endif
   {
     TComMv cMvTest = pcMvRefine[i];
@@ -868,8 +891,6 @@
 
     setDistParamComp(COMPONENT_Y);
-#if NH_3D_IC
+#if NH_3D
     m_cDistParam.bUseIC = pcPatternKey->getICFlag();
-#endif
-#if NH_3D_SDC_INTER
     m_cDistParam.bUseSDCMRSAD = pcPatternKey->getSDCMRSADFlag();
 #endif
@@ -1020,56 +1041,53 @@
       if( !pcCU->getSlice()->isIntra() )
       {
-        if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+        if (pcCU->getSlice()->getPPS()->getTransquantBypassEnabledFlag())
         {
           m_pcEntropyCoder->encodeCUTransquantBypassFlag( pcCU, 0, true );
         }
         m_pcEntropyCoder->encodeSkipFlag( pcCU, 0, true );
-#if NH_3D_DIS
+#if NH_3D
         m_pcEntropyCoder->encodeDIS(pcCU, 0, true );
         if(!pcCU->getDISFlag(uiAbsPartIdx))
 #endif
-        m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
-      }
-#if NH_3D_DIS
+          m_pcEntropyCoder->encodePredMode( pcCU, 0, true );
+      }
+#if NH_3D
       else
       {
         m_pcEntropyCoder->encodeDIS(pcCU, 0, true );
       }
-#endif
-#if NH_3D_DIS
       if(!pcCU->getDISFlag(uiAbsPartIdx))
       {
 #endif
-      m_pcEntropyCoder  ->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
-
-      if (pcCU->isIntra(0) && pcCU->getPartitionSize(0) == SIZE_2Nx2N )
-      {
-        m_pcEntropyCoder->encodeIPCMInfo( pcCU, 0, true );
-
-        if ( pcCU->getIPCMFlag (0))
-        {
-#if NH_3D_SDC_INTRA
+        m_pcEntropyCoder  ->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
+
+        if (pcCU->isIntra(0) && pcCU->getPartitionSize(0) == SIZE_2Nx2N )
+        {
+          m_pcEntropyCoder->encodeIPCMInfo( pcCU, 0, true );
+
+          if ( pcCU->getIPCMFlag (0))
+          {
+#if NH_3D
             m_pcEntropyCoder->encodeSDCFlag( pcCU, 0, true );
 #endif
-          return;
-        }
-      }
-#if NH_3D_DIS
-    }
-#endif
-  }
-#if NH_3D_DIS
+            return;
+          }
+        }
+#if NH_3D
+      }
+#endif
+    }
+#if NH_3D
     if(!pcCU->getDISFlag(uiAbsPartIdx))
     {
 #endif
-    // luma prediction mode
-    if( pcCU->getPartitionSize(0) == SIZE_2Nx2N )
-    {
-      if (uiAbsPartIdx==0)
-      {
-        m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, 0 );
-#if NH_3D_SDC_INTRA
+      // luma prediction mode
+      if( pcCU->getPartitionSize(0) == SIZE_2Nx2N )
+      {
+        if (uiAbsPartIdx==0)
+        {
+          m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, 0 );
+#if NH_3D
           m_pcEntropyCoder->encodeSDCFlag( pcCU, 0, true );
-#if NH_3D_DMM
           if( pcCU->getSlice()->getIsDepth() && ( !pcCU->getSDCFlag( 0 ) ) && isDmmMode( pcCU->getIntraDir( CHANNEL_TYPE_LUMA, 0 ) ) )
           {
@@ -1077,27 +1095,22 @@
           }
 #endif
-#endif
-      }
-    }
-    else
-    {
-      UInt uiQNumParts = pcCU->getTotalNumPart() >> 2;
-      if (uiTrDepth>0 && (uiAbsPartIdx%uiQNumParts)==0)
-      {
-        m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiAbsPartIdx );
-#if NH_3D_SDC_INTRA
+        }
+      }
+      else
+      {
+        UInt uiQNumParts = pcCU->getTotalNumPart() >> 2;
+        if (uiTrDepth>0 && (uiAbsPartIdx%uiQNumParts)==0)
+        {
+          m_pcEntropyCoder->encodeIntraDirModeLuma ( pcCU, uiAbsPartIdx );
+#if NH_3D
           if( uiAbsPartIdx == 0 )  
           {
             m_pcEntropyCoder->encodeSDCFlag( pcCU, 0, true );
           }
-#if NH_3D_DMM
           if( pcCU->getSlice()->getIsDepth() && ( !pcCU->getSDCFlag( uiAbsPartIdx ) ) && isDmmMode( pcCU->getIntraDir( CHANNEL_TYPE_LUMA, uiAbsPartIdx ) ) )
           {
             m_pcEntropyCoder->encodeDeltaDC( pcCU, uiAbsPartIdx );
           }
-#endif
-#endif
-#if NH_3D_DIS
-      }
+        }
 #endif
       }
@@ -1180,5 +1193,5 @@
                                       DEBUG_STRING_FN_DECLARE(sDebug)
                                            ,Int         default0Save1Load2
-#if NH_3D_ENC_DEPTH
+#if NH_3D
                                           , Bool        zeroResiFlag
 #endif
@@ -1253,5 +1266,5 @@
 
     //===== get prediction signal =====
-#if NH_3D_DMM
+#if NH_3D
     if( bIsLuma && isDmmMode( uiChFinalMode ) )
     {
@@ -1262,5 +1275,5 @@
 #endif
     predIntraAng( compID, uiChFinalMode, piOrg, uiStride, piPred, uiStride, rTu, bUseFilteredPredictions );
-#if NH_3D_DMM
+#if NH_3D
     }
 #endif
@@ -1309,5 +1322,5 @@
     for( UInt uiY = 0; uiY < uiHeight; uiY++ )
     {
-#if NH_3D_ENC_DEPTH
+#if NH_3D
       if( zeroResiFlag )
       {
@@ -1318,16 +1331,15 @@
       {
 #endif
-      for( UInt uiX = 0; uiX < uiWidth; uiX++ )
-      {
-        pResi[ uiX ] = pOrg[ uiX ] - pPred[ uiX ];
-      }
-
-      pOrg  += uiStride;
-      pResi += uiStride;
-      pPred += uiStride;
-#if NH_3D_ENC_DEPTH
-      }
-#endif
-
+        for( UInt uiX = 0; uiX < uiWidth; uiX++ )
+        {
+          pResi[ uiX ] = pOrg[ uiX ] - pPred[ uiX ];
+        }
+
+        pOrg  += uiStride;
+        pResi += uiStride;
+        pPred += uiStride;
+#if NH_3D
+      }
+#endif
     }
   }
@@ -1353,5 +1365,6 @@
   if( useTransformSkip ? m_pcEncCfg->getUseRDOQTS() : m_pcEncCfg->getUseRDOQ() )
   {
-    m_pcEntropyCoder->estimateBit( m_pcTrQuant->m_pcEstBitsSbac, uiWidth, uiHeight, chType );
+    COEFF_SCAN_TYPE scanType = COEFF_SCAN_TYPE(pcCU->getCoefScanIdx(uiAbsPartIdx, uiWidth, uiHeight, compID));
+    m_pcEntropyCoder->estimateBit( m_pcTrQuant->m_pcEstBitsSbac, uiWidth, uiHeight, chType, scanType );
   }
 
@@ -1518,5 +1531,5 @@
                                     TComTU&     rTu
                                     DEBUG_STRING_FN_DECLARE(sDebug)
-#if NH_3D_ENC_DEPTH
+#if NH_3D
                                   , Bool        zeroResiFlag
 #endif                                
@@ -1576,5 +1589,5 @@
   }
 #endif
-#if NH_3D_DMM
+#if NH_3D
   if( isDmmMode( pcCU->getIntraDir( CHANNEL_TYPE_LUMA, uiAbsPartIdx ) ) )
   {
@@ -1707,5 +1720,5 @@
       //----- code luma/chroma block with given intra prediction mode and store Cbf-----
       dSingleCost   = 0.0;
-#if NH_3D_ENC_DEPTH
+#if NH_3D
       xIntraCodingTUBlock( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaSingle, false, uiSingleDistLuma, COMPONENT_Y, rTu DEBUG_STRING_PASS_INTO(sDebug), 0, zeroResiFlag );
 #else
@@ -1886,5 +1899,5 @@
 }
 
-#if NH_3D_DIS
+#if NH_3D
 #if NH_3D_VSO
 Void TEncSearch::xIntraCodingDIS( TComDataCU* pcCU, UInt uiAbsPartIdx, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, Dist&       ruiDist, Double& dRDCost, UInt uiPredMode )
@@ -1984,6 +1997,5 @@
     dRDCost = m_pcRdCost->calcRdCost( uiBits, ruiDist );
 }
-#endif
-#if NH_3D_SDC_INTRA
+
 #if NH_3D_VSO
 Void TEncSearch::xIntraCodingSDC( TComDataCU* pcCU, UInt uiAbsPartIdx, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, Dist&       ruiDist, Double& dRDCost, Bool bZeroResidual, Int iSDCDeltaResi  )
@@ -1991,6 +2003,4 @@
 Void TEncSearch::xIntraCodingSDC( TComDataCU* pcCU, UInt uiAbsPartIdx, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, Distortion& ruiDist, Double& dRDCost, Bool bZeroResidual, Int iSDCDeltaResi  )
 #endif
-
-
 {
   UInt uiWidth        = pcCU->getWidth ( 0 );
@@ -2016,5 +2026,5 @@
   Bool* pbMask = NULL;
   UInt uiMaskStride = 0;
-#if NH_3D_DMM
+
   if( isDmmMode( uiLumaPredMode ) )
   {
@@ -2064,5 +2074,5 @@
   else // regular HEVC intra modes
   {
-#endif
+
     uiNumSegments = 1;
     
@@ -2125,7 +2135,5 @@
     predConstantSDC( piPred, uiStride, uiWidth, apDCPredValues[0] ); apDCPredValues[1] = 0;
     xCalcConstantSDC( piOrg, uiStride, uiWidth, apDCOrigValues[0] ); apDCOrigValues[1] = 0;
-#if NH_3D_DMM  
-  }
-#endif
+  }
 
   for( UInt uiSegment = 0; uiSegment < uiNumSegments; uiSegment++ )
@@ -2134,12 +2142,7 @@
     Pel pDCRec = ( !bZeroResidual ) ? apDCOrigValues[uiSegment] : apDCPredValues[uiSegment];
     // get residual (idx)
-#if NH_3D_DLT
     Pel pResidualIdx = pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), pDCRec ) - pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), apDCPredValues[uiSegment] );
-#else
-    Pel pResidualIdx = pDCRec - apDCPredValues[uiSegment];
-#endif
     if( !bZeroResidual )
     {
-#if NH_3D_DLT
       Pel   pPredIdx    = pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), apDCPredValues[uiSegment] );
       Int   pTestIdx    = pPredIdx + pResidualIdx + iSDCDeltaResi;
@@ -2148,7 +2151,4 @@
         pResidualIdx += iSDCDeltaResi;
       }
-#else
-      pResidualIdx += iSDCDeltaResi;
-#endif
     }
     // save SDC DC offset
@@ -2160,5 +2160,4 @@
   for( UInt uiSegment = 0; uiSegment < uiNumSegments; uiSegment++ )
   {
-#if NH_3D_DLT
     Pel   pPredIdx    = pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), apDCPredValues[uiSegment] );
     Pel   pResiIdx    = pcCU->getSDCSegmentDCOffset(uiSegment, uiAbsPartIdx);
@@ -2166,7 +2165,4 @@
 
     apDCResiValues[uiSegment]  = pRecoValue - apDCPredValues[uiSegment];
-#else
-    apDCResiValues[uiSegment]  = pcCU->getSDCSegmentDCOffset(uiSegment, uiAbsPartIdx);
-#endif
   }
 
@@ -2212,7 +2208,8 @@
   }
 
-#if NH_3D_DMM
-  if( pbMask ) { delete[] pbMask; }
-#endif
+  if( pbMask ) 
+  { 
+    delete[] pbMask; 
+  }
 
   //===== determine distortion =====  
@@ -2225,9 +2222,5 @@
 #endif
   {
-#if NH_3D_FIX_INTRA_SDC_VSO_OFF
     ruiDist = m_pcRdCost->getDistPart( bitDepthY, piPred, uiStride, piOrg, uiStride, uiWidth, uiHeight, COMPONENT_Y );
-#else
-    ruiDist = m_pcRdCost->getDistPart( bitDepthY, piPred, uiStride, piOrg, uiStride, uiWidth, uiHeight, COMPONENT_Y, DF_SAD );
-#endif
   }
 
@@ -2238,5 +2231,5 @@
   if( !pcCU->getSlice()->isIntra() )
   {
-    if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+    if (pcCU->getSlice()->getPPS()->getTransquantBypassEnabledFlag())
     {
       m_pcEntropyCoder->encodeCUTransquantBypassFlag( pcCU, 0, true );
@@ -2737,5 +2730,5 @@
 }
 
-#if NH_3D_DIS
+#if NH_3D
 Void TEncSearch::estIntraPredDIS( TComDataCU* pcCU, 
                                   TComYuv*    pcOrgYuv, 
@@ -2746,7 +2739,6 @@
                                   Bool        bLumaOnly )
 {
-#if NH_MV
+
   D_PRINT_INC_INDENT(g_traceModeCheck, "estIntraPredDis");
-#endif
 
   UInt    uiDepth        = pcCU->getDepth(0);
@@ -2828,5 +2820,5 @@
                                Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE]
                                DEBUG_STRING_FN_DECLARE(sDebug)
-#if NH_3D_ENC_DEPTH
+#if NH_3D
                              , Bool        bOnlyIVP
 #endif
@@ -2908,5 +2900,5 @@
     assert (tuRecurseWithPU.ProcessComponentSection(COMPONENT_Y));
     initIntraPatternChType( tuRecurseWithPU, COMPONENT_Y, true DEBUG_STRING_PASS_INTO(sTemp2) );
-#if NH_3D_ENC_DEPTH
+#if NH_3D
     if( bOnlyIVP )
     {
@@ -2917,15 +2909,131 @@
 #endif
 
-    Bool doFastSearch = (numModesForFullRD != numModesAvailable);
-    if (doFastSearch)
-    {
-      assert(numModesForFullRD < numModesAvailable);
-
-      for( Int i=0; i < numModesForFullRD; i++ )
-      {
-        CandCostList[ i ] = MAX_DOUBLE;
-      }
-      CandNum = 0;
-
+      Bool doFastSearch = (numModesForFullRD != numModesAvailable);
+      if (doFastSearch)
+      {
+        assert(numModesForFullRD < numModesAvailable);
+
+        for( Int i=0; i < numModesForFullRD; i++ )
+        {
+          CandCostList[ i ] = MAX_DOUBLE;
+        }
+        CandNum = 0;
+
+        const TComRectangle &puRect=tuRecurseWithPU.getRect(COMPONENT_Y);
+        const UInt uiAbsPartIdx=tuRecurseWithPU.GetAbsPartIdxTU();
+
+        Pel* piOrg         = pcOrgYuv ->getAddr( COMPONENT_Y, uiAbsPartIdx );
+        Pel* piPred        = pcPredYuv->getAddr( COMPONENT_Y, uiAbsPartIdx );
+        UInt uiStride      = pcPredYuv->getStride( COMPONENT_Y );
+        DistParam distParam;
+        const Bool bUseHadamard=pcCU->getCUTransquantBypass(0) == 0;
+        m_pcRdCost->setDistParam(distParam, sps.getBitDepth(CHANNEL_TYPE_LUMA), piOrg, uiStride, piPred, uiStride, puRect.width, puRect.height, bUseHadamard);
+
+#if NH_3D
+        distParam.bUseIC = false;
+        distParam.bUseSDCMRSAD = false;
+#endif
+        distParam.bApplyWeight = false;
+        for( Int modeIdx = 0; modeIdx < numModesAvailable; modeIdx++ )
+        {
+          UInt       uiMode = modeIdx;
+#if !NH_3D_VSO
+          Distortion uiSad  = 0;
+#endif
+#if NH_MV
+          D_PRINT_INC_INDENT(g_traceModeCheck, "preTest; uiMode " + n2s(uiMode) );
+#endif
+          const Bool bUseFilter=TComPrediction::filteringIntraReferenceSamples(COMPONENT_Y, uiMode, puRect.width, puRect.height, chFmt, sps.getSpsRangeExtension().getIntraSmoothingDisabledFlag());
+
+          predIntraAng( COMPONENT_Y, uiMode, piOrg, uiStride, piPred, uiStride, tuRecurseWithPU, bUseFilter, TComPrediction::UseDPCMForFirstPassIntraEstimation(tuRecurseWithPU, uiMode) );
+#if NH_3D_VSO // M34
+          Dist uiSad;           
+          if ( m_pcRdCost->getUseVSO() )
+          {
+            if ( m_pcRdCost->getUseEstimatedVSD() )
+            {          
+              uiSad = (Dist) ( m_pcRdCost->getDistPartVSD( pcCU, uiPartOffset, distParam.bitDepth , piPred, uiStride, piOrg, uiStride, distParam.iCols, distParam.iRows, true ) );
+            }
+            else
+            {    
+              uiSad = m_pcRdCost->getDistPartVSO( pcCU, uiPartOffset, distParam.bitDepth , piPred, uiStride, piOrg, uiStride, distParam.iCols, distParam.iRows, true );
+            }
+          }
+          else
+          {
+            uiSad = distParam.DistFunc(&distParam);
+          }
+#else        
+          // use hadamard transform here
+          uiSad+=distParam.DistFunc(&distParam);
+#endif
+
+          UInt   iModeBits = 0;
+
+          // NB xModeBitsIntra will not affect the mode for chroma that may have already been pre-estimated.
+          iModeBits+=xModeBitsIntra( pcCU, uiMode, uiPartOffset, uiDepth, CHANNEL_TYPE_LUMA );
+
+#if NH_3D_VSO // M35
+          Double dLambda;
+          if ( m_pcRdCost->getUseLambdaScaleVSO() )
+          {
+            dLambda = m_pcRdCost->getUseRenModel() ? m_pcRdCost->getLambdaVSO() : sqrtLambdaForFirstPass;
+          }
+          else        
+          {
+            dLambda = m_pcRdCost->getSqrtLambda();        
+          }
+
+          Double cost      = (Double)uiSad + (Double)iModeBits * dLambda;
+#else
+          Double cost      = (Double)uiSad + (Double)iModeBits * sqrtLambdaForFirstPass;
+#endif
+
+#if DEBUG_INTRA_SEARCH_COSTS
+          std::cout << "1st pass mode " << uiMode << " SAD = " << uiSad << ", mode bits = " << iModeBits << ", cost = " << cost << "\n";
+#endif
+
+          CandNum += xUpdateCandList( uiMode, cost, numModesForFullRD, uiRdModeList, CandCostList );
+#if NH_MV
+          D_DEC_INDENT( g_traceModeCheck ); 
+#endif
+        }
+
+        if (m_pcEncCfg->getFastUDIUseMPMEnabled())
+        {
+          Int uiPreds[NUM_MOST_PROBABLE_MODES] = {-1, -1, -1};
+
+          Int iMode = -1;
+          pcCU->getIntraDirPredictor( uiPartOffset, uiPreds, COMPONENT_Y, &iMode );
+
+          const Int numCand = ( iMode >= 0 ) ? iMode : Int(NUM_MOST_PROBABLE_MODES);
+
+          for( Int j=0; j < numCand; j++)
+          {
+            Bool mostProbableModeIncluded = false;
+            Int mostProbableMode = uiPreds[j];
+
+            for( Int i=0; i < numModesForFullRD; i++)
+            {
+              mostProbableModeIncluded |= (mostProbableMode == uiRdModeList[i]);
+            }
+            if (!mostProbableModeIncluded)
+            {
+              uiRdModeList[numModesForFullRD++] = mostProbableMode;
+            }
+          }
+        }
+      }
+      else
+      {
+        for( Int i=0; i < numModesForFullRD; i++)
+        {
+          uiRdModeList[i] = i;
+        }
+      }
+#if NH_3D
+    }
+    if( m_pcEncCfg->getIsDepth() )
+    {
       const TComRectangle &puRect=tuRecurseWithPU.getRect(COMPONENT_Y);
       const UInt uiAbsPartIdx=tuRecurseWithPU.GetAbsPartIdxTU();
@@ -2934,131 +3042,8 @@
       Pel* piPred        = pcPredYuv->getAddr( COMPONENT_Y, uiAbsPartIdx );
       UInt uiStride      = pcPredYuv->getStride( COMPONENT_Y );
-      DistParam distParam;
-      const Bool bUseHadamard=pcCU->getCUTransquantBypass(0) == 0;
-      m_pcRdCost->setDistParam(distParam, sps.getBitDepth(CHANNEL_TYPE_LUMA), piOrg, uiStride, piPred, uiStride, puRect.width, puRect.height, bUseHadamard);
-
-#if NH_3D
-      distParam.bUseIC = false;
-#endif
-#if NH_3D_SDC_INTER
-      distParam.bUseSDCMRSAD = false;
-#endif
-      distParam.bApplyWeight = false;
-      for( Int modeIdx = 0; modeIdx < numModesAvailable; modeIdx++ )
-      {
-        UInt       uiMode = modeIdx;
-#if !NH_3D_VSO
-        Distortion uiSad  = 0;
-#endif
-#if NH_MV
-        D_PRINT_INC_INDENT(g_traceModeCheck, "preTest; uiMode " + n2s(uiMode) );
-#endif
-
-        const Bool bUseFilter=TComPrediction::filteringIntraReferenceSamples(COMPONENT_Y, uiMode, puRect.width, puRect.height, chFmt, sps.getSpsRangeExtension().getIntraSmoothingDisabledFlag());
-
-        predIntraAng( COMPONENT_Y, uiMode, piOrg, uiStride, piPred, uiStride, tuRecurseWithPU, bUseFilter, TComPrediction::UseDPCMForFirstPassIntraEstimation(tuRecurseWithPU, uiMode) );
-#if NH_3D_VSO // M34
-        Dist uiSad;           
-        if ( m_pcRdCost->getUseVSO() )
-        {
-          if ( m_pcRdCost->getUseEstimatedVSD() )
-          {          
-            uiSad = (Dist) ( m_pcRdCost->getDistPartVSD( pcCU, uiPartOffset, distParam.bitDepth , piPred, uiStride, piOrg, uiStride, distParam.iCols, distParam.iRows, true ) );
-          }
-          else
-          {    
-            uiSad = m_pcRdCost->getDistPartVSO( pcCU, uiPartOffset, distParam.bitDepth , piPred, uiStride, piOrg, uiStride, distParam.iCols, distParam.iRows, true );
-          }
-        }
-        else
-        {
-          uiSad = distParam.DistFunc(&distParam);
-        }
-#else        
-        // use hadamard transform here
-        uiSad+=distParam.DistFunc(&distParam);
-#endif
-
-        UInt   iModeBits = 0;
-
-        // NB xModeBitsIntra will not affect the mode for chroma that may have already been pre-estimated.
-        iModeBits+=xModeBitsIntra( pcCU, uiMode, uiPartOffset, uiDepth, CHANNEL_TYPE_LUMA );
-
-#if NH_3D_VSO // M35
-        Double dLambda;
-        if ( m_pcRdCost->getUseLambdaScaleVSO() )
-        {
-          dLambda = m_pcRdCost->getUseRenModel() ? m_pcRdCost->getLambdaVSO() : sqrtLambdaForFirstPass;
-        }
-        else        
-        {
-          dLambda = m_pcRdCost->getSqrtLambda();        
-        }
-
-        Double cost      = (Double)uiSad + (Double)iModeBits * dLambda;
-#else
-        Double cost      = (Double)uiSad + (Double)iModeBits * sqrtLambdaForFirstPass;
-#endif
-
-#if DEBUG_INTRA_SEARCH_COSTS
-        std::cout << "1st pass mode " << uiMode << " SAD = " << uiSad << ", mode bits = " << iModeBits << ", cost = " << cost << "\n";
-#endif
-
-        CandNum += xUpdateCandList( uiMode, cost, numModesForFullRD, uiRdModeList, CandCostList );
-#if NH_MV
-        D_DEC_INDENT( g_traceModeCheck ); 
-#endif
-      }
-
-      if (m_pcEncCfg->getFastUDIUseMPMEnabled())
-      {
-      Int uiPreds[NUM_MOST_PROBABLE_MODES] = {-1, -1, -1};
-
-      Int iMode = -1;
-      pcCU->getIntraDirPredictor( uiPartOffset, uiPreds, COMPONENT_Y, &iMode );
-
-      const Int numCand = ( iMode >= 0 ) ? iMode : Int(NUM_MOST_PROBABLE_MODES);
-
-      for( Int j=0; j < numCand; j++)
-      {
-        Bool mostProbableModeIncluded = false;
-        Int mostProbableMode = uiPreds[j];
-
-        for( Int i=0; i < numModesForFullRD; i++)
-        {
-          mostProbableModeIncluded |= (mostProbableMode == uiRdModeList[i]);
-        }
-        if (!mostProbableModeIncluded)
-        {
-          uiRdModeList[numModesForFullRD++] = mostProbableMode;
-        }
-      }
-    }
-    }
-    else
-    {
-      for( Int i=0; i < numModesForFullRD; i++)
-      {
-        uiRdModeList[i] = i;
-      }
-    }
-#if NH_3D_ENC_DEPTH
-    }
-#endif
-
-#if NH_3D_DMM
-    if( m_pcEncCfg->getIsDepth() )
-    {
-      const TComRectangle &puRect=tuRecurseWithPU.getRect(COMPONENT_Y);
-      const UInt uiAbsPartIdx=tuRecurseWithPU.GetAbsPartIdxTU();
-
-      Pel* piOrg         = pcOrgYuv ->getAddr( COMPONENT_Y, uiAbsPartIdx );
-      Pel* piPred        = pcPredYuv->getAddr( COMPONENT_Y, uiAbsPartIdx );
-      UInt uiStride      = pcPredYuv->getStride( COMPONENT_Y );
 
       if( puRect.width >= DMM_MIN_SIZE && puRect.width <= DMM_MAX_SIZE &&  puRect.width == puRect.height &&
-          ((m_pcEncCfg->getUseDMM() &&  pcCU->getSlice()->getIntraSdcWedgeFlag()) || pcCU->getSlice()->getIntraContourFlag()) )
-      {
-#if NH_3D_ENC_DEPTH
+        ((m_pcEncCfg->getUseDMM() &&  pcCU->getSlice()->getIntraSdcWedgeFlag()) || pcCU->getSlice()->getIntraContourFlag()) )
+      {
         if( bOnlyIVP )
         {
@@ -3082,12 +3067,8 @@
           if( uiRdModeList[0] != PLANAR_IDX || varCU >= varThreshold )
           {
-#endif
             UInt startIdx = ( m_pcEncCfg->getUseDMM() &&  pcCU->getSlice()->getIntraSdcWedgeFlag() ) ? 0 : 1;
             UInt endIdx   = (                             pcCU->getSlice()->getIntraContourFlag()  ) ? 1 : 0;
             for( UInt dmmType = startIdx; dmmType <= endIdx; dmmType++ )
             {
-#if H_3D_FCO
-              if ( !(pcCU->getSlice()->getIvPic(false, pcCU->getSlice()->getViewIndex() )->getReconMark()) && (DMM4_IDX == dmmType ) ) { continue; }
-#endif
               Bool* biSegPattern  = new Bool[ puRect.width*puRect.height ];
               UInt  patternStride = puRect.width;
@@ -3114,13 +3095,11 @@
                 pcCU->setDmmDeltaDC( (DmmID)dmmType, 0, uiPartOffset, deltaDC1 );
                 pcCU->setDmmDeltaDC( (DmmID)dmmType, 1, uiPartOffset, deltaDC2 );
-  
+
                 uiRdModeList[ numModesForFullRD++ ] = (dmmType+DMM_OFFSET);
                 delete[] biSegPattern;
               }
             }
-#if NH_3D_ENC_DEPTH
           }
         }
-#endif
       }
     }
@@ -3134,5 +3113,5 @@
     DEBUG_STRING_NEW(sPU)
     UInt       uiBestPUMode  = 0;
-#if NH_3D_ENC_DEPTH
+#if NH_3D
     UInt    uiBestPUModeConv  = 0;
     UInt    uiSecondBestPUModeConv  = 0;
@@ -3147,13 +3126,9 @@
     Double     dBestPUCost   = MAX_DOUBLE;
 
-#if NH_3D_ENC_DEPTH
+#if NH_3D
     Double  dBestPUCostConv   = MAX_DOUBLE;
     UInt rdSDC = m_pcEncCfg->getIsDepth() ? numModesForFullRD : 0;
-#endif
-#if NH_3D_SDC_INTRA
     Bool    bBestUseSDC   = false;
     Pel     apBestDCOffsets[2] = {0,0};
-#endif
-#if NH_3D_ENC_DEPTH
     for( UInt uiMode = 0; uiMode < numModesForFullRD + rdSDC; uiMode++ )
 #else
@@ -3173,9 +3148,7 @@
     {
       // set luma prediction mode
-#if !NH_3D_ENC_DEPTH
+#if !NH_3D
       UInt uiOrgMode = uiRdModeList[uiMode];
-#endif
-
-#if NH_3D_ENC_DEPTH
+#else
       UInt uiOrgMode;
       if (uiMode < numModesForFullRD)
@@ -3214,16 +3187,10 @@
       pcCU->setIntraDirSubParts ( CHANNEL_TYPE_LUMA, uiOrgMode, uiPartOffset, uiDepth + uiInitTrDepth );
 
-#if NH_3D_SDC_INTRA
-#if NH_3D_ENC_DEPTH
+#if NH_3D
       Bool bTestSDC = ( ( m_pcEncCfg->getUseSDC() &&  pcCU->getSlice()->getIntraSdcWedgeFlag() ) && pcCU->getSDCAvailable(uiPartOffset) && uiMode >= numModesForFullRD);
-#else
-      Bool bTestSDC = ( m_pcEncCfg->getUseSDC() && pcCU->getSDCAvailable(uiPartOffset) );
-#endif
 
       for( UInt uiSDC=0; uiSDC<=(bTestSDC?1:0); uiSDC++ )
       {
-#if NH_3D_ENC_DEPTH
         if (!uiSDC && uiMode >= numModesForFullRD) continue;
-#endif
         pcCU->setSDCFlagSubParts( (uiSDC != 0), uiPartOffset, uiDepth + uiInitTrDepth );
         Double dOffsetCost[3] = {MAX_DOUBLE,MAX_DOUBLE,MAX_DOUBLE};
@@ -3258,8 +3225,5 @@
             }
           }
-#endif
-#if NH_3D_ENC_DEPTH
           Bool zeroResiTest = (pcCU->getSlice()->getIsDepth() && !pcCU->getSlice()->isIRAP());
-#if NH_3D_SDC_INTRA
           zeroResiTest = zeroResiTest || pcCU->getSDCFlag(uiPartOffset);
           if( uiSDC != 0 && iSDCDeltaResi != 0 )
@@ -3267,26 +3231,25 @@
             zeroResiTest = false;
           }
-#endif
           for( UInt zeroResi = 0; zeroResi <= ( zeroResiTest ? 1 : 0 ); zeroResi++ )
           {
 #endif
-      DEBUG_STRING_NEW(sMode)
-      // set context models
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
-
-      // determine residual for partition
+            DEBUG_STRING_NEW(sMode)
+              // set context models
+              m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+
+            // determine residual for partition
 #if NH_3D_VSO
-      Dist       uiPUDistY = 0;
+            Dist       uiPUDistY = 0;
 #else
-      Distortion uiPUDistY = 0;
-#endif
-      Double     dPUCost   = 0.0;
+            Distortion uiPUDistY = 0;
+#endif
+            Double     dPUCost   = 0.0;
 #if NH_3D_VSO // M36
-      if( m_pcRdCost->getUseRenModel() )
-      {
-        m_pcRdCost->setRenModelData( pcCU, uiPartOffset, pcOrgYuv, &tuRecurseWithPU );
-      }
-#endif
-#if NH_3D_SDC_INTRA
+            if( m_pcRdCost->getUseRenModel() )
+            {
+              m_pcRdCost->setRenModelData( pcCU, uiPartOffset, pcOrgYuv, &tuRecurseWithPU );
+            }
+#endif
+#if NH_3D
             if( pcCU->getSDCFlag(uiPartOffset) )
             {
@@ -3304,9 +3267,7 @@
             {
 #endif
-
 #if HHI_RQT_INTRA_SPEEDUP
-#if NH_3D_ENC_DEPTH
-      xRecurIntraCodingLumaQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaPU, uiPUDistY, true, dPUCost, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sMode), (zeroResi != 0) );
-#if NH_3D_ENC_DEPTH
+#if NH_3D
+              xRecurIntraCodingLumaQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaPU, uiPUDistY, true, dPUCost, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sMode), (zeroResi != 0) );
               if( dPUCost < dBestPUCostConv )
               {
@@ -3316,37 +3277,35 @@
                 dBestPUCostConv   = dPUCost;
               }
-#endif
 #else
-      xRecurIntraCodingLumaQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaPU, uiPUDistY, true, dPUCost, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sMode) );
+              xRecurIntraCodingLumaQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaPU, uiPUDistY, true, dPUCost, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sMode) );
 #endif
 #else
-#if NH_3D_ENC_DEPTH
-      xRecurIntraCodingLumaQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaPU, uiPUDistY, dPUCost, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sMode), (zeroResi != 0) );
+#if NH_3D
+              xRecurIntraCodingLumaQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaPU, uiPUDistY, dPUCost, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sMode), (zeroResi != 0) );
 #else
-      xRecurIntraCodingLumaQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaPU, uiPUDistY, dPUCost, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sMode) );
-#endif
-#endif
-#if NH_3D_SDC_INTRA
+              xRecurIntraCodingLumaQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaPU, uiPUDistY, dPUCost, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sMode) );
+#endif
+#endif
+#if NH_3D
             }
 #endif
 
-
 #if DEBUG_INTRA_SEARCH_COSTS
-      std::cout << "2nd pass [luma,chroma] mode [" << Int(pcCU->getIntraDir(CHANNEL_TYPE_LUMA, uiPartOffset)) << "," << Int(pcCU->getIntraDir(CHANNEL_TYPE_CHROMA, uiPartOffset)) << "] cost = " << dPUCost << "\n";
-#endif
-
-      // check r-d cost
-      if( dPUCost < dBestPUCost )
-      {
-        DEBUG_STRING_SWAP(sPU, sMode)
+            std::cout << "2nd pass [luma,chroma] mode [" << Int(pcCU->getIntraDir(CHANNEL_TYPE_LUMA, uiPartOffset)) << "," << Int(pcCU->getIntraDir(CHANNEL_TYPE_CHROMA, uiPartOffset)) << "] cost = " << dPUCost << "\n";
+#endif
+
+            // check r-d cost
+            if( dPUCost < dBestPUCost )
+            {
+              DEBUG_STRING_SWAP(sPU, sMode)
 #if HHI_RQT_INTRA_SPEEDUP_MOD
-        uiSecondBestMode  = uiBestPUMode;
-        dSecondBestPUCost = dBestPUCost;
-#endif
-        uiBestPUMode  = uiOrgMode;
-        uiBestPUDistY = uiPUDistY;
-        dBestPUCost   = dPUCost;
-
-#if NH_3D_SDC_INTRA
+                uiSecondBestMode  = uiBestPUMode;
+              dSecondBestPUCost = dBestPUCost;
+#endif
+              uiBestPUMode  = uiOrgMode;
+              uiBestPUDistY = uiPUDistY;
+              dBestPUCost   = dPUCost;
+
+#if NH_3D
               if( pcCU->getSDCFlag(uiPartOffset) )
               {
@@ -3370,4 +3329,112 @@
                 bBestUseSDC = false;
 #endif
+                xSetIntraResultLumaQT( pcRecoYuv, tuRecurseWithPU );
+
+                if (pps.getPpsRangeExtension().getCrossComponentPredictionEnabledFlag())
+                {
+                  const Int xOffset = tuRecurseWithPU.getRect( COMPONENT_Y ).x0;
+                  const Int yOffset = tuRecurseWithPU.getRect( COMPONENT_Y ).y0;
+                  for (UInt storedResidualIndex = 0; storedResidualIndex < NUMBER_OF_STORED_RESIDUAL_TYPES; storedResidualIndex++)
+                  {
+                    if (bMaintainResidual[storedResidualIndex])
+                    {
+                      xStoreCrossComponentPredictionResult(resiLuma[storedResidualIndex], resiLumaPU[storedResidualIndex], tuRecurseWithPU, xOffset, yOffset, MAX_CU_SIZE, MAX_CU_SIZE );
+                    }
+                  }
+                }
+
+                UInt uiQPartNum = tuRecurseWithPU.GetAbsPartIdxNumParts();
+
+                ::memcpy( m_puhQTTempTrIdx,  pcCU->getTransformIdx()       + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+                for (UInt component = 0; component < numberValidComponents; component++)
+                {
+                  const ComponentID compID = ComponentID(component);
+                  ::memcpy( m_puhQTTempCbf[compID], pcCU->getCbf( compID  ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+                  ::memcpy( m_puhQTTempTransformSkipFlag[compID],  pcCU->getTransformSkip(compID)  + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+                }
+#if NH_3D
+              }
+#endif
+            }
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+            else if( dPUCost < dSecondBestPUCost )
+            {
+              uiSecondBestMode  = uiOrgMode;
+              dSecondBestPUCost = dPUCost;
+            }
+#endif
+
+#if NH_3D
+          }
+        } // SDC residual loop
+      } // SDC loop
+#endif
+#if NH_MV
+      D_DEC_INDENT( g_traceModeCheck ); 
+#endif
+    } // Mode loop
+
+#if HHI_RQT_INTRA_SPEEDUP
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+    for( UInt ui =0; ui < 2; ++ui )
+#endif
+    {
+#if HHI_RQT_INTRA_SPEEDUP_MOD
+      UInt uiOrgMode   = ui ? uiSecondBestMode  : uiBestPUMode;
+      if( uiOrgMode == MAX_UINT )
+      {
+        break;
+      }
+#else
+      UInt uiOrgMode = uiBestPUMode;
+#endif
+
+
+#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
+      if (DebugOptionList::ForceLumaMode.isSet())
+      {
+        uiOrgMode = DebugOptionList::ForceLumaMode.getInt();
+      }
+#endif
+
+      pcCU->setIntraDirSubParts ( CHANNEL_TYPE_LUMA, uiOrgMode, uiPartOffset, uiDepth + uiInitTrDepth );
+#if NH_3D
+      pcCU->setSDCFlagSubParts(false, uiPartOffset, uiDepth + uiInitTrDepth);
+#endif
+
+      DEBUG_STRING_NEW(sModeTree)
+
+      // set context models
+      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
+
+      // determine residual for partition
+#if NH_3D_VSO
+      Dist       uiPUDistY = 0;
+#else
+      Distortion uiPUDistY = 0;
+#endif
+      Double     dPUCost   = 0.0;
+#if NH_3D_VSO // M37  //check if necessary
+      // reset Model
+      if( m_pcRdCost->getUseRenModel() )
+      {
+        m_pcRdCost->setRenModelData( pcCU, uiPartOffset, pcOrgYuv, &tuRecurseWithPU );        
+      }
+#endif
+
+      xRecurIntraCodingLumaQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaPU, uiPUDistY, false, dPUCost, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sModeTree));
+
+      // check r-d cost
+      if( dPUCost < dBestPUCost )
+      {
+        DEBUG_STRING_SWAP(sPU, sModeTree)
+        uiBestPUMode  = uiOrgMode;
+        uiBestPUDistY = uiPUDistY;
+        dBestPUCost   = dPUCost;
+#if NH_3D
+        bBestUseSDC   = false;
+#endif
+
+
         xSetIntraResultLumaQT( pcRecoYuv, tuRecurseWithPU );
 
@@ -3385,7 +3452,7 @@
         }
 
-        UInt uiQPartNum = tuRecurseWithPU.GetAbsPartIdxNumParts();
-
+        const UInt uiQPartNum = tuRecurseWithPU.GetAbsPartIdxNumParts();
         ::memcpy( m_puhQTTempTrIdx,  pcCU->getTransformIdx()       + uiPartOffset, uiQPartNum * sizeof( UChar ) );
+
         for (UInt component = 0; component < numberValidComponents; component++)
         {
@@ -3394,113 +3461,4 @@
           ::memcpy( m_puhQTTempTransformSkipFlag[compID],  pcCU->getTransformSkip(compID)  + uiPartOffset, uiQPartNum * sizeof( UChar ) );
         }
-#if NH_3D_SDC_INTRA
-        }
-#endif
-      }
-#if HHI_RQT_INTRA_SPEEDUP_MOD
-      else if( dPUCost < dSecondBestPUCost )
-      {
-        uiSecondBestMode  = uiOrgMode;
-        dSecondBestPUCost = dPUCost;
-      }
-#endif
-#if NH_3D_ENC_DEPTH
-          }
-#endif
-#if NH_3D_SDC_INTRA
-        } // SDC residual loop
-      } // SDC loop
-#endif
-#if NH_MV
-      D_DEC_INDENT( g_traceModeCheck ); 
-#endif
-    } // Mode loop
-
-#if HHI_RQT_INTRA_SPEEDUP
-#if HHI_RQT_INTRA_SPEEDUP_MOD
-    for( UInt ui =0; ui < 2; ++ui )
-#endif
-    {
-#if HHI_RQT_INTRA_SPEEDUP_MOD
-      UInt uiOrgMode   = ui ? uiSecondBestMode  : uiBestPUMode;
-      if( uiOrgMode == MAX_UINT )
-      {
-        break;
-      }
-#else
-      UInt uiOrgMode = uiBestPUMode;
-#endif
-
-
-#if ENVIRONMENT_VARIABLE_DEBUG_AND_TEST
-      if (DebugOptionList::ForceLumaMode.isSet())
-      {
-        uiOrgMode = DebugOptionList::ForceLumaMode.getInt();
-      }
-#endif
-
-      pcCU->setIntraDirSubParts ( CHANNEL_TYPE_LUMA, uiOrgMode, uiPartOffset, uiDepth + uiInitTrDepth );
-#if NH_3D_SDC_INTRA
-      pcCU->setSDCFlagSubParts(false, uiPartOffset, uiDepth + uiInitTrDepth);
-#endif
-
-      DEBUG_STRING_NEW(sModeTree)
-
-      // set context models
-      m_pcRDGoOnSbacCoder->load( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST] );
-
-      // determine residual for partition
-#if NH_3D_VSO
-      Dist       uiPUDistY = 0;
-#else
-      Distortion uiPUDistY = 0;
-#endif
-      Double     dPUCost   = 0.0;
-#if NH_3D_VSO // M37  //check if necessary
-      // reset Model
-      if( m_pcRdCost->getUseRenModel() )
-      {
-        m_pcRdCost->setRenModelData( pcCU, uiPartOffset, pcOrgYuv, &tuRecurseWithPU );        
-      }
-#endif
-
-      xRecurIntraCodingLumaQT( pcOrgYuv, pcPredYuv, pcResiYuv, resiLumaPU, uiPUDistY, false, dPUCost, tuRecurseWithPU DEBUG_STRING_PASS_INTO(sModeTree));
-
-      // check r-d cost
-      if( dPUCost < dBestPUCost )
-      {
-        DEBUG_STRING_SWAP(sPU, sModeTree)
-        uiBestPUMode  = uiOrgMode;
-        uiBestPUDistY = uiPUDistY;
-        dBestPUCost   = dPUCost;
-#if NH_3D_SDC_INTRA
-        bBestUseSDC   = false;
-#endif
-
-
-        xSetIntraResultLumaQT( pcRecoYuv, tuRecurseWithPU );
-
-        if (pps.getPpsRangeExtension().getCrossComponentPredictionEnabledFlag())
-        {
-          const Int xOffset = tuRecurseWithPU.getRect( COMPONENT_Y ).x0;
-          const Int yOffset = tuRecurseWithPU.getRect( COMPONENT_Y ).y0;
-          for (UInt storedResidualIndex = 0; storedResidualIndex < NUMBER_OF_STORED_RESIDUAL_TYPES; storedResidualIndex++)
-          {
-            if (bMaintainResidual[storedResidualIndex])
-            {
-              xStoreCrossComponentPredictionResult(resiLuma[storedResidualIndex], resiLumaPU[storedResidualIndex], tuRecurseWithPU, xOffset, yOffset, MAX_CU_SIZE, MAX_CU_SIZE );
-            }
-          }
-        }
-
-        const UInt uiQPartNum = tuRecurseWithPU.GetAbsPartIdxNumParts();
-        ::memcpy( m_puhQTTempTrIdx,  pcCU->getTransformIdx()       + uiPartOffset, uiQPartNum * sizeof( UChar ) );
-
-        for (UInt component = 0; component < numberValidComponents; component++)
-        {
-          const ComponentID compID = ComponentID(component);
-          ::memcpy( m_puhQTTempCbf[compID], pcCU->getCbf( compID  ) + uiPartOffset, uiQPartNum * sizeof( UChar ) );
-          ::memcpy( m_puhQTTempTransformSkipFlag[compID],  pcCU->getTransformSkip(compID)  + uiPartOffset, uiQPartNum * sizeof( UChar ) );
-        }
       }
     } // Mode loop
@@ -3511,5 +3469,5 @@
     //--- update overall distortion ---
     uiOverallDistY += uiBestPUDistY;
-#if NH_3D_SDC_INTRA
+#if NH_3D
     if( bBestUseSDC )
     {
@@ -3533,5 +3491,5 @@
       ::memcpy( pcCU->getCbf( compID  ) + uiPartOffset, m_puhQTTempCbf[compID], uiQPartNum * sizeof( UChar ) );
       ::memcpy( pcCU->getTransformSkip( compID  ) + uiPartOffset, m_puhQTTempTransformSkipFlag[compID ], uiQPartNum * sizeof( UChar ) );
-#if NH_3D_SDC_INTRA
+#if NH_3D
     }
 #endif
@@ -3570,5 +3528,5 @@
     //=== update PU data ====
     pcCU->setIntraDirSubParts     ( CHANNEL_TYPE_LUMA, uiBestPUMode, uiPartOffset, uiDepth + uiInitTrDepth );
-#if NH_3D_SDC_INTRA
+#if NH_3D
     pcCU->setSDCFlagSubParts          ( bBestUseSDC, uiPartOffset, uiDepth + uiInitTrDepth );
 #endif
@@ -3895,8 +3853,6 @@
                             iWidth, iHeight, m_pcEncCfg->getUseHADME() && (pcCU->getCUTransquantBypass(iPartIdx) == 0) );
 
-#if NH_3D_IC
+#if NH_3D
   cDistParam.bUseIC = false;
-#endif
-#if NH_3D_SDC_INTER
   cDistParam.bUseSDCMRSAD = false;
 #endif
@@ -3907,9 +3863,6 @@
 //! estimation of best merge coding
 Void TEncSearch::xMergeEstimation( TComDataCU* pcCU, TComYuv* pcYuvOrg, Int iPUIdx, UInt& uiInterDir, TComMvField* pacMvField, UInt& uiMergeIndex, Distortion& ruiCost, TComMvField* cMvFieldNeighbours, UChar* uhInterDirNeighbours, Int& numValidMergeCand 
-#if NH_3D_VSP
-                                 , Int* vspFlag
-#endif
-#if NH_3D_SPIVMP
-                                 , Bool* pbSPIVMPFlag, TComMvField* pcMvFieldSP, UChar* puhInterDirSP
+#if NH_3D
+                                 , Int* vspFlag, Bool* pbSPIVMPFlag, TComMvField* pcMvFieldSP, UChar* puhInterDirSP
 #endif
 )
@@ -3926,5 +3879,5 @@
   UInt uiDepth = pcCU->getDepth( uiAbsPartIdx );
 
-#if NH_3D_DBBP
+#if NH_3D
   DbbpTmpData* pDBBPTmpData = pcCU->getDBBPTmpData();
   if( pcCU->getDBBPFlag(0) )
@@ -3958,5 +3911,5 @@
 
   PartSize partSize = pcCU->getPartitionSize( 0 );
-#if NH_3D_DBBP
+#if NH_3D
   if ( pcCU->getSlice()->getPPS()->getLog2ParallelMergeLevelMinus2() && partSize != SIZE_2Nx2N && pcCU->getWidth( 0 ) <= 8 && pcCU->getDBBPFlag(0) == false )
 #else
@@ -3967,26 +3920,30 @@
     {
       pcCU->setPartSizeSubParts( SIZE_2Nx2N, 0, uiDepth ); // temporarily set
-#if NH_3D_MLC
+#if NH_3D
       pcCU->initAvailableFlags();
+#if MCTS_ENC_CHECK
+      UInt numSpatialMergeCandidates = 0;
+      pcCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, numSpatialMergeCandidates );
+      if (m_pcEncCfg->getTMCTSSEITileConstraint() && pcCU->isLastColumnCTUInTile())
+      {
+        numValidMergeCand = numSpatialMergeCandidates;
+      }
+#else 
       pcCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
-      pcCU->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours
-#if NH_3D_SPIVMP
-        , pcMvFieldSP, puhInterDirSP
-#endif
-        , numValidMergeCand
-        );
-
-      pcCU->buildMCL( cMvFieldNeighbours,uhInterDirNeighbours
-#if NH_3D_VSP
-        , vspFlag
-#endif
-#if NH_3D_SPIVMP
-        , pbSPIVMPFlag
-#endif
-        , numValidMergeCand
-        );
+#endif
+      pcCU->xGetInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours , pcMvFieldSP, puhInterDirSP, numValidMergeCand );
+      pcCU->buildMCL( cMvFieldNeighbours,uhInterDirNeighbours , vspFlag, pbSPIVMPFlag, numValidMergeCand );
+#else
+#if MCTS_ENC_CHECK
+      UInt numSpatialMergeCandidates = 0;
+      pcCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, numSpatialMergeCandidates );
+      if (m_pcEncCfg->getTMCTSSEITileConstraint() && pcCU->isLastColumnCTUInTile())
+      {
+        numValidMergeCand = numSpatialMergeCandidates;
+      }
 #else
       pcCU->getInterMergeCandidates( 0, 0, cMvFieldNeighbours,uhInterDirNeighbours, numValidMergeCand );
 #endif
+#endif
       pcCU->setPartSizeSubParts( partSize, 0, uiDepth ); // restore
     }
@@ -3994,31 +3951,35 @@
   else
   {
-#if NH_3D_MLC
+#if NH_3D
     pcCU->initAvailableFlags();
+#if MCTS_ENC_CHECK
+    UInt numSpatialMergeCandidates = 0;
+    pcCU->getInterMergeCandidates( uiAbsPartIdx, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, numSpatialMergeCandidates );
+    if (m_pcEncCfg->getTMCTSSEITileConstraint() && pcCU->isLastColumnCTUInTile())
+    {
+      numValidMergeCand = numSpatialMergeCandidates;
+    }
+#else 
     pcCU->getInterMergeCandidates( uiAbsPartIdx, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
-    pcCU->xGetInterMergeCandidates( uiAbsPartIdx, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours
-#if NH_3D_SPIVMP
-      , pcMvFieldSP, puhInterDirSP
-#endif
-      , numValidMergeCand
-      );
-
-    pcCU->buildMCL( cMvFieldNeighbours, uhInterDirNeighbours
-#if NH_3D_VSP
-      , vspFlag
-#endif
-#if NH_3D_SPIVMP
-      , pbSPIVMPFlag
-#endif
-      , numValidMergeCand
-      );
+#endif
+    pcCU->xGetInterMergeCandidates( uiAbsPartIdx, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours, pcMvFieldSP, puhInterDirSP , numValidMergeCand      );
+    pcCU->buildMCL( cMvFieldNeighbours, uhInterDirNeighbours , vspFlag, pbSPIVMPFlag, numValidMergeCand );
+#else
+#if MCTS_ENC_CHECK
+    UInt numSpatialMergeCandidates = 0;
+    pcCU->getInterMergeCandidates( uiAbsPartIdx, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand, numSpatialMergeCandidates );
+    if (m_pcEncCfg->getTMCTSSEITileConstraint() && pcCU->isLastColumnCTUInTile())
+    {
+      numValidMergeCand = numSpatialMergeCandidates;
+    }
 #else
     pcCU->getInterMergeCandidates( uiAbsPartIdx, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
 #endif
+#endif
   }
 
   xRestrictBipredMergeCand( pcCU, iPUIdx, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand );
 
-#if NH_3D_DBBP
+#if NH_3D
   if( pcCU->getDBBPFlag(0) )
   {
@@ -4046,9 +4007,7 @@
 
     PartSize ePartSize = pcCU->getPartitionSize( 0 );
-#if NH_3D_VSP
+#if NH_3D
     pcCU->setVSPFlagSubParts( vspFlag[uiMergeCand], uiAbsPartIdx, iPUIdx, pcCU->getDepth( uiAbsPartIdx ) );
-#endif
-
-#if NH_3D_SPIVMP
+
     pcCU->setSPIVMPFlagSubParts( pbSPIVMPFlag[uiMergeCand], uiAbsPartIdx, iPUIdx, pcCU->getDepth( uiAbsPartIdx )); 
     if (pbSPIVMPFlag[uiMergeCand])
@@ -4068,11 +4027,5 @@
     }
     else
-#endif
-#if NH_3D_VSP
-#if NH_3D_DBBP
       if ( vspFlag[uiMergeCand] && !pcCU->getDBBPFlag(0) )
-#else
-      if ( vspFlag[uiMergeCand] )
-#endif
       {
         UInt partAddr;
@@ -4103,12 +4056,9 @@
       {
 #endif
-
-    pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand], ePartSize, uiAbsPartIdx, 0, iPUIdx );
-    pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand], ePartSize, uiAbsPartIdx, 0, iPUIdx );
-#if NH_3D_VSP
-      }
-#endif
-
-
+        pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvField( cMvFieldNeighbours[0 + 2*uiMergeCand], ePartSize, uiAbsPartIdx, 0, iPUIdx );
+        pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvField( cMvFieldNeighbours[1 + 2*uiMergeCand], ePartSize, uiAbsPartIdx, 0, iPUIdx );
+#if NH_3D
+      }
+#endif
     xGetInterPredictionError( pcCU, pcYuvOrg, iPUIdx, uiCostCand, m_pcEncCfg->getUseHADME() );
     uiBitsCand = uiMergeCand + 1;
@@ -4233,5 +4183,5 @@
   Distortion   biPDistTemp = std::numeric_limits<Distortion>::max();
 
-#if NH_3D_IV_MERGE
+#if NH_3D
   TComMvField cMvFieldNeighbours[MRG_MAX_NUM_CANDS_MEM << 1]; // double length for mv of both lists
   UChar uhInterDirNeighbours[MRG_MAX_NUM_CANDS_MEM];
@@ -4272,5 +4222,5 @@
 
     pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
-#if NH_3D_VSP
+#if NH_3D
     pcCU->setVSPFlagSubParts( 0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr) );
 #endif
@@ -4629,5 +4579,5 @@
     } // end if bTestNormalMC
 #endif
-#if NH_3D_DBBP
+#if NH_3D
     // test merge mode for DBBP (2Nx2N)
     if ( pcCU->getPartitionSize( uiPartAddr ) != SIZE_2Nx2N || pcCU->getDBBPFlag(0) )
@@ -4672,5 +4622,5 @@
       Distortion uiMRGCost = std::numeric_limits<Distortion>::max();
 
-#if NH_3D_VSP
+#if NH_3D
       Int vspFlag[MRG_MAX_NUM_CANDS_MEM];
       memset(vspFlag, 0, sizeof(Int)*MRG_MAX_NUM_CANDS_MEM);
@@ -4680,6 +4630,5 @@
       pcCU->getPartIndexAndSize( iPartIdx, uiAbsPartIdx, iWidth, iHeight );
       DisInfo OriginalDvInfo = pcCU->getDvInfo(uiAbsPartIdx);
-#endif
-#if NH_3D_SPIVMP
+
       Bool bSPIVMPFlag[MRG_MAX_NUM_CANDS_MEM];
       memset(bSPIVMPFlag, false, sizeof(Bool)*MRG_MAX_NUM_CANDS_MEM);
@@ -4690,9 +4639,6 @@
 #endif
       xMergeEstimation( pcCU, pcOrgYuv, iPartIdx, uiMRGInterDir, cMRGMvField, uiMRGIndex, uiMRGCost, cMvFieldNeighbours, uhInterDirNeighbours, numValidMergeCand
-#if NH_3D_VSP
-                      , vspFlag
-#endif
-#if NH_3D_SPIVMP
-                      , bSPIVMPFlag, pcMvFieldSP, puhInterDirSP
+#if NH_3D
+                      , vspFlag , bSPIVMPFlag, pcMvFieldSP, puhInterDirSP
 #endif 
                       );
@@ -4703,8 +4649,6 @@
         pcCU->setMergeFlagSubParts ( true,          uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
         pcCU->setMergeIndexSubParts( uiMRGIndex,    uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
-#if NH_3D_VSP
+#if NH_3D
         pcCU->setVSPFlagSubParts( vspFlag[uiMRGIndex], uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
-#endif
-#if NH_3D_SPIVMP
         pcCU->setSPIVMPFlagSubParts(bSPIVMPFlag[uiMRGIndex], uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );  
         if (bSPIVMPFlag[uiMRGIndex]!=0)
@@ -4728,59 +4672,50 @@
         }
         else
-#endif
-#if NH_3D_VSP
-#if NH_3D_DBBP
-        if ( vspFlag[uiMRGIndex] && !pcCU->getDBBPFlag(uiPartAddr) )
-#else
-        if ( vspFlag[uiMRGIndex] )
-#endif
-        {
-          UInt partAddrTemp;
-          Int vspSize;
-          Int width, height;
-          pcCU->getPartIndexAndSize( iPartIdx, partAddrTemp, width, height ); // true or pcCU->getTotalNumPart()==256
-          if( uiMRGInterDir & 0x01 )
+          if ( vspFlag[uiMRGIndex] && !pcCU->getDBBPFlag(uiPartAddr) )
           {
-            pcCU->setMvFieldPUForVSP( pcCU, partAddrTemp, width, height, REF_PIC_LIST_0, cMRGMvField[0].getRefIdx(), vspSize );
-            pcCU->setVSPFlag( partAddrTemp, vspSize );
+            UInt partAddrTemp;
+            Int vspSize;
+            Int width, height;
+            pcCU->getPartIndexAndSize( iPartIdx, partAddrTemp, width, height ); // true or pcCU->getTotalNumPart()==256
+            if( uiMRGInterDir & 0x01 )
+            {
+              pcCU->setMvFieldPUForVSP( pcCU, partAddrTemp, width, height, REF_PIC_LIST_0, cMRGMvField[0].getRefIdx(), vspSize );
+              pcCU->setVSPFlag( partAddrTemp, vspSize );
+            }
+            else
+            {
+              pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMRGMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
+            }
+            if( uiMRGInterDir & 0x02 )
+            {
+              pcCU->setMvFieldPUForVSP( pcCU, partAddrTemp, width, height, REF_PIC_LIST_1, cMRGMvField[1].getRefIdx(), vspSize );
+              pcCU->setVSPFlag( partAddrTemp, vspSize );
+            }
+            else
+            {
+              pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMRGMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
+            }
+            pcCU->setInterDirSubParts  ( uiMRGInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
           }
           else
           {
+#endif
+            pcCU->setInterDirSubParts  ( uiMRGInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
             pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMRGMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
+            pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMRGMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
+#if NH_3D
           }
-          if( uiMRGInterDir & 0x02 )
-          {
-            pcCU->setMvFieldPUForVSP( pcCU, partAddrTemp, width, height, REF_PIC_LIST_1, cMRGMvField[1].getRefIdx(), vspSize );
-            pcCU->setVSPFlag( partAddrTemp, vspSize );
-          }
-          else
-          {
-            pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMRGMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
-          }
-          pcCU->setInterDirSubParts  ( uiMRGInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
-        }
-        else
-          {
-#endif
-        pcCU->setInterDirSubParts  ( uiMRGInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
-        pcCU->getCUMvField( REF_PIC_LIST_0 )->setAllMvField( cMRGMvField[0], ePartSize, uiPartAddr, 0, iPartIdx );
-        pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMRGMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
-#if NH_3D_VSP
-          }
-#endif
-#if H_3D
-          }
-#endif
-        pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( cMvZero,            ePartSize, uiPartAddr, 0, iPartIdx );
-        pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( cMvZero,            ePartSize, uiPartAddr, 0, iPartIdx );
-
-        pcCU->setMVPIdxSubParts( -1, REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
-        pcCU->setMVPNumSubParts( -1, REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
-        pcCU->setMVPIdxSubParts( -1, REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
-        pcCU->setMVPNumSubParts( -1, REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+#endif
+          pcCU->getCUMvField(REF_PIC_LIST_0)->setAllMvd    ( cMvZero,            ePartSize, uiPartAddr, 0, iPartIdx );
+          pcCU->getCUMvField(REF_PIC_LIST_1)->setAllMvd    ( cMvZero,            ePartSize, uiPartAddr, 0, iPartIdx );
+
+          pcCU->setMVPIdxSubParts( -1, REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+          pcCU->setMVPNumSubParts( -1, REF_PIC_LIST_0, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+          pcCU->setMVPIdxSubParts( -1, REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
+          pcCU->setMVPNumSubParts( -1, REF_PIC_LIST_1, uiPartAddr, iPartIdx, pcCU->getDepth(uiPartAddr));
       }
       else
       {
-#if NH_3D_SPIVMP        
+#if NH_3D
         pcCU->setSPIVMPFlagSubParts(0, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) ); 
 #endif
@@ -4788,5 +4723,5 @@
         pcCU->setMergeFlagSubParts( false,        uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
         pcCU->setInterDirSubParts ( uiMEInterDir, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
-#if NH_3D_VSP
+#if NH_3D
         pcCU->setVSPFlagSubParts ( 0,             uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
         pcCU->setDvInfoSubParts(OriginalDvInfo, uiPartAddr, iPartIdx, pcCU->getDepth( uiPartAddr ) );
@@ -4795,9 +4730,17 @@
         pcCU->getCUMvField( REF_PIC_LIST_1 )->setAllMvField( cMEMvField[1], ePartSize, uiPartAddr, 0, iPartIdx );
       }
-#if NH_3D_SPIVMP
+#if NH_3D
       delete[] pcMvFieldSP;
       delete[] puhInterDirSP;
 #endif
     }
+
+#if MCTS_ENC_CHECK
+    if (m_pcEncCfg->getTMCTSSEITileConstraint() && (!checkTMctsMvp(pcCU, iPartIdx)))
+    {
+      pcCU->setTMctsMvpIsValid(false);
+      return;
+    }
+#endif
 
     //  MC
@@ -4834,4 +4777,6 @@
   Int        iRoiWidth, iRoiHeight;
   Int        i;
+  Int        minMVPCand;
+  Int        maxMVPCand;
 
   pcCU->getPartIndexAndSize( uiPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
@@ -4840,5 +4785,5 @@
   {
 
-#if NH_3D_DBBP
+#if NH_3D
     DbbpTmpData* pDBBPTmpData = pcCU->getDBBPTmpData();
     if( pcCU->getDBBPFlag(0) )
@@ -4872,5 +4817,5 @@
 
     pcCU->fillMvpCand( uiPartIdx, uiPartAddr, eRefPicList, iRefIdx, pcAMVPInfo );
-#if NH_3D_DBBP
+#if NH_3D
     if( pcCU->getDBBPFlag(0) )
     {
@@ -4889,6 +4834,26 @@
 
   // initialize Mvp index & Mvp
+#if MCTS_ENC_CHECK
+  if (m_pcEncCfg->getTMCTSSEITileConstraint() && pcCU->isLastColumnCTUInTile() && (pcAMVPInfo->numSpatialMVPCandidates < pcAMVPInfo->iN))
+  {
+    iBestIdx    = (pcAMVPInfo->numSpatialMVPCandidates == 0) ? 1 : 0;
+    cBestMv     = pcAMVPInfo->m_acMvCand[(pcAMVPInfo->numSpatialMVPCandidates == 0) ? 1 : 0];
+    minMVPCand  = (pcAMVPInfo->numSpatialMVPCandidates == 0) ? 1 : 0;
+    maxMVPCand  = (pcAMVPInfo->numSpatialMVPCandidates == 0) ? pcAMVPInfo->iN : 1;
+  }
+  else
+  {
+    iBestIdx = 0;
+    cBestMv  = pcAMVPInfo->m_acMvCand[0];
+    minMVPCand  = 0;
+    maxMVPCand  = pcAMVPInfo->iN;
+  }
+#else
   iBestIdx = 0;
   cBestMv  = pcAMVPInfo->m_acMvCand[0];
+  minMVPCand  = 0;
+  maxMVPCand  = pcAMVPInfo->iN;
+#endif
+
   if (pcAMVPInfo->iN <= 1)
   {
@@ -4922,5 +4887,5 @@
   m_cYuvPredTemp.clear();
   //-- Check Minimum Cost.
-  for ( i = 0 ; i < pcAMVPInfo->iN; i++)
+  for ( i = minMVPCand ; i < maxMVPCand; i++)
   {
 #if NH_MV
@@ -5064,5 +5029,17 @@
   Int iBestMvBits = iOrgMvBits;
 
+#if MCTS_ENC_CHECK
+  Int minMVPCand = 0;
+  Int maxMVPCand = pcAMVPInfo->iN;
+
+  if (m_pcEncCfg->getTMCTSSEITileConstraint() && pcCU->isLastColumnCTUInTile())
+  {
+    minMVPCand = (pcAMVPInfo->numSpatialMVPCandidates == 0) ? 1 : 0;
+    maxMVPCand = (pcAMVPInfo->numSpatialMVPCandidates == 0) ? pcAMVPInfo->iN : 1;
+  }
+  for (Int iMVPIdx = minMVPCand; iMVPIdx < maxMVPCand; iMVPIdx++)
+#else
   for (Int iMVPIdx = 0; iMVPIdx < pcAMVPInfo->iN; iMVPIdx++)
+#endif
   {
     if (iMVPIdx == riMVPIdx)
@@ -5114,5 +5091,5 @@
   pcCU->clipMv( cMvCand );
 
-#if NH_3D_IC
+#if NH_3D
   Bool bICFlag = pcCU->getICFlag( uiPartAddr ) && ( pcCU->getSlice()->getViewIndex() != pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getViewIndex() );
 #endif
@@ -5122,5 +5099,5 @@
   {
     xPredInterBlk( COMPONENT_Y, pcCU, pcPicYuvRef, uiPartAddr, &cMvCand, iSizeX, iSizeY, pcTemplateCand, true, pcCU->getSlice()->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) 
-#if NH_3D_ARP
+#if NH_3D
       , false //add this for IC, otherwise, it could be removed
 #endif
@@ -5130,11 +5107,7 @@
   {
     xPredInterBlk( COMPONENT_Y, pcCU, pcPicYuvRef, uiPartAddr, &cMvCand, iSizeX, iSizeY, pcTemplateCand, false, pcCU->getSlice()->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) 
-#if NH_3D_ARP
-      , false
-#endif
-#if NH_3D_IC
-    , bICFlag
-#endif
-
+#if NH_3D
+      , false, bICFlag
+#endif
 );
   }
@@ -5175,6 +5148,5 @@
 
   Int           iSrchRng      = ( bBi ? m_bipredSearchRange : m_iSearchRange );
-  TComPattern   tmpPattern;
-  TComPattern*  pcPatternKey  = &tmpPattern;
+  TComPattern   cPattern;
 
   Double        fWeight       = 1.0;
@@ -5182,10 +5154,8 @@
   pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iRoiWidth, iRoiHeight );
 
-#if NH_3D_IC
+#if NH_3D
   Bool bICFlag = pcCU->getICFlag( uiPartAddr ) && ( pcCU->getSlice()->getViewIndex() != pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getViewIndex() );
-  pcPatternKey->setICFlag( bICFlag );
-#endif
-#if NH_3D_SDC_INTER
-   pcPatternKey->setSDCMRSADFlag( pcCU->getSlice()->getInterSdcFlag() );
+  cPattern.setICFlag( bICFlag );
+  cPattern.setSDCMRSADFlag( pcCU->getSlice()->getInterSdcFlag() );
 #endif
 
@@ -5204,10 +5174,25 @@
 
   //  Search key pattern initialization
-  pcPatternKey->initPattern( pcYuv->getAddr  ( COMPONENT_Y, uiPartAddr ),
+#if MCTS_ENC_CHECK
+  Int roiPosX, roiPosY; 
+  Int roiW, roiH;
+  pcCU->getPartPosition(iPartIdx, roiPosX, roiPosY, roiW, roiH);
+  assert(roiW == iRoiWidth);
+  assert(roiH == iRoiHeight);
+  cPattern.initPattern( pcYuv->getAddr(COMPONENT_Y, uiPartAddr),
+                        iRoiWidth,
+                        iRoiHeight,
+                        pcYuv->getStride(COMPONENT_Y),
+                        pcCU->getSlice()->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA),
+                        roiPosX,
+                        roiPosY);
+  xInitTileBorders(pcCU, &cPattern);
+#else
+  cPattern.initPattern( pcYuv->getAddr  ( COMPONENT_Y, uiPartAddr ),
                              iRoiWidth,
                              iRoiHeight,
                              pcYuv->getStride(COMPONENT_Y),
                              pcCU->getSlice()->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) );
-
+#endif
   Pel*        piRefY      = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getPicYuvRec()->getAddr( COMPONENT_Y, pcCU->getCtuRsAddr(), pcCU->getZorderIdxInCtu() + uiPartAddr );
   Int         iRefStride  = pcCU->getSlice()->getRefPic( eRefPicList, iRefIdxPred )->getPicYuvRec()->getStride(COMPONENT_Y);
@@ -5220,9 +5205,17 @@
   if ( bBi )
   {
+#if MCTS_ENC_CHECK
+    xSetSearchRange(pcCU, rcMv, iSrchRng, cMvSrchRngLT, cMvSrchRngRB, &cPattern);
+#else
     xSetSearchRange   ( pcCU, rcMv   , iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+#endif
   }
   else
   {
+#if MCTS_ENC_CHECK
+    xSetSearchRange(pcCU, cMvPred, iSrchRng, cMvSrchRngLT, cMvSrchRngRB, &cPattern);
+#else
     xSetSearchRange   ( pcCU, cMvPred, iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+#endif
   }
 
@@ -5230,5 +5223,5 @@
 
   m_pcRdCost->setPredictor  ( *pcMvPred );
-#if NH_3D_INTEGER_MV_DEPTH
+#if NH_3D
   if( pcCU->getSlice()->getIsDepth() )
   {
@@ -5239,5 +5232,5 @@
 #endif
     m_pcRdCost->setCostScale  ( 2 );    
-#if NH_3D_INTEGER_MV_DEPTH
+#if NH_3D
   }
 #endif
@@ -5248,10 +5241,10 @@
   if ( (m_motionEstimationSearchMethod==MESEARCH_FULL) || bBi )
   {
-    xPatternSearch      ( pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost );
+    xPatternSearch      ( &cPattern, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost );
   }
   else
   {
     rcMv = *pcMvPred;
-#if NH_MV_FIX_VERT_MV_REST
+#if NH_MV
     if ( m_vertRestriction )
     {
@@ -5267,5 +5260,5 @@
       pIntegerMv2Nx2NPred = &(m_integerMv2Nx2N[eRefPicList][iRefIdxPred]);
     }
-    xPatternSearchFast  ( pcCU, pcPatternKey, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost, pIntegerMv2Nx2NPred );
+    xPatternSearchFast  ( pcCU, &cPattern, piRefY, iRefStride, &cMvSrchRngLT, &cMvSrchRngRB, rcMv, ruiCost, pIntegerMv2Nx2NPred );
     if (pcCU->getPartitionSize(0) == SIZE_2Nx2N)
     {
@@ -5275,23 +5268,23 @@
 
   m_pcRdCost->selectMotionLambda( true, 0, pcCU->getCUTransquantBypass(uiPartAddr) );
-#if NH_3D_INTEGER_MV_DEPTH
+#if NH_3D
   if( ! pcCU->getSlice()->getIsDepth() )
   {
 #endif
-  m_pcRdCost->setCostScale ( 1 );
-
-  const Bool bIsLosslessCoded = pcCU->getCUTransquantBypass(uiPartAddr) != 0;
-  xPatternSearchFracDIF( bIsLosslessCoded, pcPatternKey, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost );
-
-  m_pcRdCost->setCostScale( 0 );
-  rcMv <<= 2;
-  rcMv += (cMvHalf <<= 1);
-  rcMv +=  cMvQter;
-#if NH_3D_INTEGER_MV_DEPTH
+    m_pcRdCost->setCostScale ( 1 );
+
+    const Bool bIsLosslessCoded = pcCU->getCUTransquantBypass(uiPartAddr) != 0;
+    xPatternSearchFracDIF( bIsLosslessCoded, &cPattern, piRefY, iRefStride, &rcMv, cMvHalf, cMvQter, ruiCost );
+
+    m_pcRdCost->setCostScale( 0 );
+    rcMv <<= 2;
+    rcMv += (cMvHalf <<= 1);
+    rcMv +=  cMvQter;
+#if NH_3D
   }
 #endif
 
   UInt uiMvBits = m_pcRdCost->getBitsOfVectorWithPredictor( rcMv.getHor(), rcMv.getVer() );
-#if NH_3D_INTEGER_MV_DEPTH
+#if NH_3D
   if( pcCU->getSlice()->getIsDepth() )
   {
@@ -5308,10 +5301,38 @@
 }
 
+#if MCTS_ENC_CHECK
+Void TEncSearch::xInitTileBorders(const TComDataCU* const pcCU, TComPattern* pcPatternKey)
+{
+  if (m_pcEncCfg->getTMCTSSEITileConstraint())
+  {
+    UInt  tileXPosInCtus = 0;
+    UInt  tileYPosInCtus = 0;
+    UInt  tileWidthtInCtus = 0;
+    UInt  tileHeightInCtus = 0;
+
+    getTilePosition(pcCU, tileXPosInCtus, tileYPosInCtus, tileWidthtInCtus, tileHeightInCtus);
+
+    const Int  ctuLength = pcCU->getPic()->getPicSym()->getSPS().getMaxCUWidth();
+
+    // tile position in full pels
+    const Int tileLeftTopPelPosX = ctuLength * tileXPosInCtus;
+    const Int tileLeftTopPelPosY = ctuLength * tileYPosInCtus;
+    const Int tileRightBottomPelPosX = ((tileWidthtInCtus + tileXPosInCtus) * ctuLength) - 1;
+    const Int tileRightBottomPelPosY = ((tileHeightInCtus + tileYPosInCtus) * ctuLength) - 1;
+
+    pcPatternKey->setTileBorders (tileLeftTopPelPosX,tileLeftTopPelPosY,tileRightBottomPelPosX,tileRightBottomPelPosY);
+  }
+}
+#endif
 
 Void TEncSearch::xSetSearchRange ( const TComDataCU* const pcCU, const TComMv& cMvPred, const Int iSrchRng,
+#if MCTS_ENC_CHECK
+                                   TComMv& rcMvSrchRngLT, TComMv& rcMvSrchRngRB, const TComPattern* const pcPatternKey )
+#else
                                    TComMv& rcMvSrchRngLT, TComMv& rcMvSrchRngRB )
+#endif
 {
   Int  iMvShift = 2;
-#if NH_3D_INTEGER_MV_DEPTH
+#if NH_3D
   if( pcCU->getSlice()->getIsDepth() )
   {
@@ -5322,4 +5343,27 @@
   pcCU->clipMv( cTmpMvPred );
 
+#if MCTS_ENC_CHECK
+  if (m_pcEncCfg->getTMCTSSEITileConstraint())
+  {
+    const Int lRangeXLeft = max(cTmpMvPred.getHor() - (iSrchRng << iMvShift), (pcPatternKey->getTileLeftTopPelPosX() - pcPatternKey->getROIYPosX()) << iMvShift);
+    const Int lRangeYTop = max(cTmpMvPred.getVer() - (iSrchRng << iMvShift), (pcPatternKey->getTileLeftTopPelPosY() - pcPatternKey->getROIYPosY()) << iMvShift);
+    const Int lRangeXRight = min(cTmpMvPred.getHor() + (iSrchRng << iMvShift), (pcPatternKey->getTileRightBottomPelPosX() - (pcPatternKey->getROIYPosX() + pcPatternKey->getROIYWidth())) << iMvShift);
+    const Int lRangeYBottom = min(cTmpMvPred.getVer() + (iSrchRng << iMvShift), (pcPatternKey->getTileRightBottomPelPosY() - (pcPatternKey->getROIYPosY() + pcPatternKey->getROIYHeight())) << iMvShift);
+
+    rcMvSrchRngLT.setHor(lRangeXLeft);
+    rcMvSrchRngLT.setVer(lRangeYTop);
+
+    rcMvSrchRngRB.setHor(lRangeXRight);
+    rcMvSrchRngRB.setVer(lRangeYBottom);
+  }
+  else
+  {
+    rcMvSrchRngLT.setHor(cTmpMvPred.getHor() - (iSrchRng << iMvShift));
+    rcMvSrchRngLT.setVer(cTmpMvPred.getVer() - (iSrchRng << iMvShift));
+
+    rcMvSrchRngRB.setHor( cTmpMvPred.getHor() + (iSrchRng << iMvShift));
+    rcMvSrchRngRB.setVer( cTmpMvPred.getVer() + (iSrchRng << iMvShift) );
+  }
+#else
   rcMvSrchRngLT.setHor( cTmpMvPred.getHor() - (iSrchRng << iMvShift) );
   rcMvSrchRngLT.setVer( cTmpMvPred.getVer() - (iSrchRng << iMvShift) );
@@ -5327,5 +5371,5 @@
   rcMvSrchRngRB.setHor( cTmpMvPred.getHor() + (iSrchRng << iMvShift) );
   rcMvSrchRngRB.setVer( cTmpMvPred.getVer() + (iSrchRng << iMvShift) );
-  
+  #endif
 #if NH_MV
   if ( m_vertRestriction )
@@ -5394,8 +5438,6 @@
       m_cDistParam.bitDepth = pcPatternKey->getBitDepthY();
 
-#if NH_3D_IC
+#if NH_3D
       m_cDistParam.bUseIC = pcPatternKey->getICFlag();
-#endif
-#if NH_3D_SDC_INTER
       m_cDistParam.bUseSDCMRSAD = pcPatternKey->getSDCMRSADFlag();
 #endif
@@ -5500,5 +5542,5 @@
   UInt uiSearchRange = m_iSearchRange;
   pcCU->clipMv( rcMv );
-#if NH_3D_INTEGER_MV_DEPTH
+#if NH_3D
   if( ! pcCU->getSlice()->getIsDepth() )
 #endif
@@ -5525,15 +5567,15 @@
       TComMv cMv = m_acMvPredictors[index];
       pcCU->clipMv( cMv );
-#if NH_3D_INTEGER_MV_DEPTH
+#if NH_3D
       if( ! pcCU->getSlice()->getIsDepth() )
       {      
 #endif
 #if ME_ENABLE_ROUNDING_OF_MVS
-      cMv.divideByPowerOf2(2);
+        cMv.divideByPowerOf2(2);
 #else
-      cMv >>= 2;
-#endif
-
-#if NH_3D_INTEGER_MV_DEPTH
+        cMv >>= 2;
+#endif
+
+#if NH_3D
       }
 #endif
@@ -5585,5 +5627,9 @@
     TComMv currBestMv(cStruct.iBestX, cStruct.iBestY );
     currBestMv <<= 2;
+#if MCTS_ENC_CHECK
+    xSetSearchRange(pcCU, currBestMv, iSrchRng, cMvSrchRngLT, cMvSrchRngRB, pcPatternKey);
+#else
     xSetSearchRange( pcCU, currBestMv, iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+#endif
     iSrchRngHorLeft   = cMvSrchRngLT.getHor();
     iSrchRngHorRight  = cMvSrchRngRB.getHor();
@@ -5875,5 +5921,9 @@
     TComMv currBestMv(cStruct.iBestX, cStruct.iBestY );
     currBestMv <<= 2;
+#if MCTS_ENC_CHECK
+    xSetSearchRange(pcCU, currBestMv, iSrchRng, cMvSrchRngLT, cMvSrchRngRB, pcPatternKey);
+#else
     xSetSearchRange( pcCU, currBestMv, iSrchRng, cMvSrchRngLT, cMvSrchRngRB );
+#endif
     iSrchRngHorLeft   = cMvSrchRngLT.getHor();
     iSrchRngHorRight  = cMvSrchRngRB.getHor();
@@ -5976,5 +6026,14 @@
                           pcPatternKey->getROIYHeight(),
                           iRefStride,
+#if MCTS_ENC_CHECK
+                          pcPatternKey->getBitDepthY(),
+                          pcPatternKey->getROIYPosX(),
+                          pcPatternKey->getROIYPosY());
+#else
                           pcPatternKey->getBitDepthY());
+#endif
+#if MCTS_ENC_CHECK
+  cPatternRoi.setTileBorders(pcPatternKey->getTileLeftTopPelPosX(), pcPatternKey->getTileLeftTopPelPosY(), pcPatternKey->getTileRightBottomPelPosX(), pcPatternKey->getTileRightBottomPelPosY());
+#endif
 
   //  Half-pel refinement
@@ -6052,5 +6111,5 @@
     m_pcEntropyCoder->resetBits();
 
-    if (pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+    if (pcCU->getSlice()->getPPS()->getTransquantBypassEnabledFlag())
     {
       m_pcEntropyCoder->encodeCUTransquantBypassFlag(pcCU, 0, true);
@@ -6059,8 +6118,6 @@
     m_pcEntropyCoder->encodeSkipFlag(pcCU, 0, true);
     m_pcEntropyCoder->encodeMergeIndex( pcCU, 0, true );
-#if NH_3D_ARP
+#if NH_3D
     m_pcEntropyCoder->encodeARPW( pcCU, 0 );
-#endif
-#if NH_3D_IC
     m_pcEntropyCoder->encodeICFlag( pcCU, 0, true );
 #endif
@@ -6176,5 +6233,5 @@
   const Double zeroCost     = (pcCU->isLosslessCoded( 0 )) ? (nonZeroCost+1) : (m_pcRdCost->calcRdCost( zeroResiBits, zeroDistortion ));
 #endif
-#if NH_3D_SPIVMP
+#if NH_3D
     if ( zeroCost < nonZeroCost || pcCU->getQtRootCbf(0)==0)
 #else
@@ -6272,5 +6329,5 @@
 }
 
-#if NH_3D_SDC_INTER
+#if NH_3D
 Void TEncSearch::encodeResAndCalcRdInterSDCCU( TComDataCU* pcCU, TComYuv* pcOrg, TComYuv* pcPred, TComYuv* pcResi, TComYuv* pcRec, Int uiOffest, const UInt uiDepth )
 {
@@ -6600,5 +6657,6 @@
               if ((compID != COMPONENT_Cr) && ((transformSkipModeId == 1) ? m_pcEncCfg->getUseRDOQTS() : m_pcEncCfg->getUseRDOQ()))
               {
-                m_pcEntropyCoder->estimateBit(m_pcTrQuant->m_pcEstBitsSbac, tuCompRect.width, tuCompRect.height, toChannelType(compID));
+                COEFF_SCAN_TYPE scanType = COEFF_SCAN_TYPE(pcCU->getCoefScanIdx(uiAbsPartIdx, tuCompRect.width, tuCompRect.height, compID));
+                m_pcEntropyCoder->estimateBit(m_pcTrQuant->m_pcEstBitsSbac, tuCompRect.width, tuCompRect.height, toChannelType(compID), scanType);
               }
 
@@ -7365,5 +7423,5 @@
   // Reload only contexts required for coding intra mode information
   m_pcRDGoOnSbacCoder->loadIntraDirMode( m_pppcRDSbacCoder[uiDepth][CI_CURR_BEST], chType );
-#if NH_3D_DMM
+#if NH_3D
   if( pcCU->getSlice()->getIsDepth() && isLuma(chType) )
   {
@@ -7442,5 +7500,5 @@
 
     m_pcEntropyCoder->resetBits();
-    if(pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+    if(pcCU->getSlice()->getPPS()->getTransquantBypassEnabledFlag())
     {
       m_pcEntropyCoder->encodeCUTransquantBypassFlag(pcCU, 0, true);
@@ -7448,8 +7506,6 @@
     m_pcEntropyCoder->encodeSkipFlag(pcCU, 0, true);
     m_pcEntropyCoder->encodeMergeIndex(pcCU, 0, true);
-#if NH_3D_ARP
+#if NH_3D
     m_pcEntropyCoder->encodeARPW( pcCU, 0 );
-#endif
-#if NH_3D_IC
     m_pcEntropyCoder->encodeICFlag( pcCU, 0, true );
 #endif
@@ -7460,5 +7516,5 @@
     m_pcEntropyCoder->resetBits();
 
-    if(pcCU->getSlice()->getPPS()->getTransquantBypassEnableFlag())
+    if(pcCU->getSlice()->getPPS()->getTransquantBypassEnabledFlag())
     {
       m_pcEntropyCoder->encodeCUTransquantBypassFlag(pcCU, 0, true);
@@ -7466,5 +7522,5 @@
 
     m_pcEntropyCoder->encodeSkipFlag ( pcCU, 0, true );
-#if NH_3D_DIS
+#if NH_3D
     m_pcEntropyCoder->encodeDIS ( pcCU, 0, true );
 #endif
@@ -7472,14 +7528,8 @@
     m_pcEntropyCoder->encodePartSize( pcCU, 0, pcCU->getDepth(0), true );
     m_pcEntropyCoder->encodePredInfo( pcCU, 0 );
-#if NH_3D_SDC_INTRA
+#if NH_3D
     m_pcEntropyCoder->encodeSDCFlag( pcCU, 0, true );
-#endif
-#if NH_3D_ARP
     m_pcEntropyCoder->encodeARPW( pcCU , 0  );
-#endif
-#if NH_3D_IC
     m_pcEntropyCoder->encodeICFlag( pcCU, 0, true );
-#endif
-#if NH_3D_DBBP
     m_pcEntropyCoder->encodeDBBPFlag( pcCU, 0, true );
 #endif
@@ -7752,5 +7802,5 @@
 }
 
-#if NH_3D_DMM
+#if NH_3D
   // -------------------------------------------------------------------------------------------------------------------
   // Depth intra search
@@ -7907,8 +7957,6 @@
 #endif
 
-#if NH_3D_DLT
   rDeltaDC1 = pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), ClipBD(predDC1 + rDeltaDC1, bitDepthY )) - pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), predDC1 );
   rDeltaDC2 = pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), ClipBD(predDC2 + rDeltaDC2, bitDepthY )) - pcCU->getSlice()->getPPS()->getDLT()->depthValue2idx( pcCU->getSlice()->getLayerIdInVps(), predDC2 );
-#endif
 }
 
@@ -8027,6 +8075,4 @@
 }
 
-#endif
-#if NH_3D_SDC_INTRA
 Void TEncSearch::xCalcConstantSDC( Pel* ptrSrc, UInt srcStride, UInt uiSize, Pel& valDC )
 {
Index: /trunk/source/Lib/TLibEncoder/TEncSearch.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncSearch.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncSearch.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -178,5 +178,5 @@
                                   Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE]
                                   DEBUG_STRING_FN_DECLARE(sDebug)
-#if NH_3D_ENC_DEPTH
+#if NH_3D
                                 , Bool        bOnlyIVP
 #endif
@@ -190,5 +190,5 @@
                                   Pel         resiLuma[NUMBER_OF_STORED_RESIDUAL_TYPES][MAX_CU_SIZE * MAX_CU_SIZE]
                                   DEBUG_STRING_FN_DECLARE(sDebug));
-#if NH_3D_DIS
+#if NH_3D
   Void  estIntraPredDIS        ( TComDataCU* pcCU, 
                                  TComYuv*    pcOrgYuv, 
@@ -225,5 +225,5 @@
                                   Bool        bSkipResidual
                                   DEBUG_STRING_FN_DECLARE(sDebug) );
-#if NH_3D_SDC_INTER
+#if NH_3D
   Void encodeResAndCalcRdInterSDCCU( TComDataCU* pcCU,
                                      TComYuv* pcOrg, 
@@ -281,5 +281,5 @@
                                     DEBUG_STRING_FN_DECLARE(sTest)
                                          ,Int           default0Save1Load2 = 0
-#if NH_3D_ENC_DEPTH
+#if NH_3D
                                   , Bool          zeroResiFlag = false
 #endif
@@ -301,5 +301,5 @@
                                     TComTU      &rTu
                                     DEBUG_STRING_FN_DECLARE(sDebug)
-#if NH_3D_ENC_DEPTH
+#if NH_3D
                                   , Bool        zeroResiFlag = false
 #endif
@@ -342,5 +342,5 @@
   Void  xStoreIntraResultQT       ( const ComponentID compID, TComTU &rTu);
   Void  xLoadIntraResultQT        ( const ComponentID compID, TComTU &rTu);
-#if NH_3D_DIS
+#if NH_3D
 #if NH_3D_VSO
   Void xIntraCodingDIS           ( TComDataCU* pcCU, UInt uiAbsPartIdx, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, Dist&       ruiDist, Double& dRDCost, UInt uiPredMode );
@@ -350,5 +350,5 @@
 #endif
 
-#if NH_3D_DMM
+#if NH_3D
   // -------------------------------------------------------------------------------------------------------------------
   // Depth intra search
@@ -358,6 +358,4 @@
   Void xSearchDmmDeltaDCs         ( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piOrig, Pel* piPredic, UInt uiStride, Bool* biSegPattern, Int patternStride, UInt uiWidth, UInt uiHeight, Pel& rDeltaDC1, Pel& rDeltaDC2 );
   Void xSearchDmm1Wedge           ( TComDataCU* pcCU, UInt uiAbsPtIdx, Pel* piRef, UInt uiRefStride, UInt uiWidth, UInt uiHeight, UInt& ruiTabIdx );
-#endif
-#if NH_3D_SDC_INTRA
 #if NH_3D_VSO
   Void xIntraCodingSDC            ( TComDataCU* pcCU, UInt uiAbsPartIdx, TComYuv* pcOrgYuv, TComYuv* pcPredYuv, Dist& ruiDist      , Double& dRDCost, Bool bZeroResidual, Int iSDCDeltaResi    );
@@ -419,9 +417,9 @@
                                     UChar*       uhInterDirNeighbours,
                                     Int&         numValidMergeCand
-#if NH_3D_VSP
-                                  , Int* vspFlag
-#endif
-#if NH_3D_SPIVMP
-                                  , Bool* pbSPIVMPFlag, TComMvField* pcMvFieldSP, UChar* puhInterDirSP
+#if NH_3D
+                                  , Int*         vspFlag
+                                  , Bool*        pbSPIVMPFlag
+                                  , TComMvField* pcMvFieldSP
+                                  , UChar*       puhInterDirSP
 #endif
                                    );
@@ -476,5 +474,14 @@
                                     const Int          iSrchRng,
                                     TComMv&      rcMvSrchRngLT,
+#if !MCTS_ENC_CHECK
                                     TComMv&      rcMvSrchRngRB );
+#else
+                                    TComMv&      rcMvSrchRngRB,
+                                    const TComPattern* const pcPatternKey );
+#endif
+
+#if MCTS_ENC_CHECK
+  Void xInitTileBorders(const TComDataCU* const pcCU, TComPattern* pcPatternKey);
+#endif
 
   Void xPatternSearchFast         ( const TComDataCU* const  pcCU,
Index: /trunk/source/Lib/TLibEncoder/TEncSlice.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncSlice.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -113,4 +113,11 @@
 }
 
+Void TEncSlice::updateLambda(TComSlice* pSlice, Double dQP)
+{
+  Int iQP = (Int)dQP;
+  Double dLambda = calculateLambda(pSlice, m_gopID, pSlice->getDepth(), pSlice->getSliceQp(), dQP, iQP);
+
+  setUpLambda(pSlice, dLambda, iQP);
+}
 
 
@@ -188,5 +195,8 @@
   rpcSlice->setPicOutputFlag( true );
   rpcSlice->setPOC( pocCurr );
-#if NH_3D_IC
+  pcPic->setField(isField);
+  m_gopID = iGOPid;
+
+#if NH_3D
   rpcSlice->setApplyIC( false );
 #endif
@@ -252,4 +262,5 @@
     eSliceType = B_SLICE; 
   }
+  m_eSliceTypeBaseView = eSliceTypeBaseView;
 #else
   SliceType eSliceType;
@@ -296,8 +307,11 @@
   // ------------------------------------------------------------------------------------------------------------------
 
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+  dQP = m_pcCfg->getQPForPicture(iGOPid, rpcSlice);
+#else
   dQP = m_pcCfg->getQP();
   if(eSliceType!=I_SLICE)
   {
-    if (!(( m_pcCfg->getMaxDeltaQP() == 0 ) && (dQP == -rpcSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA) ) && (rpcSlice->getPPS()->getTransquantBypassEnableFlag())))
+    if (!(( m_pcCfg->getMaxDeltaQP() == 0) && (!m_pcCfg->getLumaLevelToDeltaQPMapping().isEnabled()) && (dQP == -rpcSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA) ) && (rpcSlice->getPPS()->getTransquantBypassEnabledFlag())))
     {
 #if NH_MV
@@ -310,5 +324,5 @@
 
   // modify QP
-  Int* pdQPs = m_pcCfg->getdQPs();
+  const Int* pdQPs = m_pcCfg->getdQPs();
   if ( pdQPs )
   {
@@ -321,4 +335,5 @@
     m_pcCfg->setDeltaQpRD(0);
   }
+#endif
 
   // ------------------------------------------------------------------------------------------------------------------
@@ -326,4 +341,12 @@
   // ------------------------------------------------------------------------------------------------------------------
 
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+#if NH_MV
+  const Int temporalId=m_pcCfg->getGOPEntry((eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid).m_temporalId;
+#else
+  const Int temporalId=m_pcCfg->getGOPEntry(iGOPid).m_temporalId;
+#endif
+#endif
+
   Int iQP;
   Double dOrigQP = dQP;
@@ -335,66 +358,5 @@
     dQP = dOrigQP + ((iDQpIdx+1)>>1)*(iDQpIdx%2 ? -1 : 1);
 
-    // compute lambda value
-    Int    NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
-    Int    SHIFT_QP = 12;
-
-#if FULL_NBIT
-    Int    bitdepth_luma_qp_scale = 6 * (rpcSlice->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) - 8);
-#else
-    Int    bitdepth_luma_qp_scale = 0;
-#endif
-    Double qp_temp = (Double) dQP + bitdepth_luma_qp_scale - SHIFT_QP;
-#if FULL_NBIT
-    Double qp_temp_orig = (Double) dQP - SHIFT_QP;
-#endif
-    // Case #1: I or P-slices (key-frame)
-#if NH_MV
-    Double dQPFactor;
-    if( eSliceType != I_SLICE ) 
-    {
-      dQPFactor = m_pcCfg->getGOPEntry( (eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid ).m_QPFactor;
-    }
-    else
-#else
-    Double dQPFactor = m_pcCfg->getGOPEntry(iGOPid).m_QPFactor;
-    if ( eSliceType==I_SLICE )
-#endif
-    {
-      if (m_pcCfg->getIntraQpFactor()>=0.0 && m_pcCfg->getGOPEntry(iGOPid).m_sliceType != I_SLICE)
-      {
-        dQPFactor=m_pcCfg->getIntraQpFactor();
-      }
-      else
-      {
-        Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)(isField ? NumberBFrames/2 : NumberBFrames) );
-        
-        dQPFactor=0.57*dLambda_scale;
-      }
-    }
-    dLambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
-
-    if ( depth>0 )
-    {
-#if FULL_NBIT
-        dLambda *= Clip3( 2.00, 4.00, (qp_temp_orig / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
-#else
-        dLambda *= Clip3( 2.00, 4.00, (qp_temp / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
-#endif
-    }
-
-    // if hadamard is used in ME process
-    if ( !m_pcCfg->getUseHADME() && rpcSlice->getSliceType( ) != I_SLICE )
-    {
-      dLambda *= 0.95;
-    }
-
-#if W0062_RECALCULATE_QP_TO_ALIGN_WITH_LAMBDA
-    Double lambdaRef = 0.57*pow(2.0, qp_temp/3.0);
-    // QP correction due to modified lambda
-    Double qpOffset = floor((3.0*log(dLambda/lambdaRef)/log(2.0)) +0.5);
-    dQP += qpOffset;
-#endif
-
-    iQP = max( -rpcSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), min( MAX_QP, (Int) floor( dQP + 0.5 ) ) );
+    dLambda = calculateLambda(rpcSlice, iGOPid, depth, dQP, dQP, iQP );
 
     m_vdRdPicLambda[iDQpIdx] = dLambda;
@@ -409,4 +371,5 @@
 
 
+#if !X0038_LAMBDA_FROM_QP_CAPABILITY
 #if NH_MV
   const Int temporalId=m_pcCfg->getGOPEntry((eSliceTypeBaseView == I_SLICE) ? MAX_GOP : iGOPid).m_temporalId;
@@ -415,6 +378,6 @@
 #endif
   const std::vector<Double> &intraLambdaModifiers=m_pcCfg->getIntraLambdaModifier();
-
-#if W0038_CQP_ADJ
+#endif
+
   if(rpcSlice->getPPS()->getSliceChromaQpFlag())
   {
@@ -435,6 +398,6 @@
     rpcSlice->setSliceChromaQpDelta( COMPONENT_Cr, 0 );
   }
-#endif
-
+
+#if !X0038_LAMBDA_FROM_QP_CAPABILITY
   Double lambdaModifier;
   if( rpcSlice->getSliceType( ) != I_SLICE || intraLambdaModifiers.empty())
@@ -448,4 +411,6 @@
 
   dLambda *= lambdaModifier;
+#endif
+
   setUpLambda(rpcSlice, dLambda, iQP);
 
@@ -507,8 +472,4 @@
 #endif
   rpcSlice->setSliceQpDelta      ( 0 );
-#if !W0038_CQP_ADJ
-  rpcSlice->setSliceChromaQpDelta( COMPONENT_Cb, 0 );
-  rpcSlice->setSliceChromaQpDelta( COMPONENT_Cr, 0 );
-#endif
   rpcSlice->setUseChromaQpAdj( rpcSlice->getPPS()->getPpsRangeExtension().getChromaQpOffsetListEnabledFlag() );
 #if NH_MV
@@ -530,5 +491,5 @@
   {
     rpcSlice->setDeblockingFilterOverrideFlag( rpcSlice->getPPS()->getDeblockingFilterOverrideEnabledFlag() );
-    rpcSlice->setDeblockingFilterDisable( rpcSlice->getPPS()->getPicDisableDeblockingFilterFlag() );
+    rpcSlice->setDeblockingFilterDisable( rpcSlice->getPPS()->getPPSDeblockingFilterDisabledFlag() );
     if ( !rpcSlice->getDeblockingFilterDisable())
     {
@@ -573,9 +534,110 @@
   rpcSlice->setSliceSegmentMode     ( m_pcCfg->getSliceSegmentMode()     );
   rpcSlice->setSliceSegmentArgument ( m_pcCfg->getSliceSegmentArgument() );
-#if NH_3D_IV_MERGE
+#if NH_3D
 #else
   rpcSlice->setMaxNumMergeCand        ( m_pcCfg->getMaxNumMergeCand()        );
 #endif
 }
+
+Double TEncSlice::calculateLambda( const TComSlice* slice,
+                                   const Int        GOPid, // entry in the GOP table
+                                   const Int        depth, // slice GOP hierarchical depth.
+                                   const Double     refQP, // initial slice-level QP
+                                   const Double     dQP,   // initial double-precision QP
+                                         Int        &iQP )  // returned integer QP.
+{
+  enum   SliceType eSliceType    = slice->getSliceType();
+  const  Bool      isField       = slice->getPic()->isField();
+  const  Int       NumberBFrames = ( m_pcCfg->getGOPSize() - 1 );
+  const  Int       SHIFT_QP      = 12;
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+  const Int temporalId=m_pcCfg->getGOPEntry(GOPid).m_temporalId;
+  const std::vector<Double> &intraLambdaModifiers=m_pcCfg->getIntraLambdaModifier();
+#endif
+
+#if FULL_NBIT
+  Int    bitdepth_luma_qp_scale = 6 * (slice->getSPS()->getBitDepth(CHANNEL_TYPE_LUMA) - 8);
+#else
+  Int    bitdepth_luma_qp_scale = 0;
+#endif
+  Double qp_temp = dQP + bitdepth_luma_qp_scale - SHIFT_QP;
+  // Case #1: I or P-slices (key-frame)
+#if NH_MV
+  Double dQPFactor = m_pcCfg->getGOPEntry( (m_eSliceTypeBaseView == I_SLICE) ? MAX_GOP : GOPid ).m_QPFactor;
+#else
+  Double dQPFactor = m_pcCfg->getGOPEntry(GOPid).m_QPFactor;
+#endif
+  if ( eSliceType==I_SLICE )
+  {
+    if (m_pcCfg->getIntraQpFactor()>=0.0 && m_pcCfg->getGOPEntry(GOPid).m_sliceType != I_SLICE)
+    {
+      dQPFactor=m_pcCfg->getIntraQpFactor();
+    }
+    else
+    {
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+      if(m_pcCfg->getLambdaFromQPEnable())
+      {
+        dQPFactor=0.57;
+      }
+      else
+      {
+#endif
+        Double dLambda_scale = 1.0 - Clip3( 0.0, 0.5, 0.05*(Double)(isField ? NumberBFrames/2 : NumberBFrames) );
+        dQPFactor=0.57*dLambda_scale;
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+      }
+#endif
+    }
+  }
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+  else if( m_pcCfg->getLambdaFromQPEnable() )
+  {
+    dQPFactor=0.57;
+  }
+#endif
+
+  Double dLambda = dQPFactor*pow( 2.0, qp_temp/3.0 );
+
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+  if( !(m_pcCfg->getLambdaFromQPEnable()) && depth>0 )
+#else
+  if ( depth>0 )
+#endif
+  {
+#if FULL_NBIT
+    Double qp_temp_ref_orig = refQP - SHIFT_QP;
+    dLambda *= Clip3( 2.00, 4.00, (qp_temp_ref_orig / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
+#else
+    Double qp_temp_ref = refQP + bitdepth_luma_qp_scale - SHIFT_QP;
+    dLambda *= Clip3( 2.00, 4.00, (qp_temp_ref / 6.0) ); // (j == B_SLICE && p_cur_frm->layer != 0 )
+#endif
+  }
+
+  // if hadamard is used in ME process
+  if ( !m_pcCfg->getUseHADME() && slice->getSliceType( ) != I_SLICE )
+  {
+    dLambda *= 0.95;
+  }
+
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+  Double lambdaModifier;
+  if( eSliceType != I_SLICE || intraLambdaModifiers.empty())
+  {
+    lambdaModifier = m_pcCfg->getLambdaModifier( temporalId );
+  }
+  else
+  {
+    lambdaModifier = intraLambdaModifiers[ (temporalId < intraLambdaModifiers.size()) ? temporalId : (intraLambdaModifiers.size()-1) ];
+  }
+  dLambda *= lambdaModifier;
+#endif
+
+  iQP = max( -slice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA), min( MAX_QP, (Int) floor( dQP + 0.5 ) ) );
+
+  // NOTE: the lambda modifiers that are sometimes applied later might be best always applied in here.
+  return dLambda;
+}
+
 
 Void TEncSlice::resetQP( TComPic* pic, Int sliceQP, Double lambda )
@@ -835,5 +897,5 @@
 #endif
 
-#if NH_3D_IC
+#if NH_3D
   if ( m_pcCfg->getViewIndex() && m_pcCfg->getUseIC() &&
        !( ( pcSlice->getSliceType() == P_SLICE && pcSlice->getPPS()->getUseWP() ) || ( pcSlice->getSliceType() == B_SLICE && pcSlice->getPPS()->getWPBiPred() ) )
@@ -1213,5 +1275,5 @@
     }
 
-#if NH_3D_QTLPC
+#if NH_3D
     pcPic->setReduceBitsFlag(true);
 #endif
@@ -1285,5 +1347,5 @@
       }
     }
-#if NH_3D_QTLPC
+#if NH_3D
     pcPic->setReduceBitsFlag(false);
 #endif
Index: /trunk/source/Lib/TLibEncoder/TEncSlice.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncSlice.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncSlice.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -93,6 +93,6 @@
 #else
   UInt64                  m_uiPicDist;                          ///< total distortion for the picture
-#endif
-  Double                  m_dPicRdCost;                         ///< picture-level RD cost
+#endif  
+ Double                  m_dPicRdCost;                         ///< picture-level RD cost
   std::vector<Double>     m_vdRdPicLambda;                      ///< array of lambda candidates
   std::vector<Double>     m_vdRdPicQp;                          ///< array of picture QP candidates (double-type for lambda)
@@ -103,5 +103,10 @@
   TEncSbac                m_entropyCodingSyncContextState;      ///< context storate for state of contexts at the wavefront/WPP/entropy-coding-sync second CTU of tile-row
   SliceType               m_encCABACTableIdx;
+  Int                     m_gopID;
+#if NH_MV
+  SliceType               m_eSliceTypeBaseView;
+#endif
 
+  Double   calculateLambda( const TComSlice* pSlice, const Int GOPid, const Int depth, const Double refQP, const Double dQP, Int &iQP );
   Void     setUpLambda(TComSlice* slice, const Double dLambda, Int iQP);
   Void     calculateBoundingCtuTsAddrForSlice(UInt &startCtuTSAddrSlice, UInt &boundingCtuTSAddrSlice, Bool &haveReachedTileBoundary, TComPic* pcPic, const Int sliceMode, const Int sliceArgument);
@@ -123,5 +128,10 @@
                                 const Int iGOPid,   TComSlice*& rpcSlice, const Bool isField );
 #endif
+
   Void    resetQP             ( TComPic* pic, Int sliceQP, Double lambda );
+  Void    setGopID( Int iGopID )      { m_gopID = iGopID; }
+  Int     getGopID() const            { return m_gopID;   }
+  Void    updateLambda(TComSlice* pSlice, Double dQP);
+
   // compress and encode slice
   Void    precompressSlice    ( TComPic* pcPic                                     );      ///< precompress slice for multi-loop slice-level QP opt.
Index: /trunk/source/Lib/TLibEncoder/TEncTop.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncTop.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncTop.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -54,6 +54,15 @@
 // ====================================================================================================================
 
-TEncTop::TEncTop()
-{
+#if !NH_MV
+TEncTop::TEncTop() :
+    m_spsMap(MAX_NUM_SPS)
+  , m_ppsMap(MAX_NUM_PPS) 
+#else
+   TEncTop::TEncTop( ParameterSetMap<TComSPS>& spsMap, ParameterSetMap<TComPPS>& ppsMap ) : 
+     m_spsMap(spsMap)
+   , m_ppsMap(ppsMap)
+#endif
+      {
+
   m_iPOCLast          = -1;
   m_iNumPicRcvd       =  0;
@@ -79,5 +88,5 @@
   m_ivPicLists = NULL;
 #endif
-#if NH_3D_IC
+#if NH_3D
   m_aICEnableCandidate = NULL;
   m_aICEnableNum = NULL;
@@ -91,6 +100,5 @@
 TEncTop::~TEncTop()
 {
-#if NH_3D_FIX_LEAK
-#if NH_3D_IC
+#if NH_3D
   if ( m_aICEnableCandidate != NULL )
   {
@@ -104,5 +112,4 @@
 #endif
 
-#endif
 #if ENC_DEC_TRACE
   if (g_hTrace != stdout)
@@ -222,31 +229,74 @@
 #endif
 {
+#if NH_MV
+  Int parameterSetId     =  getParameterSetId( );
+
+  TComSPS& sps0 = *(m_spsMap.allocatePS( parameterSetId ) ); // NOTE: implementations that use more than 1 SPS need to be aware of activation issues.
+  TComPPS& pps0 = *(m_ppsMap.allocatePS( parameterSetId ) );
+#else
+  TComSPS &sps0=*(m_spsMap.allocatePS(0)); // NOTE: implementations that use more than 1 SPS need to be aware of activation issues.
+  TComPPS &pps0=*(m_ppsMap.allocatePS(0));
+#endif
   // initialize SPS
 #if H_3D
   // Assuming that all PPS indirectly refer to the same VPS via different SPS
-  m_cSPS.setVPS(m_cVPS);
-#endif
-  xInitSPS();
-  xInitVPS();
-
-#if U0132_TARGET_BITS_SATURATION
+  sps.setVPS(m_cVPS);
+#endif
+
+#if NH_MV
+  Bool initParameterSets = getSendParameterSets();
+
+  if ( initParameterSets )
+  {
+    xInitSPS( sps0 );
+  }
+#else
+  xInitSPS( sps0 );
+  xInitVPS((*m_cVPS), sps0);
+#endif
+
   if (m_RCCpbSaturationEnabled)
   {
-    m_cRateCtrl.initHrdParam(m_cSPS.getVuiParameters()->getHrdParameters(), m_iFrameRate, m_RCInitialCpbFullness);
-  }
-#endif
+    m_cRateCtrl.initHrdParam(sps0.getVuiParameters()->getHrdParameters(), m_iFrameRate, m_RCInitialCpbFullness);
+  }
+
   m_cRdCost.setCostMode(m_costMode);
 
 #if NH_MV
-  // This seems to be incorrect, but irrelevant for the MV-HEVC
-  *(m_cVPS->getPTL()) = *m_cSPS.getPTL();
-  m_cVPS->getTimingInfo()->setTimingInfoPresentFlag       ( false );
-#endif
-  // initialize PPS
-  xInitPPS();
-  xInitRPS(isFieldCoding);
-
-  xInitPPSforTiles();
-#if NH_3D_IC
+  if ( initParameterSets )
+  {
+    // This seems to be incorrect, but irrelevant for the MV-HEVC
+    if (m_layerId == 0 )
+    {
+      *(m_cVPS->getPTL()) = *sps0.getPTL();
+      m_cVPS->getTimingInfo()->setTimingInfoPresentFlag       ( false );
+    }
+#endif
+    // initialize PPS
+    xInitPPS(pps0, sps0);
+    xInitRPS(sps0, isFieldCoding);
+    xInitScalingLists(sps0, pps0);
+
+    if (m_wcgChromaQpControl.isEnabled())
+    {
+#if NH_MV
+      AOT( true ); // This is currently not supported.
+#endif
+      TComPPS &pps1=*(m_ppsMap.allocatePS(1));
+      xInitPPS(pps1, sps0);
+      xInitScalingLists(sps0, pps1);
+    }
+#if NH_MV
+  }
+
+  // Copy initialized PS
+  m_activeSps    = sps0;
+  m_activePps    = pps0;
+  
+  // Infer layer specific values for copy
+  m_activeSps.inferRepFormat( m_cVPS, getLayerId(), initParameterSets );
+#endif
+
+#if NH_3D
   m_aICEnableCandidate = new Int[ 10 ];
   m_aICEnableNum = new Int[ 10 ];
@@ -258,4 +308,5 @@
   }
 #endif
+
 
   // initialize processing unit classes
@@ -263,4 +314,5 @@
   m_cSliceEncoder.init( this );
   m_cCuEncoder.   init( this );
+  m_cCuEncoder.setSliceEncoder(&m_cSliceEncoder);
 
 #if KWU_RC_MADPRED_E0227
@@ -273,7 +325,5 @@
                    m_useRDOQ,
                    m_useRDOQTS,
-#if T0196_SELECTIVE_RDOQ
                    m_useSelectiveRDOQ,
-#endif
                    true
                   ,m_useTransformSkipFast
@@ -287,9 +337,7 @@
 
   m_iMaxRefPicNum = 0;
-
-  xInitScalingLists();
-}
-
-Void TEncTop::xInitScalingLists()
+}
+
+Void TEncTop::xInitScalingLists(TComSPS &sps, TComPPS &pps)
 {
   // Initialise scaling lists
@@ -297,27 +345,27 @@
   const Int maxLog2TrDynamicRange[MAX_NUM_CHANNEL_TYPE] =
   {
-      m_cSPS.getMaxLog2TrDynamicRange(CHANNEL_TYPE_LUMA),
-      m_cSPS.getMaxLog2TrDynamicRange(CHANNEL_TYPE_CHROMA)
+      sps.getMaxLog2TrDynamicRange(CHANNEL_TYPE_LUMA),
+      sps.getMaxLog2TrDynamicRange(CHANNEL_TYPE_CHROMA)
   };
   if(getUseScalingListId() == SCALING_LIST_OFF)
   {
-    getTrQuant()->setFlatScalingList(maxLog2TrDynamicRange, m_cSPS.getBitDepths());
+    getTrQuant()->setFlatScalingList(maxLog2TrDynamicRange, sps.getBitDepths());
     getTrQuant()->setUseScalingList(false);
-    m_cSPS.setScalingListPresentFlag(false);
-    m_cPPS.setScalingListPresentFlag(false);
+    sps.setScalingListPresentFlag(false);
+    pps.setScalingListPresentFlag(false);
   }
   else if(getUseScalingListId() == SCALING_LIST_DEFAULT)
   {
-    m_cSPS.getScalingList().setDefaultScalingList ();
-    m_cSPS.setScalingListPresentFlag(false);
-    m_cPPS.setScalingListPresentFlag(false);
-
-    getTrQuant()->setScalingList(&(m_cSPS.getScalingList()), maxLog2TrDynamicRange, m_cSPS.getBitDepths());
+    sps.getScalingList().setDefaultScalingList ();
+    sps.setScalingListPresentFlag(false);
+    pps.setScalingListPresentFlag(false);
+
+    getTrQuant()->setScalingList(&(sps.getScalingList()), maxLog2TrDynamicRange, sps.getBitDepths());
     getTrQuant()->setUseScalingList(true);
   }
   else if(getUseScalingListId() == SCALING_LIST_FILE_READ)
   {
-    m_cSPS.getScalingList().setDefaultScalingList ();
-    if(m_cSPS.getScalingList().xParseScalingList(getScalingListFileName()))
+    sps.getScalingList().setDefaultScalingList ();
+    if(sps.getScalingList().xParseScalingList(getScalingListFileName()))
     {
       Bool bParsedScalingList=false; // Use of boolean so that assertion outputs useful string
@@ -325,8 +373,8 @@
       exit(1);
     }
-    m_cSPS.getScalingList().checkDcOfMatrix();
-    m_cSPS.setScalingListPresentFlag(m_cSPS.getScalingList().checkDefaultScalingList());
-    m_cPPS.setScalingListPresentFlag(false);
-    getTrQuant()->setScalingList(&(m_cSPS.getScalingList()), maxLog2TrDynamicRange, m_cSPS.getBitDepths());
+    sps.getScalingList().checkDcOfMatrix();
+    sps.setScalingListPresentFlag(sps.getScalingList().checkDefaultScalingList());
+    pps.setScalingListPresentFlag(false);
+    getTrQuant()->setScalingList(&(sps.getScalingList()), maxLog2TrDynamicRange, sps.getBitDepths());
     getTrQuant()->setUseScalingList(true);
   }
@@ -346,5 +394,5 @@
     for(UInt listId = 0; listId < SCALING_LIST_NUM; listId+=predListStep)
     {
-      m_cSPS.getScalingList().checkPredMode( sizeId, listId );
+        sps.getScalingList().checkPredMode( sizeId, listId );
     }
   }
@@ -362,5 +410,6 @@
 
   // get original YUV
-  xGetNewPicBuffer( pcPicCurr );
+
+  xGetNewPicBuffer( pcPicCurr, getParameterSetId() );
   pcPicYuvOrg->copyToPic( pcPicCurr->getPicYuvOrg() );
 
@@ -431,5 +480,10 @@
     TComPic* pcPicCurr = NULL;
 
-    xGetNewPicBuffer( pcPicCurr );
+    Int ppsID=-1; // Use default PPS ID
+    if (getWCGChromaQPControl().isEnabled())
+    {
+      ppsID=getdQPs()[ m_iPOCLast+1 ];
+    }
+    xGetNewPicBuffer( pcPicCurr, ppsID );
     pcPicYuvOrg->copyToPic( pcPicCurr->getPicYuvOrg() );
     pcPicYuvTrueOrg->copyToPic( pcPicCurr->getPicYuvTrueOrg() );
@@ -454,5 +508,5 @@
 #if NH_MV
   }
-  m_cGOPEncoder.compressPicInGOP(m_iPOCLast, m_iNumPicRcvd, *(m_ivPicLists->getSubDpb(getLayerId(), false) ), rcListPicYuvRecOut, accessUnitsOut, false, false, snrCSC, m_printFrameMSE, gopId);
+  m_cGOPEncoder.compressPicInGOP(m_iPOCLast, m_iNumPicRcvd, *(m_ivPicLists->getSubDpb(getLayerId(), false) ), rcListPicYuvRecOut, accessUnitsOut, false, false, snrCSC, m_printFrameMSE,  m_printMSSSIM, gopId);
 
   if( gopId + 1 == m_cGOPEncoder.getGOPSize() )
@@ -460,5 +514,9 @@
 #else
   // compress GOP
+#if JVET_F0064_MSSSIM
+  m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false, snrCSC, m_printFrameMSE, m_printMSSSIM);
+#else
   m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, false, false, snrCSC, m_printFrameMSE);
+#endif
 #endif
   if ( m_RCEnableRateControl )
@@ -515,5 +573,5 @@
 
       TComPic *pcField;
-      xGetNewPicBuffer( pcField );
+      xGetNewPicBuffer( pcField, -1 );
       pcField->setReconMark (false);                     // where is this normally?
 
@@ -536,5 +594,7 @@
 
       pcField->getSlice(0)->setPOC( m_iPOCLast );        // superfluous?
+#if !REDUCED_ENCODER_MEMORY
       pcField->getPicYuvRec()->setBorderExtension(false);// where is this normally?
+#endif
 
       pcField->setTopField(isTopField);                  // interlaced requirement
@@ -570,5 +630,9 @@
     {
       // compress GOP
+#if JVET_F0064_MSSSIM
+      m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff, snrCSC, m_printFrameMSE, m_printMSSSIM);
+#else
       m_cGOPEncoder.compressGOP(m_iPOCLast, m_iNumPicRcvd, m_cListPic, rcListPicYuvRecOut, accessUnitsOut, true, isTff, snrCSC, m_printFrameMSE);
+#endif
 
       iNumEncoded += m_iNumPicRcvd;
@@ -590,11 +654,37 @@
  \retval rpcPic obtained picture buffer
  */
-Void TEncTop::xGetNewPicBuffer ( TComPic*& rpcPic )
-{
+Void TEncTop::xGetNewPicBuffer ( TComPic*& rpcPic, Int ppsId )
+{
+  rpcPic=0;
+
+#if NH_MV
+  const TComPPS &pps = m_activePps;
+  const TComSPS &sps = m_activeSps;
+  
+  if ( ppsId > 0 )
+  {
+    assert( pps.getPPSId() == ppsId );
+    assert( sps.getSPSId() == pps.getSPSId() );
+  }
+#else
+  const TComSPS *pSPS=m_spsMap.getPS(pps.getSPSId());
   // At this point, the SPS and PPS can be considered activated - they are copied to the new TComPic.
+  const TComPPS *pPPS=(ppsId<0) ? m_ppsMap.getFirstPS() : m_ppsMap.getPS(ppsId);
+  assert (pPPS!=0);
+  const TComPPS &pps=*pPPS;
+  assert (pSPS!=0);
+
+  assert (pSPS!=0);
+  const TComSPS &sps=*pSPS;
+
+#endif
+
 
 #if NH_MV
   TComList<TComPic*>& cListPic = *(m_ivPicLists->getSubDpb(getLayerId(), false) );
   TComSlice::sortPicList(cListPic);
+  // Infer the correct rep format
+
+  // As 
 #else
   TComSlice::sortPicList(m_cListPic);
@@ -608,4 +698,6 @@
     Int iSize = Int( cListPic.size() );
 #else
+  // use an entry in the buffered list if the maximum number that need buffering has been reached:
+
   if (m_cListPic.size() >= (UInt)(m_iGOPSize + getMaxDecPicBuffering(MAX_TLAYER-1) + 2) )
   {
@@ -615,17 +707,39 @@
     for ( Int i = 0; i < iSize; i++ )
     {
-      rpcPic = *(iterPic++);
+      rpcPic = *iterPic;
       if(rpcPic->getSlice(0)->isReferenced() == false)
       {
         break;
       }
-    }
-  }
-  else
+      iterPic++;
+    }
+    // If PPS ID is the same, we will assume that it has not changed since it was last used
+    // and return the old object.
+    if (pps.getPPSId() == rpcPic->getPicSym()->getPPS().getPPSId())
+    {
+#if REDUCED_ENCODER_MEMORY
+      rpcPic->releaseAllReconstructionData();
+      rpcPic->prepareForEncoderSourcePicYuv();
+#endif
+    }
+    else
+    {
+      // the IDs differ - free up an entry in the list, and then create a new one, as with the case where the max buffering state has not been reached.
+      delete rpcPic;
+      cListPic.erase(iterPic);
+      rpcPic=0;
+    }
+  }
+
+  if (rpcPic==0)
   {
     if ( getUseAdaptiveQP() )
     {
       TEncPic* pcEPic = new TEncPic;
-      pcEPic->create( m_cSPS, m_cPPS, m_cPPS.getMaxCuDQPDepth()+1, false);
+#if REDUCED_ENCODER_MEMORY
+      pcEPic->create( sps, pps, pps.getMaxCuDQPDepth()+1);
+#else
+      pcEPic->create( sps, pps, pps.getMaxCuDQPDepth()+1, false);
+#endif
       rpcPic = pcEPic;
     }
@@ -633,5 +747,9 @@
     {
       rpcPic = new TComPic;
-      rpcPic->create( m_cSPS, m_cPPS, false );
+#if REDUCED_ENCODER_MEMORY
+      rpcPic->create( sps, pps, true, false );
+#else
+      rpcPic->create( sps, pps, false );
+#endif
     }
 
@@ -648,4 +766,5 @@
 
   rpcPic->getSlice(0)->setPOC( m_iPOCLast );
+#if !REDUCED_ENCODER_MEMORY
   // mark it should be extended
   rpcPic->getPicYuvRec()->setBorderExtension(false);
@@ -653,8 +772,8 @@
   rpcPic->getPicYuvOrg()->setBorderExtension(false);
 #endif
-
-}
-
-Void TEncTop::xInitVPS()
+#endif
+}
+
+Void TEncTop::xInitVPS(TComVPS &vps, const TComSPS &sps)
 {
   // The SPS must have already been set up.
@@ -663,14 +782,14 @@
   // Do initialization in TAppEncTop
 #else
-  *m_cVPS.getPTL() = *m_cSPS.getPTL();
-  m_cVPS.setMaxOpSets(1);
-  m_cVPS.getTimingInfo()->setTimingInfoPresentFlag       ( false );
-  m_cVPS.setNumHrdParameters( 0 );
-
-  m_cVPS.createHrdParamBuffer();
-  for( UInt i = 0; i < m_cVPS.getNumHrdParameters(); i ++ )
-  {
-    m_cVPS.setHrdOpSetIdx( 0, i );
-    m_cVPS.setCprmsPresentFlag( false, i );
+  *vps.getPTL() = *sps.getPTL();
+  vps.setMaxOpSets(1);
+  vps.getTimingInfo()->setTimingInfoPresentFlag       ( false );
+  vps.setNumHrdParameters( 0 );
+
+  vps.createHrdParamBuffer();
+  for( UInt i = 0; i < vps.getNumHrdParameters(); i ++ )
+  {
+    vps.setHrdOpSetIdx( 0, i );
+    vps.setCprmsPresentFlag( false, i );
     // Set up HrdParameters here.
   }
@@ -678,12 +797,12 @@
 }
 
-Void TEncTop::xInitSPS()
-{
-#if NH_MV
-  m_cSPS.setSPSId( getLayerIdInVps() );
-  m_cSPS.setLayerId( getLayerId() );
+Void TEncTop::xInitSPS(TComSPS &sps)
+{
+#if NH_MV
+  //AOF( sps.getSPSId() == getLayerIdInVps() );
+  sps.setLayerId( getLayerId() );
  // Code below needs to be moved to VPS
 #endif
-  ProfileTierLevel& profileTierLevel = *m_cSPS.getPTL()->getGeneralPTL();
+  ProfileTierLevel& profileTierLevel = *sps.getPTL()->getGeneralPTL();
   profileTierLevel.setLevelIdc(m_level);
   profileTierLevel.setTierFlag(m_levelTier);
@@ -714,39 +833,39 @@
    * that chooses the actual compatibility based upon options */
 #if NH_MV  
-  m_cSPS.setUpdateRepFormatFlag           ( false );    
-  Bool multiLayerExtensionFlag  = ( getLayerId() > 0 ) && ( m_cVPS->getNumRefLayers( getLayerId() ) > 0 ); 
+  sps.setUpdateRepFormatFlag           ( false );    
   
-  m_cSPS.setSpsExtOrMaxSubLayersMinus1( multiLayerExtensionFlag ? 7 : m_maxTempLayer - 1 );
+  Bool multiLayerExtensionFlag  =      ( getLayerId() > 0  &&  m_cVPS->getNumRefLayers( getLayerId() ) > 0 );
+  sps.setSpsExtOrMaxSubLayersMinus1( multiLayerExtensionFlag ? 7 : m_maxTempLayer - 1 );
   if ( multiLayerExtensionFlag )
   {
-    m_cSPS.setSpsInferScalingListFlag   ( true ); 
-    m_cSPS.setSpsScalingListRefLayerId( m_cVPS->getIdRefLayer( getLayerId(), 0 ) ); 
+    sps.setSpsInferScalingListFlag   ( true ); 
+    sps.setSpsScalingListRefLayerId( m_cVPS->getIdRefLayer( getLayerId(), 0 ) ); 
 #if NH_MV
     if ( m_bUseDisparitySearchRangeRestriction )
     {
-      m_cSPS.setInterViewMvVertConstraintFlag ( true ) ;
+      sps.setInterViewMvVertConstraintFlag ( true ) ;
     }
 #endif
   }  
-  m_cSPS.setSpsExtensionPresentFlag       ( true ); 
-  m_cSPS.setSpsMultilayerExtensionFlag    ( true ); 
+  sps.setSpsExtensionPresentFlag       ( true ); 
+  sps.setSpsMultilayerExtensionFlag    ( true ); 
 #if NH_3D
-  m_cSPS.setSps3dExtensionFlag            ( true ); 
-#endif
-#endif
-
-  m_cSPS.setPicWidthInLumaSamples  ( m_iSourceWidth      );
-  m_cSPS.setPicHeightInLumaSamples ( m_iSourceHeight     );
-  m_cSPS.setConformanceWindow      ( m_conformanceWindow );
-  m_cSPS.setMaxCUWidth             ( m_maxCUWidth        );
-  m_cSPS.setMaxCUHeight            ( m_maxCUHeight       );
-  m_cSPS.setMaxTotalCUDepth        ( m_maxTotalCUDepth   );
+  sps.setSps3dExtensionFlag            ( true ); 
+#endif
+#endif
+
+  sps.setPicWidthInLumaSamples  ( m_iSourceWidth      );
+  sps.setPicHeightInLumaSamples ( m_iSourceHeight     );
+  sps.setConformanceWindow      ( m_conformanceWindow );
+  sps.setMaxCUWidth             ( m_maxCUWidth        );
+  sps.setMaxCUHeight            ( m_maxCUHeight       );
+  sps.setMaxTotalCUDepth        ( m_maxTotalCUDepth   );
 #if NH_3D
   assert( !getIsDepth()  || m_chromaFormatIDC == CHROMA_400 ); 
 #endif
-  m_cSPS.setChromaFormatIdc( m_chromaFormatIDC);
-  m_cSPS.setLog2DiffMaxMinCodingBlockSize(m_log2DiffMaxMinCodingBlockSize);
-
-  Int minCUSize = m_cSPS.getMaxCUWidth() >> ( m_cSPS.getLog2DiffMaxMinCodingBlockSize() );
+  sps.setChromaFormatIdc( m_chromaFormatIDC);
+  sps.setLog2DiffMaxMinCodingBlockSize(m_log2DiffMaxMinCodingBlockSize);
+
+  Int minCUSize = sps.getMaxCUWidth() >> ( sps.getLog2DiffMaxMinCodingBlockSize() );
   Int log2MinCUSize = 0;
   while(minCUSize > 1)
@@ -756,42 +875,39 @@
   }
 
-  m_cSPS.setLog2MinCodingBlockSize(log2MinCUSize);
-
-  m_cSPS.setPCMLog2MinSize (m_uiPCMLog2MinSize);
-  m_cSPS.setUsePCM        ( m_usePCM           );
-  m_cSPS.setPCMLog2MaxSize( m_pcmLog2MaxSize  );
-
-  m_cSPS.setQuadtreeTULog2MaxSize( m_uiQuadtreeTULog2MaxSize );
-  m_cSPS.setQuadtreeTULog2MinSize( m_uiQuadtreeTULog2MinSize );
-  m_cSPS.setQuadtreeTUMaxDepthInter( m_uiQuadtreeTUMaxDepthInter    );
-  m_cSPS.setQuadtreeTUMaxDepthIntra( m_uiQuadtreeTUMaxDepthIntra    );
-
-  m_cSPS.setTMVPFlagsPresent((getTMVPModeId() == 2 || getTMVPModeId() == 1));
-
-  m_cSPS.setMaxTrSize   ( 1 << m_uiQuadtreeTULog2MaxSize );
-
-  m_cSPS.setUseAMP ( m_useAMP );
+  sps.setLog2MinCodingBlockSize(log2MinCUSize);
+
+  sps.setPCMLog2MinSize (m_uiPCMLog2MinSize);
+  sps.setUsePCM        ( m_usePCM           );
+  sps.setPCMLog2MaxSize( m_pcmLog2MaxSize  );
+
+  sps.setQuadtreeTULog2MaxSize( m_uiQuadtreeTULog2MaxSize );
+  sps.setQuadtreeTULog2MinSize( m_uiQuadtreeTULog2MinSize );
+  sps.setQuadtreeTUMaxDepthInter( m_uiQuadtreeTUMaxDepthInter    );
+  sps.setQuadtreeTUMaxDepthIntra( m_uiQuadtreeTUMaxDepthIntra    );
+
+  sps.setSPSTemporalMVPEnabledFlag((getTMVPModeId() == 2 || getTMVPModeId() == 1));
+
+  sps.setMaxTrSize   ( 1 << m_uiQuadtreeTULog2MaxSize );
+
+  sps.setUseAMP ( m_useAMP );
 
   for (UInt channelType = 0; channelType < MAX_NUM_CHANNEL_TYPE; channelType++)
   {
-    m_cSPS.setBitDepth      (ChannelType(channelType), m_bitDepth[channelType] );
+    sps.setBitDepth      (ChannelType(channelType), m_bitDepth[channelType] );
 #if O0043_BEST_EFFORT_DECODING
-    m_cSPS.setStreamBitDepth(ChannelType(channelType), m_bitDepth[channelType] );
-#endif
-    m_cSPS.setQpBDOffset  (ChannelType(channelType), (6 * (m_bitDepth[channelType] - 8)));
-    m_cSPS.setPCMBitDepth (ChannelType(channelType), m_PCMBitDepth[channelType]         );
-  }
-#if NH_MV
-  m_cSPS.inferRepFormat( m_cVPS, getLayerId(), true ); 
-#endif
-m_cSPS.setUseSAO( m_bUseSAO );
-
-  m_cSPS.setMaxTLayers( m_maxTempLayer );
-  m_cSPS.setTemporalIdNestingFlag( ( m_maxTempLayer == 1 ) ? true : false );
-
-  for (Int i = 0; i < min(m_cSPS.getMaxTLayers(),(UInt) MAX_TLAYER); i++ )
-  {
-    m_cSPS.setMaxDecPicBuffering(m_maxDecPicBuffering[i], i);
-    m_cSPS.setNumReorderPics(m_numReorderPics[i], i);
+    sps.setStreamBitDepth(ChannelType(channelType), m_bitDepth[channelType] );
+#endif
+    sps.setQpBDOffset  (ChannelType(channelType), (6 * (m_bitDepth[channelType] - 8)));
+    sps.setPCMBitDepth (ChannelType(channelType), m_PCMBitDepth[channelType]         );
+  }
+  sps.setUseSAO( m_bUseSAO );
+
+  sps.setMaxTLayers( m_maxTempLayer );
+  sps.setTemporalIdNestingFlag( ( m_maxTempLayer == 1 ) ? true : false );
+
+  for (Int i = 0; i < min(sps.getMaxTLayers(),(UInt) MAX_TLAYER); i++ )
+  {
+    sps.setMaxDecPicBuffering(m_maxDecPicBuffering[i], i);
+    sps.setNumReorderPics(m_numReorderPics[i], i);
   }
 #if NH_MV
@@ -804,19 +920,19 @@
       if ( m_cVPS->getNecessaryLayerFlag( ols, is ) )
       {      
-        m_cSPS.inferSpsMaxDecPicBufferingMinus1( m_cVPS, ols, targetDecLayerIdList[is], true );       
-      }
-    }
-  }
-#endif
-
-
-  m_cSPS.setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag );
-  m_cSPS.setScalingListFlag ( (m_useScalingListId == SCALING_LIST_OFF) ? 0 : 1 );
-  m_cSPS.setUseStrongIntraSmoothing( m_useStrongIntraSmoothing );
-  m_cSPS.setVuiParametersPresentFlag(getVuiParametersPresentFlag());
-
-  if (m_cSPS.getVuiParametersPresentFlag())
-  {
-    TComVUI* pcVUI = m_cSPS.getVuiParameters();
+        sps.inferSpsMaxDecPicBufferingMinus1( m_cVPS, ols, targetDecLayerIdList[is], true );       
+      }
+    }
+  }
+#endif
+
+
+  sps.setPCMFilterDisableFlag  ( m_bPCMFilterDisableFlag );
+  sps.setScalingListFlag ( (m_useScalingListId == SCALING_LIST_OFF) ? 0 : 1 );
+  sps.setUseStrongIntraSmoothing( m_useStrongIntraSmoothing );
+  sps.setVuiParametersPresentFlag(getVuiParametersPresentFlag());
+
+  if (sps.getVuiParametersPresentFlag())
+  {
+    TComVUI* pcVUI = sps.getVuiParameters();
     pcVUI->setAspectRatioInfoPresentFlag(getAspectRatioInfoPresentFlag());
     pcVUI->setAspectRatioIdc(getAspectRatioIdc());
@@ -855,45 +971,47 @@
     pcVUI->setLog2MaxMvLengthVertical(getLog2MaxMvLengthVertical());
   }
-  m_cSPS.setNumLongTermRefPicSPS(NUM_LONG_TERM_REF_PIC_SPS);
+  sps.setNumLongTermRefPicSPS(NUM_LONG_TERM_REF_PIC_SPS);
   assert (NUM_LONG_TERM_REF_PIC_SPS <= MAX_NUM_LONG_TERM_REF_PICS);
   for (Int k = 0; k < NUM_LONG_TERM_REF_PIC_SPS; k++)
   {
-    m_cSPS.setLtRefPicPocLsbSps(k, 0);
-    m_cSPS.setUsedByCurrPicLtSPSFlag(k, 0);
-  }
-
-#if U0132_TARGET_BITS_SATURATION
+    sps.setLtRefPicPocLsbSps(k, 0);
+    sps.setUsedByCurrPicLtSPSFlag(k, 0);
+  }
+
   if( getPictureTimingSEIEnabled() || getDecodingUnitInfoSEIEnabled() || getCpbSaturationEnabled() )
-#else
-  if( getPictureTimingSEIEnabled() || getDecodingUnitInfoSEIEnabled() )
-#endif
-  {
-    xInitHrdParameters();
+  {
+    xInitHrdParameters(sps);
   }
   if( getBufferingPeriodSEIEnabled() || getPictureTimingSEIEnabled() || getDecodingUnitInfoSEIEnabled() )
   {
-    m_cSPS.getVuiParameters()->setHrdParametersPresentFlag( true );
+    sps.getVuiParameters()->setHrdParametersPresentFlag( true );
   }
 
   // Set up SPS range extension settings
-  m_cSPS.getSpsRangeExtension().setTransformSkipRotationEnabledFlag(m_transformSkipRotationEnabledFlag);
-  m_cSPS.getSpsRangeExtension().setTransformSkipContextEnabledFlag(m_transformSkipContextEnabledFlag);
+  sps.getSpsRangeExtension().setTransformSkipRotationEnabledFlag(m_transformSkipRotationEnabledFlag);
+  sps.getSpsRangeExtension().setTransformSkipContextEnabledFlag(m_transformSkipContextEnabledFlag);
   for (UInt signallingModeIndex = 0; signallingModeIndex < NUMBER_OF_RDPCM_SIGNALLING_MODES; signallingModeIndex++)
   {
-    m_cSPS.getSpsRangeExtension().setRdpcmEnabledFlag(RDPCMSignallingMode(signallingModeIndex), m_rdpcmEnabledFlag[signallingModeIndex]);
-  }
-  m_cSPS.getSpsRangeExtension().setExtendedPrecisionProcessingFlag(m_extendedPrecisionProcessingFlag);
-  m_cSPS.getSpsRangeExtension().setIntraSmoothingDisabledFlag( m_intraSmoothingDisabledFlag );
-  m_cSPS.getSpsRangeExtension().setHighPrecisionOffsetsEnabledFlag(m_highPrecisionOffsetsEnabledFlag);
-  m_cSPS.getSpsRangeExtension().setPersistentRiceAdaptationEnabledFlag(m_persistentRiceAdaptationEnabledFlag);
-  m_cSPS.getSpsRangeExtension().setCabacBypassAlignmentEnabledFlag(m_cabacBypassAlignmentEnabledFlag);
-#if NH_MV
-  m_cSPS.setSpsRangeExtensionsFlag( m_cSPS.getSpsRangeExtension().settingsDifferFromDefaults() );
-#endif
-}
-#if U0132_TARGET_BITS_SATURATION
+    sps.getSpsRangeExtension().setRdpcmEnabledFlag(RDPCMSignallingMode(signallingModeIndex), m_rdpcmEnabledFlag[signallingModeIndex]);
+  }
+  sps.getSpsRangeExtension().setExtendedPrecisionProcessingFlag(m_extendedPrecisionProcessingFlag);
+  sps.getSpsRangeExtension().setIntraSmoothingDisabledFlag( m_intraSmoothingDisabledFlag );
+  sps.getSpsRangeExtension().setHighPrecisionOffsetsEnabledFlag(m_highPrecisionOffsetsEnabledFlag);
+  sps.getSpsRangeExtension().setPersistentRiceAdaptationEnabledFlag(m_persistentRiceAdaptationEnabledFlag);
+  sps.getSpsRangeExtension().setCabacBypassAlignmentEnabledFlag(m_cabacBypassAlignmentEnabledFlag);
+#if NH_MV
+  sps.setSpsRangeExtensionsFlag( sps.getSpsRangeExtension().settingsDifferFromDefaults() );
+#endif
+#if NH_3D
+  sps.setSps3dExtension( m_sps3dExtension );
+#endif
+}
 // calculate scale value of bitrate and initial delay
 Int calcScale(Int x)
 {
+  if (x==0)
+  {
+    return 0;
+  }
   UInt iMask = 0xffffffff;
   Int ScaleValue = 32;
@@ -907,22 +1025,18 @@
   return ScaleValue;
 }
-#endif
-Void TEncTop::xInitHrdParameters()
+Void TEncTop::xInitHrdParameters(TComSPS &sps)
 {
   Bool useSubCpbParams = (getSliceMode() > 0) || (getSliceSegmentMode() > 0);
   Int  bitRate         = getTargetBitrate();
   Bool isRandomAccess  = getIntraPeriod() > 0;
-# if U0132_TARGET_BITS_SATURATION
   Int cpbSize          = getCpbSize();
 
+  assert (cpbSize!=0);  // CPB size may not be equal to zero. ToDo: have a better default and check for level constraints
   if( !getVuiParametersPresentFlag() && !getCpbSaturationEnabled() )
-#else
-  if( !getVuiParametersPresentFlag() )
-#endif
   {
     return;
   }
 
-  TComVUI *vui = m_cSPS.getVuiParameters();
+  TComVUI *vui = sps.getVuiParameters();
   TComHRD *hrd = vui->getHrdParameters();
 
@@ -982,5 +1096,4 @@
   }
 
-#if U0132_TARGET_BITS_SATURATION
   if (calcScale(bitRate) <= 6)
   {
@@ -1000,8 +1113,4 @@
     hrd->setCpbSizeScale(calcScale(cpbSize) - 4);
   }
-#else
-  hrd->setBitRateScale( 4 );                                       // in units of 2^( 6 + 4 ) = 1,024 bps
-  hrd->setCpbSizeScale( 6 );                                       // in units of 2^( 4 + 6 ) = 1,024 bit
-#endif
 
   hrd->setDuCpbSizeScale( 6 );                                     // in units of 2^( 4 + 6 ) = 1,024 bit
@@ -1036,10 +1145,5 @@
     bitrateValue = bitRate / (1 << (6 + hrd->getBitRateScale()) );      // bitRate is in bits, so it needs to be scaled down
     // CpbSize[ i ] = ( cpb_size_value_minus1[ i ] + 1 ) * 2^( 4 + cpb_size_scale )
-#if U0132_TARGET_BITS_SATURATION
     cpbSizeValue = cpbSize / (1 << (4 + hrd->getCpbSizeScale()) );      // using bitRate results in 1 second CPB size
-#else
-    cpbSizeValue = bitRate / (1 << (4 + hrd->getCpbSizeScale()) );      // using bitRate results in 1 second CPB size
-#endif
-
 
     // DU CPB size could be smaller (i.e. bitrateValue / number of DUs), but we don't know 
@@ -1066,8 +1170,13 @@
 
 
-Void TEncTop::xInitPPS()
-{
-#if NH_MV
-  m_cPPS.setLayerId( getLayerId() );
+Void TEncTop::xInitPPS(TComPPS &pps, const TComSPS &sps) const
+{
+
+  // pps ID already initialised.
+  pps.setSPSId(sps.getSPSId());
+
+#if NH_MV
+  AOF( pps.getPPSId() ==  getLayerIdInVps() );
+  pps.setLayerId( getLayerId() );
 #if NH_3D
   // Check if this condition is still correct
@@ -1077,16 +1186,16 @@
 #endif
   {
-    m_cPPS.setListsModificationPresentFlag( true );
-  }
-  m_cPPS.setPPSId( getLayerIdInVps() );
-  m_cPPS.setSPSId( getLayerIdInVps() );
-  m_cPPS.setPpsMultilayerExtensionFlag    ( true ); 
+    pps.setListsModificationPresentFlag( true );
+  }
+  pps.setPpsMultilayerExtensionFlag    ( true ); 
 #if NH_3D
   // Might be used for DLT
-  m_cPPS.setPps3dExtensionFlag            ( getIsDepth() ); 
-#endif
-#endif
-
-#if NH_3D_DLT
+  pps.setPps3dExtensionFlag            ( getIsDepth() ); 
+#endif
+#endif
+
+#if NH_3D
+  // This should be done in TEncAppTop
+  TComDLT curDlt = m_cDLT;
   // create mapping from depth layer indexes to layer ids
   Int j=0;
@@ -1095,10 +1204,10 @@
     Int layerId = getVPS()->getLayerIdInNuh(i);
     if( getVPS()->getDepthId(layerId) )
-      m_cDLT.setDepthIdxToLayerId(j++, layerId);
-  }
-  m_cPPS.setDLT( m_cDLT );
-#endif
-
-  m_cPPS.setConstrainedIntraPred( m_bUseConstrainedIntraPred );
+      curDlt.setDepthIdxToLayerId(j++, layerId);
+  }
+  pps.setDLT( curDlt );
+#endif
+
+  pps.setConstrainedIntraPred( m_bUseConstrainedIntraPred );
   Bool bUseDQP = (getMaxCuDQPDepth() > 0)? true : false;
 
@@ -1108,4 +1217,9 @@
   }
 
+  if ( getLumaLevelToDeltaQPMapping().isEnabled() )
+  {
+    bUseDQP = true;
+  }
+
   if (m_costMode==COST_SEQUENCE_LEVEL_LOSSLESS || m_costMode==COST_LOSSLESS_CODING)
   {
@@ -1113,40 +1227,52 @@
   }
 
-
   if ( m_RCEnableRateControl )
   {
-    m_cPPS.setUseDQP(true);
-    m_cPPS.setMaxCuDQPDepth( 0 );
+    pps.setUseDQP(true);
+    pps.setMaxCuDQPDepth( 0 );
   }
   else if(bUseDQP)
   {
-    m_cPPS.setUseDQP(true);
-    m_cPPS.setMaxCuDQPDepth( m_iMaxCuDQPDepth );
+    pps.setUseDQP(true);
+    pps.setMaxCuDQPDepth( m_iMaxCuDQPDepth );
   }
   else
   {
-    m_cPPS.setUseDQP(false);
-    m_cPPS.setMaxCuDQPDepth( 0 );
+    pps.setUseDQP(false);
+    pps.setMaxCuDQPDepth( 0 );
   }
 
   if ( m_diffCuChromaQpOffsetDepth >= 0 )
   {
-    m_cPPS.getPpsRangeExtension().setDiffCuChromaQpOffsetDepth(m_diffCuChromaQpOffsetDepth);
-    m_cPPS.getPpsRangeExtension().clearChromaQpOffsetList();
-    m_cPPS.getPpsRangeExtension().setChromaQpOffsetListEntry(1, 6, 6);
+    pps.getPpsRangeExtension().setDiffCuChromaQpOffsetDepth(m_diffCuChromaQpOffsetDepth);
+    pps.getPpsRangeExtension().clearChromaQpOffsetList();
+    pps.getPpsRangeExtension().setChromaQpOffsetListEntry(1, 6, 6);
     /* todo, insert table entries from command line (NB, 0 should not be touched) */
   }
   else
   {
-    m_cPPS.getPpsRangeExtension().setDiffCuChromaQpOffsetDepth(0);
-    m_cPPS.getPpsRangeExtension().clearChromaQpOffsetList();
-  }
-  m_cPPS.getPpsRangeExtension().setCrossComponentPredictionEnabledFlag(m_crossComponentPredictionEnabledFlag);
-  m_cPPS.getPpsRangeExtension().setLog2SaoOffsetScale(CHANNEL_TYPE_LUMA,   m_log2SaoOffsetScale[CHANNEL_TYPE_LUMA  ]);
-  m_cPPS.getPpsRangeExtension().setLog2SaoOffsetScale(CHANNEL_TYPE_CHROMA, m_log2SaoOffsetScale[CHANNEL_TYPE_CHROMA]);
-
-  m_cPPS.setQpOffset(COMPONENT_Cb, m_chromaCbQpOffset );
-  m_cPPS.setQpOffset(COMPONENT_Cr, m_chromaCrQpOffset );
-#if W0038_CQP_ADJ
+    pps.getPpsRangeExtension().setDiffCuChromaQpOffsetDepth(0);
+    pps.getPpsRangeExtension().clearChromaQpOffsetList();
+  }
+  pps.getPpsRangeExtension().setCrossComponentPredictionEnabledFlag(m_crossComponentPredictionEnabledFlag);
+  pps.getPpsRangeExtension().setLog2SaoOffsetScale(CHANNEL_TYPE_LUMA,   m_log2SaoOffsetScale[CHANNEL_TYPE_LUMA  ]);
+  pps.getPpsRangeExtension().setLog2SaoOffsetScale(CHANNEL_TYPE_CHROMA, m_log2SaoOffsetScale[CHANNEL_TYPE_CHROMA]);
+
+  if (getWCGChromaQPControl().isEnabled())
+  {
+    const Int baseQp=m_iQP+pps.getPPSId();
+    const Double chromaQp = m_wcgChromaQpControl.chromaQpScale * baseQp + m_wcgChromaQpControl.chromaQpOffset;
+    const Double dcbQP = m_wcgChromaQpControl.chromaCbQpScale * chromaQp;
+    const Double dcrQP = m_wcgChromaQpControl.chromaCrQpScale * chromaQp;
+    const Int cbQP =(Int)(dcbQP + ( dcbQP < 0 ? -0.5 : 0.5) );
+    const Int crQP =(Int)(dcrQP + ( dcrQP < 0 ? -0.5 : 0.5) );
+    pps.setQpOffset(COMPONENT_Cb, Clip3( -12, 12, min(0, cbQP) + m_chromaCbQpOffset ));
+    pps.setQpOffset(COMPONENT_Cr, Clip3( -12, 12, min(0, crQP) + m_chromaCrQpOffset));
+  }
+  else
+  {
+    pps.setQpOffset(COMPONENT_Cb, m_chromaCbQpOffset );
+    pps.setQpOffset(COMPONENT_Cr, m_chromaCrQpOffset );
+  }
   Bool bChromaDeltaQPEnabled = false;
   {
@@ -1164,49 +1290,49 @@
     }
   }
-  m_cPPS.setSliceChromaQpFlag(bChromaDeltaQPEnabled);
-#endif
-
-  m_cPPS.setEntropyCodingSyncEnabledFlag( m_entropyCodingSyncEnabledFlag );
-  m_cPPS.setTilesEnabledFlag( (m_iNumColumnsMinus1 > 0 || m_iNumRowsMinus1 > 0) );
-  m_cPPS.setUseWP( m_useWeightedPred );
-  m_cPPS.setWPBiPred( m_useWeightedBiPred );
-  m_cPPS.setOutputFlagPresentFlag( false );
-#if NH_MV
-  m_cPPS.setNumExtraSliceHeaderBits( 2 ); 
-#endif
-  m_cPPS.setSignHideFlag(getSignHideFlag());
+  pps.setSliceChromaQpFlag(bChromaDeltaQPEnabled);
+
+  pps.setEntropyCodingSyncEnabledFlag( m_entropyCodingSyncEnabledFlag );
+  pps.setTilesEnabledFlag( (m_iNumColumnsMinus1 > 0 || m_iNumRowsMinus1 > 0) );
+  pps.setUseWP( m_useWeightedPred );
+  pps.setWPBiPred( m_useWeightedBiPred );
+  pps.setOutputFlagPresentFlag( false );
+#if NH_MV
+  pps.setNumExtraSliceHeaderBits( 2 ); 
+#endif
+  pps.setSignDataHidingEnabledFlag(getSignDataHidingEnabledFlag());
+
   if ( getDeblockingFilterMetric() )
   {
-    m_cPPS.setDeblockingFilterOverrideEnabledFlag(true);
-    m_cPPS.setPicDisableDeblockingFilterFlag(false);
+    pps.setDeblockingFilterOverrideEnabledFlag(true);
+    pps.setPPSDeblockingFilterDisabledFlag(false);
   }
   else
   {
-      m_cPPS.setDeblockingFilterOverrideEnabledFlag( !getLoopFilterOffsetInPPS() );
-      m_cPPS.setPicDisableDeblockingFilterFlag( getLoopFilterDisable() );
-    }
-
-  if (! m_cPPS.getPicDisableDeblockingFilterFlag())
-  {
-    m_cPPS.setDeblockingFilterBetaOffsetDiv2( getLoopFilterBetaOffset() );
-    m_cPPS.setDeblockingFilterTcOffsetDiv2( getLoopFilterTcOffset() );
+    pps.setDeblockingFilterOverrideEnabledFlag( !getLoopFilterOffsetInPPS() );
+    pps.setPPSDeblockingFilterDisabledFlag( getLoopFilterDisable() );
+    }
+
+  if (! pps.getPPSDeblockingFilterDisabledFlag())
+  {
+    pps.setDeblockingFilterBetaOffsetDiv2( getLoopFilterBetaOffset() );
+    pps.setDeblockingFilterTcOffsetDiv2( getLoopFilterTcOffset() );
   }
   else
   {
-    m_cPPS.setDeblockingFilterBetaOffsetDiv2(0);
-    m_cPPS.setDeblockingFilterTcOffsetDiv2(0);
+    pps.setDeblockingFilterBetaOffsetDiv2(0);
+    pps.setDeblockingFilterTcOffsetDiv2(0);
   }
 
   // deblockingFilterControlPresentFlag is true if any of the settings differ from the inferred values:
-  const Bool deblockingFilterControlPresentFlag = m_cPPS.getDeblockingFilterOverrideEnabledFlag() ||
-                                                  m_cPPS.getPicDisableDeblockingFilterFlag()      ||
-                                                  m_cPPS.getDeblockingFilterBetaOffsetDiv2() != 0 ||
-                                                  m_cPPS.getDeblockingFilterTcOffsetDiv2() != 0;
-
-  m_cPPS.setDeblockingFilterControlPresentFlag(deblockingFilterControlPresentFlag);
-
-  m_cPPS.setLog2ParallelMergeLevelMinus2   (m_log2ParallelMergeLevelMinus2 );
-  m_cPPS.setCabacInitPresentFlag(CABAC_INIT_PRESENT_FLAG);
-  m_cPPS.setLoopFilterAcrossSlicesEnabledFlag( m_bLFCrossSliceBoundaryFlag );
+  const Bool deblockingFilterControlPresentFlag = pps.getDeblockingFilterOverrideEnabledFlag() ||
+                                                  pps.getPPSDeblockingFilterDisabledFlag()     ||
+                                                  pps.getDeblockingFilterBetaOffsetDiv2() != 0 ||
+                                                  pps.getDeblockingFilterTcOffsetDiv2() != 0;
+
+  pps.setDeblockingFilterControlPresentFlag(deblockingFilterControlPresentFlag);
+
+  pps.setLog2ParallelMergeLevelMinus2   (m_log2ParallelMergeLevelMinus2 );
+  pps.setCabacInitPresentFlag(CABAC_INIT_PRESENT_FLAG);
+  pps.setLoopFilterAcrossSlicesEnabledFlag( m_bLFCrossSliceBoundaryFlag );
 
 
@@ -1233,27 +1359,29 @@
   }
   assert(bestPos <= 15);
-  m_cPPS.setNumRefIdxL0DefaultActive(bestPos);
-  m_cPPS.setNumRefIdxL1DefaultActive(bestPos);
-  m_cPPS.setTransquantBypassEnableFlag(getTransquantBypassEnableFlag());
-  m_cPPS.setUseTransformSkip( m_useTransformSkip );
-  m_cPPS.getPpsRangeExtension().setLog2MaxTransformSkipBlockSize( m_log2MaxTransformSkipBlockSize  );
+  pps.setNumRefIdxL0DefaultActive(bestPos);
+  pps.setNumRefIdxL1DefaultActive(bestPos);
+  pps.setTransquantBypassEnabledFlag(getTransquantBypassEnabledFlag());
+  pps.setUseTransformSkip( m_useTransformSkip );
+  pps.getPpsRangeExtension().setLog2MaxTransformSkipBlockSize( m_log2MaxTransformSkipBlockSize  );
 
   if (m_sliceSegmentMode != NO_SLICES)
   {
-    m_cPPS.setDependentSliceSegmentsEnabledFlag( true );
-  }
+    pps.setDependentSliceSegmentsEnabledFlag( true );
+  }
+
+  xInitPPSforTiles(pps);
 }
 
 //Function for initializing m_RPSList, a list of TComReferencePictureSet, based on the GOPEntry objects read from the config file.
-Void TEncTop::xInitRPS(Bool isFieldCoding)
+Void TEncTop::xInitRPS(TComSPS &sps, Bool isFieldCoding)
 {
   TComReferencePictureSet*      rps;
 
-  m_cSPS.createRPSList(getGOPSize() + m_extraRPSs + 1);
-  TComRPSList* rpsList = m_cSPS.getRPSList();
+  sps.createRPSList(getGOPSize() + m_extraRPSs + 1);
+  TComRPSList* rpsList = sps.getRPSList();
 
   for( Int i = 0; i < getGOPSize()+m_extraRPSs; i++)
   {
-    GOPEntry ge = getGOPEntry(i);
+    const GOPEntry &ge = getGOPEntry(i);
     rps = rpsList->getReferencePictureSet(i);
     rps->setNumberOfPictures(ge.m_numRefPics);
@@ -1480,15 +1608,18 @@
 }
 
-Void  TEncTop::xInitPPSforTiles()
-{
-  m_cPPS.setTileUniformSpacingFlag( m_tileUniformSpacingFlag );
-  m_cPPS.setNumTileColumnsMinus1( m_iNumColumnsMinus1 );
-  m_cPPS.setNumTileRowsMinus1( m_iNumRowsMinus1 );
+Void  TEncTop::xInitPPSforTiles(TComPPS &pps) 
+#if NH_MV
+  const
+#endif
+{
+  pps.setTileUniformSpacingFlag( m_tileUniformSpacingFlag );
+  pps.setNumTileColumnsMinus1( m_iNumColumnsMinus1 );
+  pps.setNumTileRowsMinus1( m_iNumRowsMinus1 );
   if( !m_tileUniformSpacingFlag )
   {
-    m_cPPS.setTileColumnWidth( m_tileColumnWidth );
-    m_cPPS.setTileRowHeight( m_tileRowHeight );
-  }
-  m_cPPS.setLoopFilterAcrossTilesEnabledFlag( m_loopFilterAcrossTilesEnabledFlag );
+    pps.setTileColumnWidth( m_tileColumnWidth );
+    pps.setTileRowHeight( m_tileRowHeight );
+  }
+  pps.setLoopFilterAcrossTilesEnabledFlag( m_loopFilterAcrossTilesEnabledFlag );
 
   // # substreams is "per tile" when tiles are independent.
@@ -1557,4 +1688,101 @@
 }
 
+#if JCTVC_Y0038_PARAMS
+#if NH_MV
+Void TEncTop::setParamSetChanged(Int id, Bool isPps )
+{
+  if ( isPps )
+  {
+    m_ppsMap.setChangedFlag(id);
+  }
+  else
+  {
+    m_spsMap.setChangedFlag(id);
+  }
+}
+#else
+
+Void TEncTop::setParamSetChanged(Int spsId, Int ppsId)
+{
+  m_ppsMap.setChangedFlag(ppsId);
+  m_spsMap.setChangedFlag(spsId);
+}
+#endif
+#endif
+
+Bool TEncTop::PPSNeedsWriting(Int ppsId)
+{
+  Bool bChanged=m_ppsMap.getChangedFlag(ppsId);
+  m_ppsMap.clearChangedFlag(ppsId);
+  return bChanged;
+}
+
+Bool TEncTop::SPSNeedsWriting(Int spsId)
+{
+  Bool bChanged=m_spsMap.getChangedFlag(spsId);
+  m_spsMap.clearChangedFlag(spsId);
+  return bChanged;
+}
+
+#if X0038_LAMBDA_FROM_QP_CAPABILITY
+Int TEncCfg::getQPForPicture(const UInt gopIndex, const TComSlice *pSlice) const
+{
+  const Int lumaQpBDOffset = pSlice->getSPS()->getQpBDOffset(CHANNEL_TYPE_LUMA);
+  Int qp;
+
+  if (getCostMode()==COST_LOSSLESS_CODING)
+  {
+    qp=LOSSLESS_AND_MIXED_LOSSLESS_RD_COST_TEST_QP;
+  }
+  else
+  {
+    const SliceType sliceType=pSlice->getSliceType();
+
+    qp = getBaseQP();
+
+#if JVET_G0101_QP_SWITCHING
+    // modify QP if a fractional QP was originally specified, cause dQPs to be 0 or 1.
+    const Int* pdQPs = getdQPs();
+    if ( pdQPs )
+    {
+      qp += pdQPs[ pSlice->getPOC() ];
+    }
+#endif
+
+    if(sliceType==I_SLICE)
+    {
+      qp += getIntraQPOffset();
+    }
+    else
+    {
+      // Only adjust QP when not lossless
+      if (!(( getMaxDeltaQP() == 0 ) && (!getLumaLevelToDeltaQPMapping().isEnabled()) && (qp == -lumaQpBDOffset ) && (pSlice->getPPS()->getTransquantBypassEnabledFlag())))
+      {
+        const GOPEntry &gopEntry=getGOPEntry(gopIndex);
+        // adjust QP according to the QP offset for the GOP entry.
+        qp +=gopEntry.m_QPOffset;
+
+        // adjust QP according to QPOffsetModel for the GOP entry.
+        Double dqpOffset=qp*gopEntry.m_QPOffsetModelScale+gopEntry.m_QPOffsetModelOffset+0.5;
+        Int qpOffset = (Int)floor(Clip3<Double>(0.0, 3.0, dqpOffset));
+        qp += qpOffset ;
+      }
+    }
+
+#if !JVET_G0101_QP_SWITCHING
+    // modify QP if a fractional QP was originally specified, cause dQPs to be 0 or 1.
+    const Int* pdQPs = getdQPs();
+    if ( pdQPs )
+    {
+      qp += pdQPs[ pSlice->getPOC() ];
+    }
+#endif
+  }
+  qp = Clip3( -lumaQpBDOffset, MAX_QP, qp );
+  return qp;
+}
+#endif
+
+
 #if NH_MV
 Int TEncTop::getFrameId(Int iGOPid)  
@@ -1583,4 +1811,11 @@
   }
   return pcPic;
+}
+
+
+Int TEncTop::xGetPsIdAndPsLayerId( )
+{
+  // LayerId of the parameter set and the Parameter set id are always equal in HTM
+  return ( m_sendParameterSets ?  ( getLayerId() == 0 ?  0 : 1 )  : getLayerId() );
 }
 
@@ -1700,5 +1935,8 @@
   }
 }
-#endif
+
+
+#endif
+
 
 //! \}
Index: /trunk/source/Lib/TLibEncoder/TEncTop.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/TEncTop.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/TEncTop.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -83,5 +83,5 @@
   TComPicLists*           m_ivPicLists;                   ///< access to picture lists of other layers 
 #endif
-#if NH_3D_IC
+#if NH_3D
   Int *m_aICEnableCandidate;
   Int *m_aICEnableNum;
@@ -104,7 +104,17 @@
   TEncSlice               m_cSliceEncoder;                ///< slice encoder
   TEncCu                  m_cCuEncoder;                   ///< CU encoder
+
+#if NH_3D  
+  TComSps3dExtension     m_sps3dExtension;
+#endif
+
   // SPS
-  TComSPS                 m_cSPS;                         ///< SPS. This is the base value. This is copied to TComPicSym
-  TComPPS                 m_cPPS;                         ///< PPS. This is the base value. This is copied to TComPicSym
+#if NH_MV
+  ParameterSetMap<TComSPS>& m_spsMap;                      ///< SPS. This is the base value. This is copied to TComPicSym
+  ParameterSetMap<TComPPS>& m_ppsMap;                      ///< PPS. This is the base value. This is copied to TComPicSym
+#else
+  ParameterSetMap<TComSPS> m_spsMap;                      ///< SPS. This is the base value. This is copied to TComPicSym
+  ParameterSetMap<TComPPS> m_ppsMap;                      ///< PPS. This is the base value. This is copied to TComPicSym
+#endif
   // RD cost computation
   TComRdCost              m_cRdCost;                      ///< RD cost computation class
@@ -135,17 +145,28 @@
   TEncAnalyze             m_cAnalyzeAll_in;
 #endif
+  
 protected:
-  Void  xGetNewPicBuffer  ( TComPic*& rpcPic );           ///< get picture buffer which will be processed
-  Void  xInitVPS          ();                             ///< initialize VPS from encoder options
-  Void  xInitSPS          ();                             ///< initialize SPS from encoder options
-  Void  xInitPPS          ();                             ///< initialize PPS from encoder options
-  Void  xInitScalingLists();                              ///< initialize scaling lists
-  Void  xInitHrdParameters();                             ///< initialize HRD parameters
-
-  Void  xInitPPSforTiles  ();
-  Void  xInitRPS          (Bool isFieldCoding);           ///< initialize PPS from encoder options
+  Void  xGetNewPicBuffer  ( TComPic*& rpcPic, Int ppsId ); ///< get picture buffer which will be processed. If ppsId<0, then the ppsMap will be queried for the first match.
+  Void  xInitVPS          (TComVPS &vps, const TComSPS &sps); ///< initialize VPS from encoder options
+  Void  xInitSPS          (TComSPS &sps);                 ///< initialize SPS from encoder options
+  Void  xInitPPS          (TComPPS &pps, const TComSPS &sps) const; ///< initialize PPS from encoder options
+  Void  xInitScalingLists (TComSPS &sps, TComPPS &pps);   ///< initialize scaling lists
+  Void  xInitHrdParameters(TComSPS &sps);                 ///< initialize HRD parameters
+
+#if NH_MV  
+  Int   xGetPsIdAndPsLayerId      ( ); 
+
+  Void  xInitPPSforTiles  (TComPPS &pps) const ;
+#else
+  Void  xInitPPSforTiles  (TComPPS &pps);
+#endif
+  Void  xInitRPS          (TComSPS &sps, Bool isFieldCoding);           ///< initialize PPS from encoder options
 
 public:
+#if NH_MV
+  TEncTop( ParameterSetMap<TComSPS>& spsMap, ParameterSetMap<TComPPS>& ppsMap );
+#else
   TEncTop();
+#endif
   virtual ~TEncTop();
 
@@ -160,5 +181,5 @@
   TComPicLists* getIvPicLists() { return m_ivPicLists; }
 #endif
-#if NH_3D_IC
+#if NH_3D
   Int*      getICEnableCandidate() { return m_aICEnableCandidate; }
   Int*      getICEnableNum() { return m_aICEnableNum; }
@@ -212,10 +233,19 @@
 #endif
 #if NH_3D
-  Void                    setSps3dExtension     ( TComSps3dExtension sps3dExtension ) { m_cSPS.setSps3dExtension( sps3dExtension );  };
-#endif
-#if NH_3D_IC
+  Void                    setSps3dExtension     ( TComSps3dExtension sps3dExtension ) { m_sps3dExtension = sps3dExtension;  };
   Void                    setICEnableCandidate         ( Int* ICEnableCandidate) { m_aICEnableCandidate = ICEnableCandidate; }
   Void                    setICEnableNum         ( Int* ICEnableNum) { m_aICEnableNum = ICEnableNum; }
 #endif
+
+#if JCTVC_Y0038_PARAMS
+#if NH_MV
+  Void                   setParamSetChanged(Int iD, Bool isPps );
+#else
+  Void                   setParamSetChanged(Int spsId, Int ppsId);
+#endif
+#endif
+  Bool                   PPSNeedsWriting(Int ppsId);
+  Bool                   SPSNeedsWriting(Int spsId);
+
   // -------------------------------------------------------------------------------------------------------------------
   // encoder function
@@ -248,5 +278,9 @@
                std::list<AccessUnit>& accessUnitsOut, Int& iNumEncoded, Bool isTff);
 #endif
-  Void printSummary(Bool isField) { m_cGOPEncoder.printOutSummary (m_uiNumAllPicCoded, isField, m_printMSEBasedSequencePSNR, m_printSequenceMSE, m_cSPS.getBitDepths()); }
+#if JVET_F0064_MSSSIM
+  Void printSummary(Bool isField) { m_cGOPEncoder.printOutSummary (m_uiNumAllPicCoded, isField, m_printMSEBasedSequencePSNR, m_printSequenceMSE, m_printMSSSIM, m_spsMap.getFirstPS()->getBitDepths()); }
+#else
+  Void printSummary(Bool isField) { m_cGOPEncoder.printOutSummary (m_uiNumAllPicCoded, isField, m_printMSEBasedSequencePSNR, m_printSequenceMSE, m_spsMap.getFirstPS()->getBitDepths()); }
+#endif
 
 #if NH_3D_VSO
Index: /trunk/source/Lib/TLibEncoder/WeightPredAnalysis.cpp
===================================================================
--- /trunk/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/WeightPredAnalysis.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibEncoder/WeightPredAnalysis.h
===================================================================
--- /trunk/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 1412)
+++ /trunk/source/Lib/TLibEncoder/WeightPredAnalysis.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/TLibExtractor/TExtrTop.cpp
===================================================================
--- /trunk/source/Lib/TLibExtractor/TExtrTop.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibExtractor/TExtrTop.cpp	(revision 1413)
@@ -48,5 +48,5 @@
 Void TExtrTop::init()
 {
-  m_cEntropyDecoder.init(&m_cPrediction);
+  m_cEntropyDecoder.init(&m_cPrediction, NULL);
 
   m_acSPSBuffer.clear();
Index: /trunk/source/Lib/TLibRenderer/TRenModel.cpp
===================================================================
--- /trunk/source/Lib/TLibRenderer/TRenModel.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibRenderer/TRenModel.cpp	(revision 1413)
@@ -418,17 +418,8 @@
 
 #if H_3D_VSO_EARLY_SKIP
-#if RM_INIT_FIX
   m_apcRenModels[iModelNum]->create( iMode ,m_iWidth, m_iHeight, m_iShiftPrec, m_aaaiSubPelShiftLut, m_iHoleMargin,  bUseOrgRef, ( iMode != 2 )  ? BLEND_NONE : iBlendMode , m_bLimOutput, m_bEarlySkip );
+
 #else
-  m_apcRenModels[iModelNum]->create( iMode ,m_iWidth, m_iHeight, m_iShiftPrec, m_aaaiSubPelShiftLut, m_iHoleMargin,  bUseOrgRef, iBlendMode, m_bLimOutput, m_bEarlySkip );
-#endif
-
-#else
-
-#if RM_INIT_FIX
   m_apcRenModels[iModelNum]->create( iMode ,m_iWidth, m_iHeight, m_iShiftPrec, m_aaaiSubPelShiftLut, m_iHoleMargin,  bUseOrgRef, ( iMode != 2 )  ? BLEND_NONE : iBlendMode, m_bLimOutput );
-#else
-  m_apcRenModels[iModelNum]->create( iMode ,m_iWidth, m_iHeight, m_iShiftPrec, m_aaaiSubPelShiftLut, m_iHoleMargin,  bUseOrgRef, iBlendMode, m_bLimOutput );
-#endif
 #endif
 
@@ -507,26 +498,4 @@
 
   // Render
-#if !RM_FIX_SETUP
-  m_apcRenModels[iModelNum]->setupLutAndRef(  pcPicYuvRefView, ppiShiftLutLeft, ppiBaseShiftLutLeft, ppiShiftLutRight, ppiBaseShiftLutRight, iDistToLeft, bAnyRefFromOrg );
-
-  // Setup with actual data  
-    for (Int iBaseViewIdx = 0; iBaseViewIdx < m_iNumOfBaseViews; iBaseViewIdx++ )
-    {
-      if ( m_aaeBaseViewPosInModel[iBaseViewIdx][iModelNum] != VIEWPOS_INVALID )
-      {
-        m_apcRenModels[iModelNum]->setLRView(
-          m_aaeBaseViewPosInModel[iBaseViewIdx][iModelNum],
-          m_aapiCurVideoPel      [iBaseViewIdx],
-          m_aaiCurVideoStrides   [iBaseViewIdx],
-          m_apiCurDepthPel       [iBaseViewIdx],
-          m_aiCurDepthStrides    [iBaseViewIdx]
-        );
-      }
-    }
-  // Render initial state
-  AOT( m_bLimOutput && m_aaeBaseViewPosInModel[ iEncViewSIdx ][iModelNum] == VIEWPOS_INVALID );
-  m_apcRenModels[iModelNum]->setupInitialState( m_bLimOutput ? m_aaeBaseViewPosInModel[ iEncViewSIdx ][iModelNum] : VIEWPOS_INVALID );  
-
-#else
   m_apcRenModels[iModelNum]->setupLut(  ppiShiftLutLeft, ppiBaseShiftLutLeft, ppiShiftLutRight, ppiBaseShiftLutRight, iDistToLeft );
   
@@ -587,5 +556,4 @@
     m_apcRenModels[iModelNum]->setLimOutStruct( (curViewPosInModel == VIEWPOS_RIGHT)  ? VIEWPOS_LEFT : VIEWPOS_RIGHT );
   }  
-#endif
 }
 
Index: /trunk/source/Lib/TLibRenderer/TRenSingleModel.cpp
===================================================================
--- /trunk/source/Lib/TLibRenderer/TRenSingleModel.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibRenderer/TRenSingleModel.cpp	(revision 1413)
@@ -246,19 +246,4 @@
 
 
-#if !RM_FIX_SETUP
-template <BlenMod iBM, Bool bBitInc> Void
-  TRenSingleModelC<iBM,bBitInc>::setupInitialState( Int curViewPosInModel )
-{
-  xRenderAll( );
-
-  if ( m_bLimOutput )
-  {
-    AOT( curViewPosInModel == VIEWPOS_INVALID )
-    xSetLimOutStruct( (curViewPosInModel == VIEWPOS_RIGHT)  ? VIEWPOS_LEFT : VIEWPOS_RIGHT );
-  }
-}
-#endif
-
-#if RM_FIX_SETUP
 template <BlenMod iBM, Bool bBitInc> Void
   TRenSingleModelC<iBM,bBitInc>::setupRefView      ( TComPicYuv* pcOrgVideo )
@@ -287,12 +272,5 @@
 template <BlenMod iBM, Bool bBitInc> Void
   TRenSingleModelC<iBM,bBitInc>::setupLut( Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight,  Int** ppiBaseShiftLutRight,  Int iDistToLeft )
-#else
-template <BlenMod iBM, Bool bBitInc> Void
-  TRenSingleModelC<iBM,bBitInc>::setupLutAndRef( TComPicYuv* pcOrgVideo, Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight,  Int** ppiBaseShiftLutRight,  Int iDistToLeft, Bool bRenderRef )
-#endif
-{
-#if !RM_FIX_SETUP
-  AOT( !m_bUseOrgRef && pcOrgVideo );
-#endif
+{
   AOT( (ppiShiftLutLeft  == NULL) && (m_iMode == 0 || m_iMode == 2) );
   AOT( (ppiShiftLutRight == NULL) && (m_iMode == 1 || m_iMode == 2) );
@@ -306,42 +284,11 @@
     TRenFilter<REN_BIT_DEPTH>::setupZLUT( true, 30, iDistToLeft, ppiBaseShiftLutLeft, ppiBaseShiftLutRight, m_iBlendZThres, m_iBlendDistWeight, m_piInvZLUTLeft, m_piInvZLUTRight );
   }
-
-#if !RM_FIX_SETUP
-  // Copy Reference
-  m_pcPicYuvRef = pcOrgVideo;
-
-  if ( pcOrgVideo )
-  {
-    assert( pcOrgVideo->getChromaFormat() == CHROMA_420 );     
-
-    TRenFilter<REN_BIT_DEPTH>::copy(             pcOrgVideo->getAddr( COMPONENT_Y  ) +  m_iHorOffset       * pcOrgVideo->getStride( COMPONENT_Y  ), pcOrgVideo->getStride( COMPONENT_Y  ), m_iWidth,      m_iUsedHeight,      m_aapiRefVideoPel[0], m_aiRefVideoStrides[0]);
-    TRenFilter<REN_BIT_DEPTH>::sampleCUpHorUp(0, pcOrgVideo->getAddr( COMPONENT_Cb ) + (m_iHorOffset >> 1) * pcOrgVideo->getStride( COMPONENT_Cb ), pcOrgVideo->getStride( COMPONENT_Cb ), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiRefVideoPel[1], m_aiRefVideoStrides[1]);
-    TRenFilter<REN_BIT_DEPTH>::sampleCUpHorUp(0, pcOrgVideo->getAddr( COMPONENT_Cr ) + (m_iHorOffset >> 1) * pcOrgVideo->getStride( COMPONENT_Cr ), pcOrgVideo->getStride( COMPONENT_Cr ), m_iWidth >> 1, m_iUsedHeight >> 1, m_aapiRefVideoPel[2], m_aiRefVideoStrides[2]);    
-    xSetStructRefView();
-  }
-  else
-  {
-    if ( bRenderRef )
-    {    
-      xRenderAll( ); 
-      xSetStructSynthViewAsRefView();
-    }
-  }
-#endif
-}
-
-template <BlenMod iBM, Bool bBitInc> Void
-#if RM_FIX_SETUP
+}
+
+template <BlenMod iBM, Bool bBitInc> Void
 TRenSingleModelC<iBM,bBitInc>::renderAll( )
-#else
-TRenSingleModelC<iBM,bBitInc>::xRenderAll( )
-#endif
 {
   // Initial Rendering
-#if RM_FIX_SETUP
   resetStructError();
-#else
-  xResetStructError();
-#endif
   xInitSampleStructs();
   switch ( m_iMode )
@@ -465,9 +412,5 @@
 
 template <BlenMod iBM, Bool bBitInc> Void
-#if RM_FIX_SETUP
 TRenSingleModelC<iBM,bBitInc>::resetStructError( )
-#else
-TRenSingleModelC<iBM,bBitInc>::xResetStructError( )
-#endif
 {
   RenModelOutPels* pcCurOutSampleRow = m_pcOutputSamples;
@@ -484,9 +427,5 @@
 
 template <BlenMod iBM, Bool bBitInc> Void
-#if RM_FIX_SETUP
   TRenSingleModelC<iBM,bBitInc>::setLimOutStruct(Int iSourceViewPos )
-#else
-  TRenSingleModelC<iBM,bBitInc>::xSetLimOutStruct(Int iSourceViewPos )
-#endif
 {  
   RM_AOF( m_bLimOutput ); 
@@ -537,9 +476,5 @@
 
 template <BlenMod iBM, Bool bBitInc> Void
-#if RM_FIX_SETUP
 TRenSingleModelC<iBM,bBitInc>::setStructSynthViewAsRefView( )
-#else
-TRenSingleModelC<iBM,bBitInc>::xSetStructSynthViewAsRefView( )
-#endif
 {
   AOT( m_iMode < 0 || m_iMode > 2);
Index: /trunk/source/Lib/TLibRenderer/TRenSingleModel.h
===================================================================
--- /trunk/source/Lib/TLibRenderer/TRenSingleModel.h	(revision 1412)
+++ /trunk/source/Lib/TLibRenderer/TRenSingleModel.h	(revision 1413)
@@ -78,5 +78,5 @@
   virtual Void   setLRView         ( Int iViewPos, Pel** apiCurVideoPel, Int* aiCurVideoStride, Pel* piCurDepthPel, Int iCurDepthStride ) = 0;
   virtual Void   setupPart         ( UInt uiHorOffset,       Int iUsedHeight ) = 0;
-#if RM_FIX_SETUP
+
   virtual Void   setupLut          ( Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight, Int** ppiBaseShiftLutRight, Int iDistToLeft ) = 0;
   virtual Void   setupRefView      ( TComPicYuv* pcOrgVideo ) = 0;
@@ -86,8 +86,4 @@
   virtual Void   resetStructError            ()                     = 0;
   virtual Void   setLimOutStruct             ( Int iSourceViewPos ) = 0; 
-#else
-  virtual Void   setupLutAndRef    ( TComPicYuv* pcOrgVideo, Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight, Int** ppiBaseShiftLutRight, Int iDistToLeft, Bool bRenderRef ) = 0;
-  virtual Void   setupInitialState ( Int curViewPosInModel ) = 0;
-#endif
 
   // Set Data
@@ -195,5 +191,5 @@
   Void   setLRView         ( Int iViewPos, Pel** apiCurVideoPel, Int* aiCurVideoStride, Pel* piCurDepthPel, Int iCurDepthStride );  
   Void   setupPart         ( UInt uiHorOffset,       Int uiUsedHeight ); 
-#if RM_FIX_SETUP
+
   Void   setupLut          (  Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight, Int** ppiBaseShiftLutRight, Int iDistToLeft);
   Void   setupRefView      ( TComPicYuv* pcOrgVideo );
@@ -203,8 +199,4 @@
   Void              resetStructError            ();
   Void              setLimOutStruct             ( Int iSourceViewPos ); 
-#else
-  Void   setupLutAndRef    ( TComPicYuv* pcOrgVideo, Int** ppiShiftLutLeft, Int** ppiBaseShiftLutLeft, Int** ppiShiftLutRight, Int** ppiBaseShiftLutRight, Int iDistToLeft, Bool bRenderRef );
-  Void   setupInitialState ( Int curViewPosInModel );
-#endif
 
 
@@ -229,8 +221,4 @@
 
 private:
-
-#if !RM_FIX_SETUP
-   __inline Void  xRenderAll( );
-#endif
 
 
@@ -310,13 +298,5 @@
        
   Void            xSetStructRefView            ();
-#if !RM_FIX_SETUP
-  Void            xResetStructError            ();
-  Void            xSetLimOutStruct             (Int iSourceViewPos ); 
-#endif
-  
   Void            xInitSampleStructs           ();
-#if !RM_FIX_SETUP
-  Void            xSetStructSynthViewAsRefView ();
-#endif
   Void            xCopy2PicYuv                ( Pel** ppiSrcVideoPel, Int* piStrides, TComPicYuv* rpcPicYuvTarget );
 
Index: /trunk/source/Lib/TLibVideoIO/TVideoIOYuv.cpp
===================================================================
--- /trunk/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 1412)
+++ /trunk/source/Lib/TLibVideoIO/TVideoIOYuv.cpp	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -186,7 +186,7 @@
  * seekable, by consuming bytes.
  */
-Void TVideoIOYuv::skipFrames(UInt numFrames, UInt width, UInt height, ChromaFormat format)
-{
-  if (!numFrames)
+Void TVideoIOYuv::skipFrames(Int numFrames, UInt width, UInt height, ChromaFormat format)
+{
+  if (numFrames==0)
   {
     return;
@@ -733,5 +733,8 @@
   }
 
+  if(pPicYuvUser)
+  {
   ColourSpaceConvert(*pPicYuvTrueOrg, *pPicYuvUser, ipcsc, true);
+  }
 
   return true;
Index: /trunk/source/Lib/TLibVideoIO/TVideoIOYuv.h
===================================================================
--- /trunk/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 1412)
+++ /trunk/source/Lib/TLibVideoIO/TVideoIOYuv.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
@@ -67,5 +67,5 @@
   Void  close ();                                           ///< close file
 
-  Void skipFrames(UInt numFrames, UInt width, UInt height, ChromaFormat format);
+  Void skipFrames(Int numFrames, UInt width, UInt height, ChromaFormat format);
 
   // if fileFormat<NUM_CHROMA_FORMAT, the format of the file is that format specified, else it is the format of the TComPicYuv.
Index: /trunk/source/Lib/libmd5/MD5.h
===================================================================
--- /trunk/source/Lib/libmd5/MD5.h	(revision 1412)
+++ /trunk/source/Lib/libmd5/MD5.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.
  *
- * Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
Index: /trunk/source/Lib/libmd5/libmd5.h
===================================================================
--- /trunk/source/Lib/libmd5/libmd5.h	(revision 1412)
+++ /trunk/source/Lib/libmd5/libmd5.h	(revision 1413)
@@ -4,5 +4,5 @@
  * granted under this license.  
  *
-* Copyright (c) 2010-2016, ITU/ISO/IEC
+ * Copyright (c) 2010-2017, ITU/ISO/IEC
  * All rights reserved.
  *
